Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,996 @@
//! Authentication step UI and state transitions used by onboarding.
//!
//! This module owns the auth-step state machine (ChatGPT login/device-code/API
//! key), renders the corresponding UI, and handles auth-scoped keyboard input.
//! It intentionally does not decide onboarding flow completion; the enclosing
//! onboarding screen coordinates step progression.
#![allow(clippy::unwrap_used)]
use akode_app_server_client::AppServerRequestHandle;
use akode_app_server_protocol::AccountUpdatedNotification;
use akode_app_server_protocol::AuthMode as ApiAuthMode;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::LoginAccountParams;
use akode_app_server_protocol::LoginAccountResponse;
use akode_login::AuthConfig;
use akode_login::read_openai_api_key_from_env;
use akode_protocol::auth::AuthMode;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Constraint;
use ratatui::layout::Layout;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Block;
use ratatui::widgets::BorderType;
use ratatui::widgets::Borders;
use ratatui::widgets::Paragraph;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
use akode_protocol::config_types::ForcedLoginMethod;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Instant;
use uuid::Uuid;
use crate::LoginStatus;
use crate::activation_key_guard::ActivationKeyGuard;
use crate::key_hint::KeyBinding;
use crate::key_hint::KeyBindingListExt;
use crate::onboarding::gateway::GatewayStep;
use crate::onboarding::gateway::USE_CUSTOM_PROVIDER;
use crate::onboarding::keys;
use crate::onboarding::onboarding_screen::KeyboardHandler;
use crate::onboarding::onboarding_screen::StepStateProvider;
use crate::tui::FrameRequester;
/// Marks buffer cells that have cyan+underlined style as an OSC 8 hyperlink.
///
/// Terminal emulators recognise the OSC 8 escape sequence and treat the entire
/// marked region as a single clickable link, regardless of row wrapping. This
/// is necessary because ratatui's cell-based rendering emits `MoveTo` at every
/// row boundary, which breaks normal terminal URL detection for long URLs that
/// wrap across multiple rows.
pub(crate) fn mark_url_hyperlink(buf: &mut Buffer, area: Rect, url: &str) {
crate::terminal_hyperlinks::mark_url_hyperlink(buf, area, url);
}
use super::onboarding_screen::StepState;
#[derive(Clone)]
pub(crate) enum SignInState {
PickMode,
ApiKeyEntry(ApiKeyInputState),
ApiKeyConfigured,
GatewaySelected(String),
GatewayOAuth {
provider_id: String,
url: Option<String>,
},
GatewayOAuthFailed {
provider_id: String,
message: String,
},
GatewayConfigured,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SignInOption {
ApiKey,
Gateway,
}
const API_KEY_DISABLED_MESSAGE: &str = "API key login is disabled.";
pub(super) fn onboarding_request_id() -> akode_app_server_protocol::RequestId {
akode_app_server_protocol::RequestId::String(Uuid::new_v4().to_string())
}
#[derive(Clone, Default)]
pub(crate) struct ApiKeyInputState {
value: String,
prepopulated_from_env: bool,
}
impl KeyboardHandler for AuthModeWidget {
fn handle_key_event(&mut self, key_event: KeyEvent) {
if self
.activation_key_guard
.as_mut()
.is_some_and(|guard| guard.consume(KeyBinding::from_event(key_event), key_event.kind))
|| key_event.kind == KeyEventKind::Release
{
return;
}
if self.handle_gateway_key_event(key_event) {
return;
}
if self.handle_api_key_entry_key_event(&key_event) {
return;
}
if keys::MOVE_UP.is_pressed(key_event) {
self.move_highlight(/*delta*/ -1);
return;
}
if keys::MOVE_DOWN.is_pressed(key_event) {
self.move_highlight(/*delta*/ 1);
return;
}
if key_event.kind != KeyEventKind::Press {
return;
}
if keys::SELECT_FIRST.is_pressed(key_event) {
self.select_option_by_index(/*index*/ 0, key_event);
return;
}
if keys::SELECT_SECOND.is_pressed(key_event) {
self.select_option_by_index(/*index*/ 1, key_event);
return;
}
if keys::SELECT_THIRD.is_pressed(key_event) {
self.select_option_by_index(/*index*/ 2, key_event);
return;
}
if keys::SELECT_FOURTH.is_pressed(key_event) {
self.select_option_by_index(/*index*/ 3, key_event);
return;
}
if keys::CONFIRM.is_pressed(key_event) {
let sign_in_state = { (*self.sign_in_state.read().unwrap()).clone() };
match sign_in_state {
SignInState::GatewayOAuthFailed { provider_id, .. } => {
self.start_gateway_oauth(provider_id)
}
SignInState::PickMode => {
self.activate_highlighted_mode(key_event);
}
_ => {}
}
}
}
fn handle_paste(&mut self, pasted: String) {
if let Some(wizard) = &mut self.gateway {
if let Some(input) = wizard.active_input_mut() {
input.paste(&pasted);
self.request_frame.schedule_frame();
}
return;
}
let is_api_key_entry = matches!(
*self.sign_in_state.read().unwrap(),
SignInState::ApiKeyEntry(_)
);
if is_api_key_entry {
let _ = self.handle_api_key_entry_paste(pasted);
}
}
}
#[allow(dead_code)]
pub(crate) struct AuthModeWidget {
pub request_frame: FrameRequester,
pub highlighted_mode: SignInOption,
pub(super) activation_key_guard: Option<ActivationKeyGuard>,
pub error: Arc<RwLock<Option<String>>>,
pub sign_in_state: Arc<RwLock<SignInState>>,
pub login_status: LoginStatus,
pub app_server_target: crate::AppServerTarget,
pub app_server_request_handle: AppServerRequestHandle,
pub auth_config: AuthConfig,
pub gateway_setup_enabled: bool,
pub(super) gateway: Option<GatewayStep>,
}
impl AuthModeWidget {
pub(super) fn set_error(&self, message: Option<String>) {
*self.error.write().unwrap() = message;
}
fn error_message(&self) -> Option<String> {
self.error.read().unwrap().clone()
}
/// Returns whether the auth flow is currently accepting text input.
pub(crate) fn is_text_entry_active(&self) -> bool {
if let Some(wizard) = &self.gateway {
return wizard.is_text_entry_active();
}
self.sign_in_state.read().is_ok_and(|guard| match &*guard {
SignInState::ApiKeyEntry(_) => true,
_ => false,
})
}
/// Returns whether printable quit shortcuts must be treated as text input.
///
/// API-key entry keeps its existing empty-field quit behavior, while
/// provider setup fields accept printable input from their first character.
pub(crate) fn should_suppress_printable_quit(&self) -> bool {
if let Some(wizard) = &self.gateway {
return wizard.is_text_entry_active();
}
self.sign_in_state.read().is_ok_and(|guard| match &*guard {
SignInState::ApiKeyEntry(state) => !state.value.is_empty(),
_ => false,
})
}
fn confirm_binding(&self) -> KeyBinding {
keys::CONFIRM[0]
}
fn cancel_binding(&self) -> KeyBinding {
keys::CANCEL[0]
}
fn is_api_login_allowed(&self) -> bool {
self.auth_config
.is_login_method_allowed(ForcedLoginMethod::Api)
}
fn displayed_sign_in_options(&self) -> Vec<SignInOption> {
let mut options = vec![SignInOption::ApiKey];
if self.gateway_setup_enabled {
options.push(SignInOption::Gateway);
}
options
}
fn move_highlight(&mut self, delta: isize) {
if !matches!(*self.sign_in_state.read().unwrap(), SignInState::PickMode) {
return;
}
let options = self.displayed_sign_in_options();
if options.is_empty() {
return;
}
let current_index = options
.iter()
.position(|option| *option == self.highlighted_mode)
.unwrap_or(0);
let next_index =
(current_index as isize + delta).rem_euclid(options.len() as isize) as usize;
self.highlighted_mode = options[next_index];
}
fn select_option_by_index(&mut self, index: usize, key_event: KeyEvent) {
if !matches!(*self.sign_in_state.read().unwrap(), SignInState::PickMode) {
return;
}
let options = self.displayed_sign_in_options();
if let Some(option) = options.get(index).copied() {
self.highlighted_mode = option;
self.activate_highlighted_mode(key_event);
}
}
fn activate_highlighted_mode(&mut self, key_event: KeyEvent) {
let option = self.highlighted_mode;
self.guard_activation(key_event);
self.handle_sign_in_option(option);
}
pub(super) fn guard_activation(&mut self, key_event: KeyEvent) {
// Enter and printable shortcuts can repeat as plain presses without a release.
self.activation_key_guard = Some(ActivationKeyGuard::new_at(
KeyBinding::from_event(key_event),
Instant::now(),
/*reported_repeats_only*/ false,
));
}
fn handle_sign_in_option(&mut self, option: SignInOption) {
match option {
SignInOption::ApiKey => {
if self.is_api_login_allowed() {
self.start_api_key_entry();
} else {
self.disallow_api_login();
}
}
SignInOption::Gateway => {
if self.gateway_setup_enabled && self.is_api_login_allowed() {
self.start_gateway_picker();
} else if !self.is_api_login_allowed() {
self.disallow_api_login();
}
}
}
}
fn disallow_api_login(&mut self) {
self.highlighted_mode = SignInOption::ApiKey;
self.set_error(Some(API_KEY_DISABLED_MESSAGE.to_string()));
*self.sign_in_state.write().unwrap() = SignInState::PickMode;
self.request_frame.schedule_frame();
}
fn render_pick_mode(&self, area: Rect, buf: &mut Buffer) {
let mut lines: Vec<Line> = if self.gateway_setup_enabled {
vec![" Choose how you want to use Codex.".into(), "".into()]
} else {
vec![" Connect an API key to use Codex.".into(), "".into()]
};
let options_start = lines.len();
let mut compact_options = Vec::new();
let mut create_mode_item = |idx: usize,
selected_mode: SignInOption,
text: &str,
description: &str|
-> Vec<Line<'static>> {
let is_selected = self.highlighted_mode == selected_mode;
let caret = if is_selected { ">" } else { " " };
let line1 = if is_selected {
Line::from(vec![
format!("{caret} {index}. ", index = idx + 1).cyan().dim(),
text.to_string().cyan(),
])
} else {
format!(" {index}. {text}", index = idx + 1).into()
};
let line2 = if is_selected {
Line::from(format!(" {description}"))
.fg(Color::Cyan)
.add_modifier(Modifier::DIM)
} else {
Line::from(format!(" {description}"))
.style(Style::default().add_modifier(Modifier::DIM))
};
compact_options.push(line1.clone());
vec![line1, line2]
};
for (idx, option) in self.displayed_sign_in_options().into_iter().enumerate() {
match option {
SignInOption::ApiKey => {
lines.extend(create_mode_item(
idx,
option,
"Use an OpenAI API key",
"Pay for what you use",
));
}
SignInOption::Gateway => {
lines.extend(create_mode_item(
idx,
option,
USE_CUSTOM_PROVIDER,
"Choose a saved configuration or create a new one",
));
}
}
lines.push("".into());
}
let options_end = lines.len();
if !self.is_api_login_allowed() {
lines.push(
" API key login is disabled by your administrator."
.dim()
.into(),
);
lines.push("".into());
}
lines.push(Line::from(vec![
" Press ".dim(),
self.confirm_binding().into(),
" to continue".dim(),
]));
if let Some(err) = self.error_message() {
lines.push("".into());
lines.push(err.red().into());
}
// Keep the options and confirmation hint visible in short terminals.
if Paragraph::new(lines.clone())
.wrap(Wrap { trim: false })
.line_count(area.width)
> usize::from(area.height)
{
lines.splice(options_start..options_end, compact_options);
}
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
}
fn render_api_key_configured(&self, area: Rect, buf: &mut Buffer) {
let lines = vec![
"✓ API key configured".fg(Color::Green).into(),
"".into(),
" aKode will use usage-based billing with your API key.".into(),
];
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
}
fn render_api_key_entry(&self, area: Rect, buf: &mut Buffer, state: &ApiKeyInputState) {
let [intro_area, input_area, footer_area] = Layout::vertical([
Constraint::Min(4),
Constraint::Length(3),
Constraint::Min(2),
])
.areas(area);
let mut intro_lines: Vec<Line> = vec![
Line::from(vec![
"> ".into(),
"Use your own OpenAI API key for usage-based billing".bold(),
]),
"".into(),
" Paste or type your API key below.".into(),
"".into(),
];
if state.prepopulated_from_env {
intro_lines.push(" Detected OPENAI_API_KEY environment variable.".into());
intro_lines.push(
" Paste a different key if you prefer to use another account."
.dim()
.into(),
);
intro_lines.push("".into());
}
Paragraph::new(intro_lines)
.wrap(Wrap { trim: false })
.render(intro_area, buf);
let content_line: Line = if state.value.is_empty() {
vec!["Paste or type your API key".dim()].into()
} else {
Line::from(state.value.clone())
};
Paragraph::new(content_line)
.wrap(Wrap { trim: false })
.block(
Block::default()
.title("API key")
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(Color::Cyan)),
)
.render(input_area, buf);
let mut footer_lines: Vec<Line> = vec![
Line::from(vec![
" Press ".dim(),
self.confirm_binding().into(),
" to save".dim(),
]),
Line::from(vec![
" Press ".dim(),
self.cancel_binding().into(),
" to go back".dim(),
]),
];
if let Some(error) = self.error_message() {
footer_lines.push("".into());
footer_lines.push(error.red().into());
}
Paragraph::new(footer_lines)
.wrap(Wrap { trim: false })
.render(footer_area, buf);
}
fn handle_api_key_entry_key_event(&mut self, key_event: &KeyEvent) -> bool {
let mut should_save: Option<String> = None;
let mut should_request_frame = false;
{
let mut guard = self.sign_in_state.write().unwrap();
if let SignInState::ApiKeyEntry(state) = &mut *guard {
if keys::CANCEL.is_pressed(*key_event) {
*guard = SignInState::PickMode;
self.set_error(/*message*/ None);
should_request_frame = true;
} else if key_event.kind == KeyEventKind::Press
&& keys::CONFIRM.is_pressed(*key_event)
{
let trimmed = state.value.trim().to_string();
if trimmed.is_empty() {
self.set_error(Some("API key cannot be empty".to_string()));
should_request_frame = true;
} else {
should_save = Some(trimmed);
}
} else {
match key_event.code {
KeyCode::Backspace => {
if state.prepopulated_from_env {
state.value.clear();
state.prepopulated_from_env = false;
} else {
state.value.pop();
}
self.set_error(/*message*/ None);
should_request_frame = true;
}
KeyCode::Char(c)
if key_event.kind == KeyEventKind::Press
&& !key_event.modifiers.contains(KeyModifiers::SUPER)
&& !key_event.modifiers.contains(KeyModifiers::CONTROL)
&& !key_event.modifiers.contains(KeyModifiers::ALT) =>
{
if state.prepopulated_from_env {
state.value.clear();
state.prepopulated_from_env = false;
}
state.value.push(c);
self.set_error(/*message*/ None);
should_request_frame = true;
}
_ => {}
}
}
// handled; let guard drop before potential save
} else {
return false;
}
}
if let Some(api_key) = should_save {
self.save_api_key(api_key);
} else if should_request_frame {
self.request_frame.schedule_frame();
}
true
}
fn handle_api_key_entry_paste(&mut self, pasted: String) -> bool {
let trimmed = pasted.trim();
if trimmed.is_empty() {
return false;
}
let mut guard = self.sign_in_state.write().unwrap();
if let SignInState::ApiKeyEntry(state) = &mut *guard {
if state.prepopulated_from_env {
state.value = trimmed.to_string();
state.prepopulated_from_env = false;
} else {
state.value.push_str(trimmed);
}
self.set_error(/*message*/ None);
} else {
return false;
}
drop(guard);
self.request_frame.schedule_frame();
true
}
pub(super) fn start_api_key_entry(&mut self) {
if !self.is_api_login_allowed() {
self.disallow_api_login();
return;
}
self.set_error(/*message*/ None);
let prefill_from_env = read_openai_api_key_from_env();
let mut guard = self.sign_in_state.write().unwrap();
match &mut *guard {
SignInState::ApiKeyEntry(state) => {
if state.value.is_empty() {
if let Some(prefill) = prefill_from_env {
state.value = prefill;
state.prepopulated_from_env = true;
} else {
state.prepopulated_from_env = false;
}
}
}
_ => {
*guard = SignInState::ApiKeyEntry(ApiKeyInputState {
value: prefill_from_env.clone().unwrap_or_default(),
prepopulated_from_env: prefill_from_env.is_some(),
});
}
}
drop(guard);
self.request_frame.schedule_frame();
}
fn save_api_key(&mut self, api_key: String) {
if !self.is_api_login_allowed() {
self.disallow_api_login();
return;
}
self.set_error(/*message*/ None);
let request_handle = self.app_server_request_handle.clone();
let sign_in_state = self.sign_in_state.clone();
let error = self.error.clone();
let request_frame = self.request_frame.clone();
tokio::spawn(async move {
match request_handle
.request_typed::<LoginAccountResponse>(ClientRequest::LoginAccount {
request_id: onboarding_request_id(),
params: LoginAccountParams::ApiKey {
api_key: api_key.clone(),
},
})
.await
{
Ok(LoginAccountResponse::ApiKey {}) => {
*error.write().unwrap() = None;
*sign_in_state.write().unwrap() = SignInState::ApiKeyConfigured;
}
Err(err) => {
*error.write().unwrap() = Some(format!("Failed to save API key: {err}"));
*sign_in_state.write().unwrap() = SignInState::ApiKeyEntry(ApiKeyInputState {
value: api_key,
prepopulated_from_env: false,
});
}
}
request_frame.schedule_frame();
});
self.request_frame.schedule_frame();
}
pub(crate) fn on_account_updated(&mut self, notification: AccountUpdatedNotification) {
self.login_status = notification
.auth_mode
.map(|auth_mode| {
LoginStatus::AuthMode(match auth_mode {
ApiAuthMode::ApiKey => AuthMode::ApiKey,
ApiAuthMode::Headers => AuthMode::Headers,
})
})
.unwrap_or(LoginStatus::NotAuthenticated);
}
}
impl StepStateProvider for AuthModeWidget {
fn get_step_state(&self) -> StepState {
let sign_in_state = self.sign_in_state.read().unwrap();
match &*sign_in_state {
SignInState::PickMode
| SignInState::ApiKeyEntry(_)
| SignInState::GatewayOAuth { .. }
| SignInState::GatewayOAuthFailed { .. } => StepState::InProgress,
SignInState::ApiKeyConfigured
| SignInState::GatewaySelected(_)
| SignInState::GatewayConfigured => StepState::Complete,
}
}
}
impl WidgetRef for AuthModeWidget {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
if let Some(wizard) = &self.gateway {
wizard.render(area, buf);
return;
}
let sign_in_state = self.sign_in_state.read().unwrap();
match &*sign_in_state {
SignInState::PickMode => {
self.render_pick_mode(area, buf);
}
SignInState::ApiKeyEntry(state) => {
self.render_api_key_entry(area, buf, state);
}
SignInState::ApiKeyConfigured => {
self.render_api_key_configured(area, buf);
}
SignInState::GatewayOAuth { url, .. } => {
let mut lines = vec![Line::from(
"Finish signing in to your gateway in the browser.".bold(),
)];
if let Some(url) = url {
lines.push(Line::from(url.clone().cyan().underlined()));
}
lines.push(Line::from("Press Ctrl+C to quit.".dim()));
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
if let Some(url) = url {
mark_url_hyperlink(buf, area, url);
}
}
SignInState::GatewayOAuthFailed { message, .. } => {
Paragraph::new(vec![
Line::from(message.clone().red()),
Line::from("Press Enter to retry or Ctrl+C to quit.".dim()),
])
.wrap(Wrap { trim: false })
.render(area, buf);
}
SignInState::GatewaySelected(_) | SignInState::GatewayConfigured => {
Paragraph::new("✓ Custom provider configured".green())
.wrap(Wrap { trim: false })
.render(area, buf);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::legacy_core::config::ConfigBuilder;
use akode_app_server_client::AppServerRequestHandle;
use akode_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY;
use akode_app_server_client::InProcessAppServerClient;
use akode_app_server_client::InProcessClientStartArgs;
use akode_arg0::Arg0DispatchPaths;
use akode_config::LoaderOverrides;
use akode_features::Feature;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use tempfile::TempDir;
pub(super) async fn widget_api_login_forbidden() -> (AuthModeWidget, TempDir) {
let codex_home = TempDir::new().unwrap();
let codex_home_path = codex_home.path().to_path_buf();
// Embedded startup can refresh configuration after first paint.
let loader_overrides = LoaderOverrides {
ignore_managed_requirements: true,
managed_config_path: Some(codex_home_path.join("managed_config.toml")),
..LoaderOverrides::without_managed_config_for_tests()
};
let config = ConfigBuilder::default()
.loader_overrides(loader_overrides.clone())
.codex_home(codex_home_path.clone())
.build()
.await
.unwrap();
let mut auth_config = config.auth_config();
let client = InProcessAppServerClient::start(InProcessClientStartArgs {
required_human_approval: true,
arg0_paths: Arg0DispatchPaths::default(),
config: Arc::new(config),
cli_overrides: Vec::new(),
loader_overrides,
strict_config: false,
embedded_network_policy: Default::default(),
feedback: akode_feedback::CodexFeedback::new(),
log_db: None,
state_db: None,
environment_manager: Arc::new(
akode_app_server_client::EnvironmentManager::default_for_tests(),
),
config_warnings: Vec::new(),
session_source: serde_json::from_value(serde_json::json!("cli"))
.expect("cli session source should deserialize"),
enable_codex_api_key_env: false,
client_name: "test".to_string(),
client_version: "test".to_string(),
experimental_api: true,
mcp_server_openai_form_elicitation: false,
opt_out_notification_methods: Vec::new(),
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
})
.await
.unwrap();
// A non-API login method forbids API keys; it can no longer select ChatGPT.
auth_config.forced_login_method = Some(ForcedLoginMethod::Chatgpt);
let widget = AuthModeWidget {
request_frame: FrameRequester::test_dummy(),
highlighted_mode: SignInOption::ApiKey,
activation_key_guard: None,
error: Arc::new(RwLock::new(None)),
sign_in_state: Arc::new(RwLock::new(SignInState::PickMode)),
login_status: LoginStatus::NotAuthenticated,
app_server_target: crate::AppServerTarget::Embedded,
app_server_request_handle: AppServerRequestHandle::InProcess(client.request_handle()),
auth_config,
gateway_setup_enabled: false,
gateway: None,
};
(widget, codex_home)
}
#[tokio::test]
async fn api_key_entry_snapshots() {
let (mut widget, _tmp) = widget_api_login_forbidden().await;
widget.auth_config.forced_login_method = None;
*widget.sign_in_state.write().unwrap() =
SignInState::ApiKeyEntry(ApiKeyInputState::default());
for (name, width) in [("api_key_entry", 80), ("api_key_entry_narrow", 40)] {
let height = 14;
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut terminal = crate::custom_terminal::Terminal::with_options(
crate::test_backend::VT100Backend::new(width, height),
)
.expect("terminal");
terminal.set_viewport_area(area);
terminal
.draw(|frame| widget.render_ref(area, frame.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(name, terminal.backend().to_string());
}
}
#[tokio::test]
async fn api_key_flow_disabled_when_api_login_forbidden() {
let (mut widget, _tmp) = widget_api_login_forbidden().await;
widget.start_api_key_entry();
assert_eq!(
widget.error_message().as_deref(),
Some(API_KEY_DISABLED_MESSAGE)
);
assert!(matches!(
&*widget.sign_in_state.read().unwrap(),
SignInState::PickMode
));
}
#[tokio::test]
async fn gateway_option_requires_feature_and_api_login_permission() {
let (mut widget, codex_home) = widget_api_login_forbidden().await;
widget.auth_config.forced_login_method = None;
assert_eq!(
widget.displayed_sign_in_options(),
vec![SignInOption::ApiKey]
);
std::fs::write(
codex_home.path().join("config.toml"),
"[features]\ngateway_setup_wizard = true\n",
)
.unwrap();
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.unwrap();
widget.gateway_setup_enabled = crate::should_show_provider_setup_wizard(
widget.login_status,
/*requires_openai_auth*/ true,
&config,
&widget.app_server_target,
Feature::GatewaySetupWizard,
);
assert_eq!(
widget.displayed_sign_in_options(),
vec![SignInOption::ApiKey, SignInOption::Gateway]
);
widget.move_highlight(/*delta*/ 1);
let area = Rect::new(0, 0, 76, 19);
let mut buffer = Buffer::empty(area);
widget.render_pick_mode(area, &mut buffer);
let mut rows = (area.top()..area.bottom())
.map(|row| {
(area.left()..area.right())
.map(|column| buffer[(column, row)].symbol())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>();
while rows.last().is_some_and(String::is_empty) {
rows.pop();
}
insta::assert_snapshot!(rows.join("\n"), @r###"
Choose how you want to use aKode.
1. Use an OpenAI API key
Pay for what you use
> 2. Use a custom provider or gateway
Choose a saved configuration or create a new one
Press enter to continue
"###);
}
#[tokio::test]
async fn saving_api_key_is_blocked_when_api_login_forbidden() {
let (mut widget, _tmp) = widget_api_login_forbidden().await;
widget.save_api_key("sk-test".to_string());
assert_eq!(
widget.error_message().as_deref(),
Some(API_KEY_DISABLED_MESSAGE)
);
assert!(matches!(
&*widget.sign_in_state.read().unwrap(),
SignInState::PickMode
));
assert_eq!(widget.login_status, LoginStatus::NotAuthenticated);
}
/// Collects all buffer cell symbols that contain the OSC 8 open sequence
/// for the given URL. Returns the concatenated "inner" characters.
fn collect_osc8_chars(buf: &Buffer, area: Rect, url: &str) -> String {
let open = format!("\x1B]8;;{url}\x07");
let close = "\x1B]8;;\x07";
let mut chars = String::new();
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
let sym = buf[(x, y)].symbol();
if let Some(rest) = sym.strip_prefix(open.as_str())
&& let Some(ch) = rest.strip_suffix(close)
{
chars.push_str(ch);
}
}
}
chars
}
#[test]
fn mark_url_hyperlink_wraps_cyan_underlined_cells() {
let url = "https://example.com";
let area = Rect::new(0, 0, 20, 1);
let mut buf = Buffer::empty(area);
// Manually write some cyan+underlined characters to simulate a rendered URL.
for (i, ch) in "example".chars().enumerate() {
let cell = &mut buf[(i as u16, 0)];
cell.set_symbol(&ch.to_string());
cell.fg = Color::Cyan;
cell.modifier = Modifier::UNDERLINED;
}
// Leave a plain cell that should NOT be marked.
buf[(7, 0)].set_symbol("X");
mark_url_hyperlink(&mut buf, area, url);
// Each cyan+underlined cell should now carry the OSC 8 wrapper.
let found = collect_osc8_chars(&buf, area, url);
assert_eq!(found, "example");
// The plain "X" cell should be untouched.
assert_eq!(buf[(7, 0)].symbol(), "X");
}
#[test]
fn mark_url_hyperlink_sanitizes_control_chars() {
let area = Rect::new(0, 0, 10, 1);
let mut buf = Buffer::empty(area);
// One cyan+underlined cell to mark.
let cell = &mut buf[(0, 0)];
cell.set_symbol("a");
cell.fg = Color::Cyan;
cell.modifier = Modifier::UNDERLINED;
// URL contains ESC and BEL that could break the OSC 8 sequence.
let malicious_url = "https://evil.com/\x1B]8;;\x07injected";
mark_url_hyperlink(&mut buf, area, malicious_url);
let sym = buf[(0, 0)].symbol().to_string();
// The sanitized URL retains `]` (printable) but strips ESC and BEL.
let sanitized = "https://evil.com/]8;;injected";
assert!(
sym.contains(sanitized),
"symbol should contain sanitized URL, got: {sym:?}"
);
// The injected close-sequence must not survive: \x1B and \x07 are gone.
assert!(
!sym.contains("\x1B]8;;\x07injected"),
"symbol must not contain raw control chars from URL"
);
}
}
#[cfg(test)]
mod activation_key_tests;
#[cfg(test)]
#[path = "gateway_tests.rs"]
mod gateway_tests;

View File

@@ -0,0 +1,43 @@
#![cfg(test)]
//! Regression coverage for a key held across the sign-in menus.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn held_enter_requires_a_fresh_confirmation_to_save_a_prefilled_api_key() {
let (mut widget, _home) = tests::widget_api_login_forbidden().await;
widget.auth_config.forced_login_method = None;
let enter = |kind| KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, kind);
assert_eq!(widget.highlighted_mode, SignInOption::ApiKey);
widget.handle_key_event(enter(KeyEventKind::Press));
{
let mut state = widget.sign_in_state.write().unwrap();
let SignInState::ApiKeyEntry(input) = &mut *state else {
panic!("expected API key entry");
};
input.value = "test-api-key".into();
input.prepopulated_from_env = true;
}
let (request_frame, mut frames) = FrameRequester::test_channel();
widget.request_frame = request_frame;
widget.handle_key_event(enter(KeyEventKind::Press));
widget.handle_key_event(enter(KeyEventKind::Repeat));
widget.handle_key_event(KeyCode::Left.into());
widget.handle_key_event(enter(KeyEventKind::Repeat));
assert_eq!(
frames.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
);
widget.handle_key_event(enter(KeyEventKind::Release));
widget.handle_key_event(enter(KeyEventKind::Press));
frames.try_recv().expect("fresh Enter should start saving");
frames.recv().await.expect("API key save should finish");
assert!(matches!(
*widget.sign_in_state.read().unwrap(),
SignInState::ApiKeyConfigured
));
}

View File

@@ -0,0 +1,152 @@
//! Folder consent for startup and task navigation.
//! Local daemon resumes recheck folders changed during consent. Remote checks
//! retain their existing explicit-cwd scope until authoritative roots are available.
use super::OnboardingResult;
use super::OnboardingScreen;
use super::Step;
use super::run_onboarding_screen;
use crate::AppServerTarget;
use crate::app_server_session::AppServerSession;
use crate::config_update::ProjectTrustHost;
use crate::config_update::read_remote_project_trust;
use crate::legacy_core::config::Config;
use crate::onboarding::trust_directory::TrustCancelAction;
use crate::onboarding::trust_directory::TrustDirectorySelection;
use crate::onboarding::trust_directory::TrustDirectoryWidget;
use crate::startup_draft::StartupDraftPump;
use crate::tui::Tui;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::RequestId;
use akode_app_server_protocol::Thread;
use akode_app_server_protocol::ThreadReadParams;
use akode_app_server_protocol::ThreadReadResponse;
use akode_protocol::config_types::TrustLevel;
use color_eyre::eyre::Result;
use std::collections::VecDeque;
use std::path::Path;
use uuid::Uuid;
#[derive(Clone, Copy, Default)]
pub(crate) struct DirectoryTrustOptions<'a> {
pub resumed_thread: Option<&'a Thread>,
pub cancel: Option<TrustCancelAction>,
}
pub(crate) async fn check_directory_trust(
tui: &mut Tui,
app_server: &AppServerSession,
config: &Config,
target: &AppServerTarget,
cwd: &Path,
options: DirectoryTrustOptions<'_>,
mut startup_draft: Option<&mut StartupDraftPump>,
) -> Result<OnboardingResult> {
let DirectoryTrustOptions {
resumed_thread,
cancel,
} = options;
let connected = !matches!(target, AppServerTarget::Embedded);
let mut consent = OnboardingResult::default();
// Another client can load the saved task while consent is pending. Check both folders.
let saved_cwd = resumed_thread
.filter(|thread| {
matches!(target, AppServerTarget::LocalDaemon { .. }) && thread.cwd.as_path() != cwd
})
.map(|thread| thread.cwd.as_path());
let mut pending_cwds: VecDeque<_> = std::iter::once(cwd)
.chain(saved_cwd)
.map(Path::to_path_buf)
.collect();
let mut checked_cwds = Vec::new();
while let Some(cwd) = pending_cwds.pop_front() {
if checked_cwds.contains(&cwd) {
continue;
}
checked_cwds.push(cwd.clone());
let cwd = cwd.as_path();
let host = if !target.uses_remote_workspace() {
ProjectTrustHost::Local
} else {
ProjectTrustHost::Remote
};
let lookup = read_remote_project_trust(app_server.request_handle(), cwd, host);
let project = if let Some(draft) = startup_draft.as_deref_mut() {
draft.run_until(tui, lookup).await??
} else {
lookup.await?
};
let Some(project) = project else {
continue;
};
// Remote connections retain the existing behavior for saved untrusted folders.
if target.uses_remote_workspace() && project.trust_level == Some(TrustLevel::Untrusted) {
continue;
}
if cancel == Some(TrustCancelAction::CurrentTask)
&& project.trust_level == Some(TrustLevel::Untrusted)
&& !config.active_project.is_untrusted()
{
color_eyre::eyre::bail!(
"Folder trust changed. Reopen the destination with its restricted settings."
);
}
let remote_trust_key =
connected.then(|| project.trust_target.to_string_lossy().into_owned());
if let Some(draft) = startup_draft.as_deref_mut() {
draft.flush_pending_events(tui).await?;
}
let screen = OnboardingScreen {
request_frame: tui.frame_requester(),
steps: vec![Step::TrustDirectory(TrustDirectoryWidget {
restricted: project.trust_level == Some(TrustLevel::Untrusted),
existing_task: connected && resumed_thread.is_some(),
cancel: cancel.unwrap_or(TrustCancelAction::AgentsOverview),
cwd: project.cwd,
trust_target: project.trust_target,
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Trust,
error: None,
})],
remote_trust_key,
is_done: false,
should_exit: false,
};
let result = run_onboarding_screen(
screen,
Some(app_server.request_handle()),
/*app_server*/ None,
tui,
)
.await?;
tui.terminal.clear()?;
tui.frame_requester().schedule_frame();
if result.should_exit {
return Ok(result);
}
consent.directory_trust_persisted |= result.directory_trust_persisted;
if matches!(target, AppServerTarget::LocalDaemon { .. })
&& let Some(thread) = resumed_thread
{
// Another client may have reopened this task in a different folder during consent.
let request_handle = app_server.request_handle();
let recheck = request_handle.request_typed(ClientRequest::ThreadRead {
request_id: RequestId::String(format!("tui-trust-recheck-{}", Uuid::new_v4())),
params: ThreadReadParams {
thread_id: thread.id.clone(),
include_turns: false,
},
});
let latest: ThreadReadResponse = if let Some(draft) = startup_draft.as_deref_mut() {
draft.run_until(tui, recheck).await??
} else {
recheck.await?
};
pending_cwds.push_back(latest.thread.cwd.to_path_buf());
}
}
Ok(consent)
}

View File

@@ -0,0 +1,290 @@
//! Gateway sign-in uses the settings picker and form. Creating a gateway returns to the
//! picker; only explicitly selecting a saved provider completes sign-in.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use super::keys;
use super::provider_setup::ProviderInput;
use crate::app::provider::CREATE_CUSTOM_PROVIDER;
use crate::app::provider::Draft;
use crate::app::provider::ProviderForm;
use crate::app::provider::provider_item;
use crate::app::provider::rpc;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::ListSelectionView;
use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionViewParams;
use crate::bottom_pane::popup_consts::accept_cancel_hint_line;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::ListAction;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
use akode_app_server_client::AppServerRequestHandle;
use akode_app_server_protocol::ModelProviderConfigWriteParams;
use akode_app_server_protocol::ModelProviderListResponse;
use akode_app_server_protocol::ProviderSettings;
use akode_app_server_protocol::WriteStatus;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use futures::future::LocalBoxFuture;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Widget;
use tokio::sync::mpsc::unbounded_channel;
pub(super) const USE_CUSTOM_PROVIDER: &str = "Use a custom provider or gateway";
// Requests stay on the onboarding thread so a redraw can stop polling without losing the reply.
pub(super) enum GatewayStep {
Loading(LocalBoxFuture<'static, Self>),
LoadError(Box<ListSelectionView>),
Picking(Box<Picker>),
Editing {
picker: Box<Picker>,
form: Box<ProviderForm>,
},
Saving(LocalBoxFuture<'static, Self>),
Selecting(LocalBoxFuture<'static, Result<String, Self>>),
}
impl GatewayStep {
fn load(handle: AppServerRequestHandle, notice: Option<String>) -> Self {
Self::Loading(Box::pin(async move {
match rpc::list_providers(&handle).await {
Ok(mut page) if page.can_change_default => {
page.data
.retain(|p| matches!(p.settings, ProviderSettings::CustomGateway { .. }));
Self::Picking(Box::new(Picker::new(page, /*selected*/ None, notice)))
}
Ok(_) => Self::load_error(
"The default provider is set by configuration policy or a launch override."
.into(),
),
Err(message) => Self::load_error(message),
}
}))
}
fn load_error(message: String) -> Self {
let (tx, _) = unbounded_channel();
Self::LoadError(Box::new(ListSelectionView::new(
crate::app::provider::load_error(USE_CUSTOM_PROVIDER, message),
AppEventSender::new(tx),
RuntimeKeymap::defaults().list,
)))
}
fn save(
handle: AppServerRequestHandle,
picker: Box<Picker>,
mut form: Box<ProviderForm>,
params: ModelProviderConfigWriteParams,
) -> Self {
GatewayStep::Saving(Box::pin(async move {
match rpc::write_provider(&handle, params).await {
Ok(rpc::ProviderWrite::Saved(provider)) => {
let mut page = picker.page;
let selected = page.data.len();
page.data.push(provider);
GatewayStep::Picking(Box::new(Picker::new(
page,
Some(selected),
/*notice*/ None,
)))
}
Ok(rpc::ProviderWrite::UnconfirmedCreate) => {
GatewayStep::load(handle, Some(rpc::UNCONFIRMED_CREATE.into()))
}
Err(message) => {
form.error = Some(message);
GatewayStep::Editing { picker, form }
}
}
}))
}
pub(super) fn active_input_mut(&mut self) -> Option<&mut ProviderInput> {
match self {
Self::Editing { form, .. } => form.active_input_mut(),
_ => None,
}
}
pub(super) fn is_text_entry_active(&self) -> bool {
matches!(self, Self::Editing { form, .. } if form.active_input().is_some())
}
pub(super) fn render(&self, area: Rect, buf: &mut Buffer) {
match self {
Self::Loading(_) => Widget::render(Line::from("Loading gateways…".dim()), area, buf),
Self::Editing { form, .. } => form.render(area, buf),
Self::Saving(_) | Self::Selecting(_) => {
Widget::render(Line::from("Saving gateway settings…".dim()), area, buf)
}
Self::LoadError(list) => list.render(area, buf),
Self::Picking(picker) => picker.list.render(area, buf),
}
}
}
pub(super) struct Picker {
page: ModelProviderListResponse,
list: ListSelectionView,
}
impl Picker {
fn new(
page: ModelProviderListResponse,
selected: Option<usize>,
notice: Option<String>,
) -> Self {
let mut items: Vec<_> = page
.data
.iter()
.map(|p| provider_item(p, &page.default_provider_id))
.collect();
let keymap = RuntimeKeymap::defaults().list;
let hint = |accept| {
accept_cancel_hint_line(
keymap.primary_hint(ListAction::Accept),
accept,
keymap.primary_hint(ListAction::Cancel),
"to go back",
)
};
items.push(SelectionItem {
name: CREATE_CUSTOM_PROVIDER.into(),
footer_hint: Some(hint("to create")),
..Default::default()
});
// Like the other startup pickers, consume the selection directly before the app event loop exists.
let (tx, _) = unbounded_channel();
let list = ListSelectionView::new(
SelectionViewParams {
title: Some(USE_CUSTOM_PROVIDER.into()),
footer_hint: Some(hint("to use as default")),
footer_note: notice.map(Into::into),
initial_selected_idx: selected,
auto_number_shortcuts: false,
items,
..Default::default()
},
AppEventSender::new(tx),
keymap,
);
Self { page, list }
}
fn activate(self: Box<Self>, index: usize, handle: AppServerRequestHandle) -> GatewayStep {
let Some(provider) = self.page.data.get(index) else {
let form = ProviderForm::new(
Draft::new(/*provider*/ None, &self.page.data),
/*error*/ None,
);
return GatewayStep::Editing {
picker: self,
form: Box::new(form),
};
};
let id = provider.id.clone();
GatewayStep::Selecting(Box::pin(async move {
let message = match rpc::set_default_provider(&handle, &id).await {
Ok(response) => match response.status {
WriteStatus::Ok => return Ok(id),
WriteStatus::OkOverridden => rpc::override_reason(response),
},
Err(err) => err.to_string(),
};
Err(GatewayStep::Picking(Box::new(Picker::new(
self.page,
Some(index),
Some(message),
))))
}))
}
}
impl AuthModeWidget {
pub(super) fn start_gateway_picker(&mut self) {
self.set_error(/*message*/ None);
self.gateway = Some(GatewayStep::load(
self.app_server_request_handle.clone(),
/*notice*/ None,
));
self.request_frame.schedule_frame();
}
pub(super) async fn advance_gateway_request(&mut self) {
self.gateway = match &mut self.gateway {
Some(GatewayStep::Loading(request) | GatewayStep::Saving(request)) => {
Some(request.await)
}
Some(GatewayStep::Selecting(request)) => match request.await {
Ok(id) => {
*self
.sign_in_state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
SignInState::GatewaySelected(id);
None
}
Err(picker) => Some(picker),
},
None
| Some(
GatewayStep::Picking(_) | GatewayStep::LoadError(_) | GatewayStep::Editing { .. },
) => std::future::pending().await,
};
self.request_frame.schedule_frame();
}
pub(super) fn handle_gateway_key_event(&mut self, key: KeyEvent) -> bool {
let Some(step) = self.gateway.take() else {
return false;
};
self.gateway = match step {
GatewayStep::Loading(_) | GatewayStep::Picking(_) | GatewayStep::LoadError(_)
if keys::CANCEL.is_pressed(key) =>
{
None
}
GatewayStep::Editing { picker, .. } if keys::CANCEL.is_pressed(key) => {
Some(GatewayStep::Picking(picker))
}
GatewayStep::Editing { picker, mut form } => {
if let Some(params) = form.input(key) {
self.guard_activation(key);
let handle = self.app_server_request_handle.clone();
Some(GatewayStep::save(handle, picker, form, params))
} else {
Some(GatewayStep::Editing { picker, form })
}
}
GatewayStep::LoadError(mut view) => {
view.handle_key_event(key);
if view.take_last_selected_index().is_some() {
self.guard_activation(key);
None
} else {
Some(GatewayStep::LoadError(view))
}
}
GatewayStep::Picking(mut picker)
if key.kind == KeyEventKind::Press || !keys::CONFIRM.is_pressed(key) =>
{
picker.list.handle_key_event(key);
if let Some(index) = picker.list.take_last_selected_index() {
self.guard_activation(key);
Some(picker.activate(index, self.app_server_request_handle.clone()))
} else {
Some(GatewayStep::Picking(picker))
}
}
step => Some(step),
};
self.request_frame.schedule_frame();
true
}
}

View File

@@ -0,0 +1,162 @@
//! Finish authentication against the embedded server running the selected gateway.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use super::auth::onboarding_request_id;
use super::onboarding_screen::OnboardingScreen;
use super::onboarding_screen::OnboardingScreenArgs;
use super::onboarding_screen::run_onboarding_screen;
use crate::AppServerTarget;
use crate::app_server_session::AppServerSession;
use crate::get_login_status;
use crate::legacy_core::config::Config;
use crate::should_show_login_screen;
use crate::startup_draft::StartupCancelled;
use crate::tui::Tui;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::GatewayOAuthCancelResponse;
use akode_app_server_protocol::GatewayOAuthChangedNotification;
use akode_app_server_protocol::GatewayOAuthLoginResponse;
use akode_app_server_protocol::GatewayOAuthReadResponse;
use akode_app_server_protocol::GatewayOAuthStatus;
use color_eyre::Result;
use color_eyre::eyre::OptionExt;
pub(crate) async fn authenticate_gateway(
tui: &mut Tui,
server: &mut AppServerSession,
config: &Config,
) -> Result<()> {
let (login_status, account) = get_login_status(server).await?;
let primary_login = should_show_login_screen(login_status, account.requires_openai_auth);
// Some gateways require both credentials. The primary login must finish first.
for login in [Login::Primary, Login::GatewayOAuth] {
match login {
Login::Primary if !primary_login => continue,
Login::GatewayOAuth if config.model_provider.gateway_oauth.is_none() => continue,
Login::GatewayOAuth | Login::Primary => {}
}
let handle = server.request_handle();
let mut screen = OnboardingScreen::new(
tui,
OnboardingScreenArgs {
show_login_screen: true,
gateway_setup_enabled: false,
show_trust_screen: false,
remote_project_trust: None,
login_status,
app_server_target: AppServerTarget::Embedded,
app_server_request_handle: Some(handle.clone()),
config: config.clone(),
},
)
.await;
let widget = screen
.auth_widget_mut()
.ok_or_eyre("The gateway login screen is unavailable.")?;
match login {
Login::Primary => widget.start_api_key_entry(),
Login::GatewayOAuth => widget.start_gateway_oauth(config.model_provider_id.clone()),
}
if run_onboarding_screen(screen, Some(handle), Some(server), tui)
.await?
.should_exit
{
if matches!(login, Login::GatewayOAuth) {
let _ = server
.request_handle()
.request_typed::<GatewayOAuthCancelResponse>(
ClientRequest::GatewayOAuthCancel {
request_id: onboarding_request_id(),
params: None,
},
)
.await;
}
return Err(
std::io::Error::new(std::io::ErrorKind::Interrupted, StartupCancelled).into(),
);
}
}
Ok(())
}
enum Login {
Primary,
GatewayOAuth,
}
impl AuthModeWidget {
pub(super) fn start_gateway_oauth(&mut self, provider_id: String) {
*self
.sign_in_state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = SignInState::GatewayOAuth {
provider_id: provider_id.clone(),
url: None,
};
let state = self.sign_in_state.clone();
let frame = self.request_frame.clone();
let handle = self.app_server_request_handle.clone();
tokio::spawn(async move {
let result: Result<()> = async {
let status = handle
.request_typed::<GatewayOAuthReadResponse>(ClientRequest::GatewayOAuthRead {
request_id: onboarding_request_id(),
params: None,
})
.await?;
color_eyre::eyre::ensure!(
status.provider_id == provider_id,
"The selected gateway changed during sign-in."
);
if status.required && status.status != Some(GatewayOAuthStatus::Succeeded) {
handle
.request_typed::<GatewayOAuthLoginResponse>(
ClientRequest::GatewayOAuthLogin {
request_id: onboarding_request_id(),
params: None,
},
)
.await?;
}
Ok(())
}
.await;
*state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = match result {
Ok(()) => SignInState::GatewayConfigured,
Err(err) => SignInState::GatewayOAuthFailed {
provider_id,
message: err.to_string(),
},
};
frame.schedule_frame();
});
}
pub(super) fn on_gateway_oauth_changed(
&mut self,
notification: GatewayOAuthChangedNotification,
) {
let Some(auth_url) = notification.auth_url else {
return;
};
let mut state = self
.sign_in_state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let SignInState::GatewayOAuth { provider_id, url } = &mut *state
&& notification.provider_id == *provider_id
&& url.as_ref() != Some(&auth_url)
{
*url = Some(auth_url.clone());
drop(state);
self.request_frame.schedule_frame();
tokio::task::spawn_blocking(move || {
let _ = webbrowser::open(&auth_url);
});
}
}
}

View File

@@ -0,0 +1,191 @@
#![cfg(test)]
use super::*;
use crate::app::provider::rpc::list_providers;
use crate::app::provider::rpc::write_provider;
use akode_app_server_protocol::CustomGatewaySettingsParams;
use akode_app_server_protocol::ProviderSettingsPatch;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use serde_json::json;
fn screen(widget: &AuthModeWidget, height: u16) -> String {
let area = Rect::new(0, 0, 72, height);
let mut terminal = crate::custom_terminal::Terminal::with_options(
crate::test_backend::VT100Backend::new(area.width, area.height),
)
.unwrap();
terminal.set_viewport_area(area);
terminal
.draw(|frame| widget.render_ref(area, frame.buffer_mut()))
.unwrap();
terminal
.backend()
.to_string()
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
}
#[tokio::test]
async fn select_a_saved_gateway_during_sign_in() -> color_eyre::Result<()> {
let (mut widget, home) = super::tests::widget_api_login_forbidden().await;
widget.auth_config.forced_login_method = None;
widget.gateway_setup_enabled = true;
insta::assert_snapshot!("gateway_sign_in_menu", screen(&widget, /*height*/ 8));
widget.handle_key_event(KeyCode::Char('2').into());
widget.advance_gateway_request().await;
insta::assert_snapshot!("gateway_empty_picker", screen(&widget, /*height*/ 8));
widget.handle_key_event(KeyCode::Esc.into());
let managed = home.path().join("managed_config.toml");
std::fs::write(&managed, "model_provider = 'openai'")?;
widget.handle_key_event(KeyCode::Char('2').into());
widget.advance_gateway_request().await;
let error = screen(&widget, /*height*/ 8);
assert!(error.contains("configuration policy"));
insta::assert_snapshot!("gateway_load_error", error);
widget.handle_key_event(KeyCode::Esc.into());
std::fs::remove_file(managed)?;
std::fs::write(
home.path().join("config.toml"),
r#"
[model_providers.office]
name = "Office"
base_url = "https://office.example.test/v1"
wire_api = "responses"
"#,
)?;
widget.handle_key_event(KeyCode::Char('2').into());
widget.advance_gateway_request().await;
insta::assert_snapshot!("gateway_saved_picker", screen(&widget, /*height*/ 8));
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
assert!(matches!(widget.get_step_state(), StepState::Complete));
insta::assert_snapshot!(screen(&widget, /*height*/ 4), @"✓ Custom provider configured");
let saved: toml::Value =
toml::from_str(&std::fs::read_to_string(home.path().join("config.toml"))?)?;
assert_eq!(saved["model_provider"].as_str(), Some("office"));
Ok(())
}
#[tokio::test]
async fn create_highlights_the_saved_gateway_until_explicitly_selected() -> color_eyre::Result<()> {
let (mut widget, home) = super::tests::widget_api_login_forbidden().await;
widget.auth_config.forced_login_method = None;
widget.gateway_setup_enabled = true;
write_provider(
&widget.app_server_request_handle,
akode_app_server_protocol::ModelProviderConfigWriteParams {
settings: ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
name: Some("Office".into()),
base_url: Some(Some("https://office.example.test/v1".into())),
..Default::default()
}),
},
)
.await
.map_err(color_eyre::Report::msg)?;
widget.handle_key_event(KeyCode::Char('2').into());
widget.advance_gateway_request().await;
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Enter.into());
insta::assert_snapshot!(screen(&widget, /*height*/ 12), @r"
Create a custom provider or gateway
› Name* Team gateway
Base URL* https://gateway.example/v1
API key variable $TEAM_API_KEY
Save
* Required
Enter the environment variable name on the app server.
tab move · enter next/save · esc back
");
widget.handle_paste("Team gateway".into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_paste("https://team.example.test/v1?".into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_paste("TEAM_KEY-".into());
widget.handle_key_event(KeyCode::Down.into());
insta::assert_snapshot!("gateway_save_focused_short", screen(&widget, /*height*/ 4));
widget.handle_key_event(KeyCode::Enter.into());
insta::assert_snapshot!("gateway_save_error_short", screen(&widget, /*height*/ 4));
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(KeyCode::Backspace.into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
insta::assert_snapshot!("gateway_validation_retry", screen(&widget, /*height*/ 8));
// Correct the invalid URL and keep the other fields.
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(KeyCode::Backspace.into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
assert_eq!(widget.error_message(), None);
widget.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Repeat,
));
assert!(matches!(widget.get_step_state(), StepState::InProgress));
insta::assert_snapshot!("gateway_created_picker", screen(&widget, /*height*/ 8));
let page = list_providers(&widget.app_server_request_handle)
.await
.map_err(color_eyre::Report::msg)?;
// aKode has no default provider until one is selected.
assert_eq!(page.default_provider_id, "");
widget.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Release,
));
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
assert!(matches!(widget.get_step_state(), StepState::Complete));
let saved: serde_json::Value =
toml::from_str(&std::fs::read_to_string(home.path().join("config.toml"))?)?;
assert_eq!(
saved,
json!({
"model_provider": "team-gateway",
"model_providers": {
"office": {
"name": "Office",
"base_url": "https://office.example.test/v1",
"wire_api": "responses",
},
"team-gateway": {
"name": "Team gateway",
"base_url": "https://team.example.test/v1",
"env_key": "TEAM_KEY",
"wire_api": "responses",
},
},
})
);
Ok(())
}
#[tokio::test]
async fn gateway_oauth_displays_the_browser_link_and_retry_action() {
let (widget, _home) = super::tests::widget_api_login_forbidden().await;
*widget.sign_in_state.write().unwrap() = SignInState::GatewayOAuth {
provider_id: "office".into(),
url: Some("https://office.example.test/authorize".into()),
};
insta::assert_snapshot!("gateway_oauth_browser", screen(&widget, /*height*/ 4));
*widget.sign_in_state.write().unwrap() = SignInState::GatewayOAuthFailed {
provider_id: "office".into(),
message: "Gateway sign-in expired.".into(),
};
insta::assert_snapshot!("gateway_oauth_failed", screen(&widget, /*height*/ 4));
}

View File

@@ -0,0 +1,40 @@
//! Fixed shortcuts used before users have had a chance to configure Codex.
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use crate::key_hint;
use crate::key_hint::KeyBinding;
pub(crate) const MOVE_UP: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Up),
key_hint::plain(KeyCode::Char('k')),
];
pub(crate) const MOVE_DOWN: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Down),
key_hint::plain(KeyCode::Char('j')),
];
pub(crate) const SELECT_FIRST: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Char('1')),
key_hint::plain(KeyCode::Char('y')),
];
pub(crate) const SELECT_SECOND: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Char('2')),
key_hint::plain(KeyCode::Char('n')),
];
pub(crate) const SELECT_THIRD: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('3'))];
pub(crate) const SELECT_FOURTH: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('4'))];
pub(crate) const CONFIRM: [KeyBinding; 1] = [key_hint::plain(KeyCode::Enter)];
pub(crate) const CANCEL: [KeyBinding; 1] = [key_hint::plain(KeyCode::Esc)];
pub(crate) const QUIT: [KeyBinding; 3] = [
key_hint::plain(KeyCode::Char('q')),
key_hint::ctrl(KeyCode::Char('c')),
key_hint::ctrl(KeyCode::Char('d')),
];
pub(crate) const TOGGLE_ANIMATION: [KeyBinding; 2] = [
key_hint::ctrl(KeyCode::Char('.')),
KeyBinding::new(
KeyCode::Char('.'),
KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
),
];

View File

@@ -0,0 +1,18 @@
mod auth;
mod gateway;
mod gateway_login;
pub(crate) use gateway_login::authenticate_gateway;
mod keys;
pub(crate) mod onboarding_screen;
mod provider_required;
pub(crate) use provider_required::model_provider_missing;
pub(crate) use provider_required::show_no_model_provider_setup;
mod provider_setup;
pub(crate) use provider_setup::FieldDisplay;
pub(crate) use provider_setup::ProviderInput;
pub(crate) use provider_setup::move_provider_field;
mod trust_directory;
pub(crate) use auth::mark_url_hyperlink;
pub(crate) use onboarding_screen::DirectoryTrustOptions;
pub(crate) use trust_directory::TrustCancelAction;
mod welcome;

View File

@@ -0,0 +1,954 @@
//! Onboarding screen orchestration and top-level keyboard routing.
//!
//! The onboarding flow is a small state machine over visible steps
//! (welcome/auth/trust). This module decides which step receives key/paste
//! events and enforces flow-level safety rules that cut across individual step
//! widgets. Folder-entry consent reuses this same event loop for startup and in-app navigation.
//!
//! In particular, onboarding quit handling has a text-entry guard for API-key
//! input: the printable `q` quit key is treated as text input while the user is
//! editing a non-empty API-key field, while control/alt chords remain available
//! as explicit exit shortcuts.
use akode_app_server_client::AppServerEvent;
use akode_app_server_client::AppServerRequestHandle;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::ConfigBatchWriteParams;
use akode_app_server_protocol::RequestId;
use akode_app_server_protocol::ServerNotification;
use akode_exec_server::LOCAL_FS;
use akode_git_utils::resolve_root_git_project_for_trust;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Color;
use ratatui::widgets::Clear;
use ratatui::widgets::WidgetRef;
use crate::LoginStatus;
use crate::app_server_session::AppServerSession;
use crate::config_update::RemoteProjectTrust;
use crate::config_update::format_config_error;
use crate::config_update::replace_config_value;
use crate::config_update::write_trusted_project;
use crate::empty_state_animation::Presentation;
use crate::key_hint::KeyBindingListExt;
use crate::legacy_core::config::Config;
use crate::onboarding::auth::AuthModeWidget;
use crate::onboarding::auth::SignInOption;
use crate::onboarding::auth::SignInState;
use crate::onboarding::keys;
use crate::onboarding::trust_directory::TrustDirectorySelection;
use crate::onboarding::trust_directory::TrustDirectoryWidget;
use crate::onboarding::welcome::WelcomeWidget;
use crate::startup_draft::StartupCancelled;
use crate::tui::FrameRequester;
use crate::tui::MouseCapture;
use crate::tui::Tui;
use crate::tui::TuiEvent;
use color_eyre::eyre::Result;
use color_eyre::eyre::WrapErr;
use std::sync::Arc;
use std::sync::RwLock;
use uuid::Uuid;
#[path = "directory_trust.rs"]
mod directory_trust;
pub(crate) use directory_trust::DirectoryTrustOptions;
pub(crate) use directory_trust::check_directory_trust;
#[allow(clippy::large_enum_variant)]
enum Step {
Welcome(WelcomeWidget),
Auth(AuthModeWidget),
TrustDirectory(TrustDirectoryWidget),
}
pub(crate) trait KeyboardHandler {
fn handle_key_event(&mut self, key_event: KeyEvent);
fn handle_paste(&mut self, _pasted: String) {}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StepState {
Hidden,
InProgress,
Complete,
}
pub(crate) trait StepStateProvider {
fn get_step_state(&self) -> StepState;
}
pub(crate) struct OnboardingScreen {
request_frame: FrameRequester,
steps: Vec<Step>,
remote_trust_key: Option<String>,
is_done: bool,
should_exit: bool,
}
pub(crate) struct OnboardingScreenArgs {
pub show_trust_screen: bool,
pub remote_project_trust: Option<RemoteProjectTrust>,
pub show_login_screen: bool,
pub gateway_setup_enabled: bool,
pub login_status: LoginStatus,
pub app_server_target: crate::AppServerTarget,
pub app_server_request_handle: Option<AppServerRequestHandle>,
pub config: Config,
}
#[derive(Default)]
pub(crate) struct OnboardingResult {
pub directory_trust_persisted: bool,
pub selected_gateway: Option<String>,
pub should_exit: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct TextEntryContext {
/// Whether onboarding is currently rendering a text-entry state.
active: bool,
/// Whether printable quit shortcuts should be consumed as text input.
has_text: bool,
}
impl OnboardingScreen {
pub(crate) async fn new(tui: &mut Tui, args: OnboardingScreenArgs) -> Self {
let OnboardingScreenArgs {
show_trust_screen,
remote_project_trust,
show_login_screen,
gateway_setup_enabled,
login_status,
app_server_target,
app_server_request_handle,
config,
} = args;
let local_settings = crate::local_settings::LocalSettings::from(&config);
let cwd = config.cwd.to_path_buf();
let remote_trust_key = remote_project_trust
.as_ref()
.map(|project| project.trust_target.to_string_lossy().into_owned());
let auth_config = config.auth_config();
let mut steps: Vec<Step> = Vec::new();
steps.push(Step::Welcome(WelcomeWidget::new(
!matches!(login_status, LoginStatus::NotAuthenticated),
tui.frame_requester(),
local_settings.tui.animations && local_settings.tui.effects.welcome,
)));
#[cfg(target_os = "windows")]
let show_windows_create_sandbox_hint = if show_trust_screen
&& remote_project_trust.is_none()
&& let Some(handle) = &app_server_request_handle
{
crate::windows_sandbox::WindowsSandboxConfig::read(
handle.clone(),
config.cwd.display().to_string(),
)
.await
.is_ok_and(|state| !state.is_enabled())
} else {
false
};
#[cfg(not(target_os = "windows"))]
let show_windows_create_sandbox_hint = false;
if show_login_screen {
let highlighted_mode = SignInOption::ApiKey;
if let Some(app_server_request_handle) = app_server_request_handle {
steps.push(Step::Auth(AuthModeWidget {
request_frame: tui.frame_requester(),
highlighted_mode,
activation_key_guard: None,
error: Arc::new(RwLock::new(None)),
sign_in_state: Arc::new(RwLock::new(SignInState::PickMode)),
login_status,
app_server_target,
app_server_request_handle,
auth_config,
gateway_setup_enabled,
gateway: None,
}));
} else {
tracing::warn!("skipping onboarding login step without app-server request handle");
}
}
let highlighted = TrustDirectorySelection::Trust;
if show_trust_screen {
let (cwd, trust_target) = match remote_project_trust {
Some(RemoteProjectTrust {
cwd, trust_target, ..
}) => (cwd, trust_target),
None => {
let trust_target =
resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &config.cwd)
.await
.map(Into::into)
.unwrap_or_else(|| cwd.clone());
(cwd, trust_target)
}
};
steps.push(Step::TrustDirectory(TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: super::trust_directory::TrustCancelAction::Quit,
cwd,
trust_target,
show_windows_create_sandbox_hint,
should_quit: false,
selection: None,
highlighted,
error: None,
}))
}
Self {
request_frame: tui.frame_requester(),
steps,
remote_trust_key,
is_done: false,
should_exit: false,
}
}
fn current_steps_mut(&mut self) -> Vec<&mut Step> {
let mut out: Vec<&mut Step> = Vec::new();
for step in self.steps.iter_mut() {
match step.get_step_state() {
StepState::Hidden => continue,
StepState::Complete => out.push(step),
StepState::InProgress => {
out.push(step);
break;
}
}
}
out
}
fn current_steps(&self) -> Vec<&Step> {
let mut out: Vec<&Step> = Vec::new();
for step in self.steps.iter() {
match step.get_step_state() {
StepState::Hidden => continue,
StepState::Complete => out.push(step),
StepState::InProgress => {
out.push(step);
break;
}
}
}
out
}
fn is_auth_in_progress(&self) -> bool {
self.steps.iter().any(|step| {
matches!(step, Step::Auth(_)) && matches!(step.get_step_state(), StepState::InProgress)
})
}
pub(crate) fn is_done(&self) -> bool {
self.is_done
|| !self
.steps
.iter()
.any(|step| matches!(step.get_step_state(), StepState::InProgress))
}
pub fn should_exit(&self) -> bool {
self.should_exit
}
/// Check whether the first unfinished onboarding step can grant directory trust.
fn is_trust_step_active(&self) -> bool {
self.steps
.iter()
.find(|step| matches!(step.get_step_state(), StepState::InProgress))
.is_some_and(|step| matches!(step, Step::TrustDirectory(_)))
}
pub(super) fn auth_widget_mut(&mut self) -> Option<&mut AuthModeWidget> {
self.steps.iter_mut().find_map(|step| match step {
Step::Auth(widget) => Some(widget),
Step::Welcome(_) | Step::TrustDirectory(_) => None,
})
}
fn handle_app_server_notification(&mut self, notification: ServerNotification) {
match notification {
ServerNotification::GatewayOAuthChanged(notification) => {
if let Some(widget) = self.auth_widget_mut() {
widget.on_gateway_oauth_changed(notification);
}
}
ServerNotification::AccountUpdated(notification) => {
if let Some(widget) = self.auth_widget_mut() {
widget.on_account_updated(notification);
}
}
_ => {}
}
}
fn text_entry_context(&self) -> TextEntryContext {
self.steps
.iter()
.find_map(|step| {
if let Step::Auth(widget) = step {
Some(TextEntryContext {
active: widget.is_text_entry_active(),
has_text: widget.should_suppress_printable_quit(),
})
} else {
None
}
})
.unwrap_or_default()
}
}
impl KeyboardHandler for OnboardingScreen {
/// Route key events to onboarding steps while preserving text-entry safety.
///
/// OpenAI API-key entry suppresses printable quit bindings after typing
/// starts, while provider setup fields suppress them from the first character.
/// Control/alt quit chords still work as emergency exits.
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release {
if let Some(widget) = self.auth_widget_mut() {
widget.handle_key_event(key_event);
}
return;
}
let text_entry_context = self.text_entry_context();
let should_quit = key_event.kind == KeyEventKind::Press
&& keys::QUIT.is_pressed(key_event)
&& !suppress_quit_while_typing(key_event, text_entry_context);
if should_quit {
if self.is_auth_in_progress() {
// If the user cancels the auth menu, exit the app rather than
// leave the user at a prompt in an unauthed state.
self.should_exit = true;
} else if self.is_trust_step_active() {
self.should_exit = true;
}
self.is_done = true;
} else {
if let Some(Step::Welcome(widget)) = self
.steps
.iter_mut()
.find(|step| matches!(step, Step::Welcome(_)))
{
widget.handle_key_event(key_event);
}
if let Some(active_step) = self.current_steps_mut().into_iter().last() {
active_step.handle_key_event(key_event);
}
if self.steps.iter().any(|step| {
if let Step::TrustDirectory(widget) = step {
widget.should_quit()
} else {
false
}
}) {
self.should_exit = true;
self.is_done = true;
}
}
self.request_frame.schedule_frame();
}
fn handle_paste(&mut self, pasted: String) {
if pasted.is_empty() {
return;
}
if let Some(active_step) = self.current_steps_mut().into_iter().last() {
active_step.handle_paste(pasted);
}
self.request_frame.schedule_frame();
}
}
/// Returns `true` when a quit shortcut should be ignored as text input.
///
/// This only applies when the active text-entry state suppresses printable quit
/// shortcuts and the key has no control/alt modifiers.
fn suppress_quit_while_typing(key_event: KeyEvent, text_entry_context: TextEntryContext) -> bool {
text_entry_context.active
&& text_entry_context.has_text
&& matches!(key_event.code, KeyCode::Char(_))
&& !key_event
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
}
impl WidgetRef for &OnboardingScreen {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
let logo_presentation = if self.text_entry_context().active {
Presentation::Faded
} else {
Presentation::Animated
};
for step in self.current_steps() {
match step {
Step::Welcome(widget) => widget.set_presentation(logo_presentation),
Step::Auth(_) | Step::TrustDirectory(_) => {}
}
}
Clear.render(area, buf);
// Render steps top-to-bottom, measuring each step's height dynamically.
let mut y = area.y;
let bottom = area.y.saturating_add(area.height);
let width = area.width;
// Helper to scan a temporary buffer and return number of used rows.
fn used_rows(tmp: &Buffer, width: u16, height: u16) -> u16 {
if width == 0 || height == 0 {
return 0;
}
let mut last_non_empty: Option<u16> = None;
for yy in 0..height {
let mut any = false;
for xx in 0..width {
let cell = &tmp[(xx, yy)];
let has_symbol = !cell.symbol().trim().is_empty();
let has_style = cell.fg != Color::Reset
|| cell.bg != Color::Reset
|| !cell.modifier.is_empty();
if has_symbol || has_style {
any = true;
break;
}
}
if any {
last_non_empty = Some(yy);
}
}
last_non_empty.map(|v| v + 2).unwrap_or(0)
}
let mut i = 0usize;
let current_steps = self.current_steps();
while i < current_steps.len() && y < bottom {
let step = &current_steps[i];
let max_h = bottom.saturating_sub(y);
if max_h == 0 || width == 0 {
break;
}
let scratch_area = Rect::new(0, 0, width, max_h);
let mut scratch = Buffer::empty(scratch_area);
if let Step::Welcome(widget) = step {
widget.update_layout_area(scratch_area);
}
step.render_ref(scratch_area, &mut scratch);
let h = used_rows(&scratch, width, max_h).min(max_h);
if h > 0 {
let target = Rect {
x: area.x,
y,
width,
height: h,
};
Clear.render(target, buf);
step.render_ref(target, buf);
y = y.saturating_add(h);
}
i += 1;
}
}
}
impl KeyboardHandler for Step {
fn handle_key_event(&mut self, key_event: KeyEvent) {
match self {
Step::Welcome(widget) => widget.handle_key_event(key_event),
Step::Auth(widget) => widget.handle_key_event(key_event),
Step::TrustDirectory(widget) => widget.handle_key_event(key_event),
}
}
fn handle_paste(&mut self, pasted: String) {
match self {
Step::Welcome(_) => {}
Step::Auth(widget) => widget.handle_paste(pasted),
Step::TrustDirectory(widget) => widget.handle_paste(pasted),
}
}
}
impl StepStateProvider for Step {
fn get_step_state(&self) -> StepState {
match self {
Step::Welcome(w) => w.get_step_state(),
Step::Auth(w) => w.get_step_state(),
Step::TrustDirectory(w) => w.get_step_state(),
}
}
}
impl WidgetRef for Step {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
match self {
Step::Welcome(widget) => {
widget.render_ref(area, buf);
}
Step::Auth(widget) => {
widget.render_ref(area, buf);
}
Step::TrustDirectory(widget) => {
widget.render_ref(area, buf);
}
}
}
}
pub(crate) async fn run_onboarding_app(
args: OnboardingScreenArgs,
app_server: Option<&mut AppServerSession>,
tui: &mut Tui,
) -> Result<OnboardingResult> {
let request_handle = args.app_server_request_handle.clone();
let screen = OnboardingScreen::new(tui, args).await;
run_onboarding_screen(screen, request_handle, app_server, tui).await
}
pub(super) async fn run_onboarding_screen(
onboarding_screen: OnboardingScreen,
app_server_request_handle: Option<AppServerRequestHandle>,
app_server: Option<&mut AppServerSession>,
tui: &mut Tui,
) -> Result<OnboardingResult> {
// Let the terminal select and copy login URLs and device codes, even in fullscreen mode.
let previous_mouse_capture = tui.mouse_capture;
let result = match tui.set_mouse_capture(MouseCapture::Disabled) {
Ok(()) => {
run_onboarding_screen_inner(
onboarding_screen,
app_server_request_handle,
app_server,
tui,
)
.await
}
Err(error) => Err(error.into()),
};
let restore = tui.set_mouse_capture(previous_mouse_capture);
result.and_then(|result| restore.map(|()| result).map_err(Into::into))
}
async fn run_onboarding_screen_inner(
mut onboarding_screen: OnboardingScreen,
app_server_request_handle: Option<AppServerRequestHandle>,
mut app_server: Option<&mut AppServerSession>,
tui: &mut Tui,
) -> Result<OnboardingResult> {
use tokio_stream::StreamExt;
let mut directory_trust_persisted = false;
// One-time guard to fully clear the screen after ChatGPT login success message is shown
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(&onboarding_screen, frame.area());
})?;
tui.discard_pending_input_before_interactive_screen()?;
let tui_events = tui.event_stream();
tokio::pin!(tui_events);
let mut trust_step_was_active = onboarding_screen.is_trust_step_active();
while !onboarding_screen.is_done() {
tokio::select! {
() = async {
match onboarding_screen.auth_widget_mut() {
Some(auth) => auth.advance_gateway_request().await,
None => std::future::pending().await,
}
} => {}
event = tui_events.next() => {
if let Some(event) = event {
tui.screen_size_for_event(&event)?;
match event {
TuiEvent::Key(key_event) => {
onboarding_screen.handle_key_event(key_event);
if !directory_trust_persisted {
directory_trust_persisted = persist_selected_trust(
&mut onboarding_screen,
app_server_request_handle.clone(),
)
.await;
}
}
TuiEvent::Paste(text) => {
onboarding_screen.handle_paste(text);
}
TuiEvent::Draw
| TuiEvent::Resume
| TuiEvent::Resize(_)
| TuiEvent::FocusGained
| TuiEvent::FocusLost => {
for step in &onboarding_screen.steps {
if let Step::Welcome(widget) = step {
if matches!(&event, TuiEvent::Resume) {
widget.set_presentation(crate::empty_state_animation::Presentation::Hidden);
}
widget.set_focused(tui.is_terminal_focused());
}
}
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(&onboarding_screen, frame.area());
})?;
}
TuiEvent::Mouse(_) => {}
}
} else {
return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, StartupCancelled).into());
}
}
event = async {
match app_server.as_mut() {
Some(app_server) => app_server.next_event().await,
None => None,
}
}, if app_server.is_some() => {
if let Some(event) = event {
match event.event {
AppServerEvent::ServerNotification(notification) => {
onboarding_screen.handle_app_server_notification(*notification);
}
AppServerEvent::Disconnected { message } => {
return Err(color_eyre::eyre::eyre!(message));
}
AppServerEvent::ThreadStreamDisconnected(_)
| AppServerEvent::Lagged { .. }
| AppServerEvent::ServerRequest(_) => {}
}
}
}
}
discard_pending_input_on_trust_step_transition(
&onboarding_screen,
&mut trust_step_was_active,
|onboarding_screen| {
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(onboarding_screen, frame.area());
})?;
tui.discard_pending_input_before_interactive_screen()?;
Ok(())
},
)?;
}
Ok(OnboardingResult {
directory_trust_persisted,
selected_gateway: onboarding_screen.auth_widget_mut().and_then(|widget| {
match &*widget
.sign_in_state
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
SignInState::GatewaySelected(id) => Some(id.clone()),
_ => None,
}
}),
should_exit: onboarding_screen.should_exit(),
})
}
/// Render a newly activated trust step before discarding keys from the preceding screen.
///
/// Once the step is active, preserve fresh navigation and confirmation input.
fn discard_pending_input_on_trust_step_transition(
onboarding_screen: &OnboardingScreen,
trust_step_was_active: &mut bool,
render_and_discard: impl FnOnce(&OnboardingScreen) -> Result<()>,
) -> Result<()> {
let trust_step_is_active = onboarding_screen.is_trust_step_active();
if trust_step_is_active && !*trust_step_was_active {
render_and_discard(onboarding_screen)?;
}
*trust_step_was_active = trust_step_is_active;
Ok(())
}
async fn persist_selected_trust(
onboarding_screen: &mut OnboardingScreen,
request_handle: Option<AppServerRequestHandle>,
) -> bool {
let Some((trust_step_index, trust_target)) = onboarding_screen
.steps
.iter()
.enumerate()
.find_map(|(index, step)| {
if let Step::TrustDirectory(widget) = step
&& widget.selection == Some(TrustDirectorySelection::Trust)
&& !widget.restricted
{
return Some((index, widget.trust_target.clone()));
}
None
})
else {
return false;
};
let result = match (
request_handle,
onboarding_screen.remote_trust_key.as_deref(),
) {
(Some(request_handle), Some(project_key)) => {
let project_key = project_key.replace('\\', "\\\\").replace('"', "\\\"");
request_handle
.request_typed::<serde_json::Value>(ClientRequest::ConfigBatchWrite {
request_id: RequestId::String(format!(
"tui-project-trust-write-{}",
Uuid::new_v4()
)),
params: ConfigBatchWriteParams {
edits: vec![replace_config_value(
format!("projects.\"{project_key}\".trust_level"),
serde_json::json!("trusted"),
)],
file_path: None,
expected_version: None,
reload_user_config: true,
},
})
.await
.map(|_| ())
.wrap_err("config/batchWrite failed while persisting remote project trust")
}
(Some(request_handle), None) => write_trusted_project(request_handle, &trust_target)
.await
.map(|_| ()),
(None, _) => Err(color_eyre::eyre::eyre!("app server unavailable")),
};
match result {
Ok(()) => true,
Err(error) => {
let error = format_config_error(&error);
tracing::error!(
"failed to persist trusted project state for {}: {error}",
trust_target.display()
);
if let Step::TrustDirectory(widget) = &mut onboarding_screen.steps[trust_step_index] {
widget.selection = None;
widget.error = Some(format!(
"Failed to set trust for {}: {error}",
trust_target.display()
));
}
false
}
}
}
#[cfg(test)]
mod tests {
use super::OnboardingScreen;
use super::Step;
use super::StepStateProvider;
use super::TextEntryContext;
use super::discard_pending_input_on_trust_step_transition;
use super::persist_selected_trust;
use super::suppress_quit_while_typing;
use crate::onboarding::onboarding_screen::KeyboardHandler;
use crate::onboarding::trust_directory::TrustDirectorySelection;
use crate::onboarding::trust_directory::TrustDirectoryWidget;
use crate::tui::FrameRequester;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[test]
fn suppresses_printable_quit_key_during_api_key_entry() {
let suppressed = suppress_quit_while_typing(
KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
TextEntryContext {
active: true,
has_text: true,
},
);
assert!(suppressed);
}
#[test]
fn does_not_suppress_printable_quit_key_when_api_key_input_is_empty() {
let suppressed = suppress_quit_while_typing(
KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
TextEntryContext {
active: true,
has_text: false,
},
);
assert!(!suppressed);
}
#[test]
fn does_not_suppress_control_quit_key_during_api_key_entry() {
let suppressed = suppress_quit_while_typing(
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
TextEntryContext {
active: true,
has_text: true,
},
);
assert!(!suppressed);
}
#[test]
fn does_not_suppress_when_not_in_api_key_entry() {
let suppressed = suppress_quit_while_typing(
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE),
TextEntryContext {
active: false,
has_text: true,
},
);
assert!(!suppressed);
}
#[test]
fn buffered_enter_is_discarded_when_trust_step_becomes_active() {
let mut onboarding_screen = OnboardingScreen {
request_frame: FrameRequester::test_dummy(),
steps: vec![Step::TrustDirectory(TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: super::super::trust_directory::TrustCancelAction::Quit,
cwd: PathBuf::from("/workspace/project"),
trust_target: PathBuf::from("/workspace/project"),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Trust,
error: None,
})],
remote_trust_key: None,
is_done: false,
should_exit: false,
};
let mut buffered_keys = vec![KeyEvent::from(KeyCode::Enter)];
let mut trust_step_was_active = false;
let mut drain_count = 0;
discard_pending_input_on_trust_step_transition(
&onboarding_screen,
&mut trust_step_was_active,
|_| {
drain_count += 1;
buffered_keys.clear();
Ok(())
},
)
.expect("discard buffered trust input");
for key in buffered_keys {
onboarding_screen.handle_key_event(key);
}
assert!(onboarding_screen.is_trust_step_active());
let Step::TrustDirectory(widget) = &onboarding_screen.steps[0] else {
panic!("trust step should remain present");
};
assert_eq!(widget.selection, None);
assert_eq!(widget.highlighted, TrustDirectorySelection::Trust);
let mut navigation_keys = vec![KeyEvent::from(KeyCode::Down)];
discard_pending_input_on_trust_step_transition(
&onboarding_screen,
&mut trust_step_was_active,
|_| {
drain_count += 1;
navigation_keys.clear();
Ok(())
},
)
.expect("retain fresh trust navigation");
assert_eq!(drain_count, 1);
onboarding_screen.handle_key_event(navigation_keys.remove(0));
let Step::TrustDirectory(widget) = &onboarding_screen.steps[0] else {
panic!("trust step should remain present");
};
assert_eq!(widget.highlighted, TrustDirectorySelection::Quit);
onboarding_screen.handle_key_event(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
assert!(onboarding_screen.should_exit());
}
#[tokio::test]
async fn restricted_acceptance_and_cancellation_do_not_persist_trust() {
for key in [KeyCode::Enter, KeyCode::Esc] {
let mut screen = OnboardingScreen {
request_frame: FrameRequester::test_dummy(),
steps: vec![Step::TrustDirectory(TrustDirectoryWidget {
restricted: true,
existing_task: false,
cancel: super::super::trust_directory::TrustCancelAction::AgentsOverview,
cwd: PathBuf::from("/workspace/project"),
trust_target: PathBuf::from("/workspace/project"),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Trust,
error: None,
})],
remote_trust_key: Some("/workspace/project".to_string()),
is_done: false,
should_exit: false,
};
screen.handle_key_event(key.into());
assert!(!persist_selected_trust(&mut screen, /*request_handle*/ None).await);
assert!(screen.is_done());
assert_eq!(screen.should_exit(), key == KeyCode::Esc);
let Step::TrustDirectory(widget) = &screen.steps[0] else {
panic!("trust step")
};
assert_eq!(widget.error, None);
}
}
#[tokio::test]
async fn trust_persistence_failure_keeps_trust_step_in_progress() {
let mut onboarding_screen = OnboardingScreen {
request_frame: FrameRequester::test_dummy(),
steps: vec![Step::TrustDirectory(TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: super::super::trust_directory::TrustCancelAction::Quit,
cwd: PathBuf::from("/workspace/project"),
trust_target: PathBuf::from("/workspace/project"),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: Some(TrustDirectorySelection::Trust),
highlighted: TrustDirectorySelection::Trust,
error: None,
})],
remote_trust_key: None,
is_done: false,
should_exit: false,
};
let persisted =
persist_selected_trust(&mut onboarding_screen, /*request_handle*/ None).await;
assert!(!persisted);
let Step::TrustDirectory(widget) = &onboarding_screen.steps[0] else {
panic!("trust step should remain present");
};
assert_eq!(widget.selection, None);
assert_eq!(widget.get_step_state(), super::StepState::InProgress);
assert!(
widget
.error
.as_deref()
.is_some_and(|error| error.contains("app server unavailable"))
);
}
}

View File

@@ -0,0 +1,67 @@
//! Startup guidance shown when no model provider is configured.
//!
//! aKode ships no default provider, so a fresh installation cannot start a model session until
//! the user adds one. For now startup prints the setup guidance and exits with an error; a
//! first-run onboarding screen can replace [`show_no_model_provider_setup`] later.
use akode_app_server_client::AppServerRequestHandle;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::ConfigReadParams;
use akode_app_server_protocol::RequestId;
use akode_model_provider_info::NO_MODEL_PROVIDER_CONFIGURED_ERROR;
use uuid::Uuid;
use crate::AppExitInfo;
use crate::ExitReason;
use crate::config_update::EffectiveConfig;
use crate::legacy_core::config::Config;
use crate::tui::Tui;
/// Whether neither the local configuration nor the connected app server selects a provider.
///
/// A connected server can resolve a provider from its own configuration, so a missing local
/// provider alone is not enough. When the server cannot answer, startup continues and reports
/// any provider error through the normal session path.
pub(crate) async fn model_provider_missing(
config: &Config,
request_handle: AppServerRequestHandle,
) -> bool {
if config.model_provider_configured() {
return false;
}
let server_config = request_handle
.request_typed::<EffectiveConfig>(ClientRequest::ConfigRead {
request_id: RequestId::String(format!("tui-provider-check-{}", Uuid::new_v4())),
params: ConfigReadParams {
include_layers: false,
cwd: Some(config.cwd.display().to_string()),
},
})
.await;
match server_config {
Ok(server_config) => server_config
.config
.model_provider
.as_deref()
.is_none_or(|provider| provider.trim().is_empty()),
Err(err) => {
tracing::warn!(%err, "Failed to read the server's model provider");
false
}
}
}
/// Explain how to configure a model provider instead of starting a model session.
///
/// The returned exit info makes the caller print the guidance and exit with a non-zero status.
pub(crate) fn show_no_model_provider_setup(tui: &mut Tui) -> AppExitInfo {
let _ = tui.terminal.clear();
AppExitInfo {
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::Fatal(NO_MODEL_PROVIDER_CONFIGURED_ERROR.to_string()),
}
}

View File

@@ -0,0 +1,115 @@
//! Single-line fields shared by provider settings and the gateway setup form.
use crate::bottom_pane::TextArea;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use unicode_segmentation::UnicodeSegmentation;
// The sign-in state is shared with request tasks. Each field owns its editing history,
// including killed text, so yanking in another field cannot reveal a credential.
#[derive(Clone)]
pub(crate) struct ProviderInput(Arc<Mutex<TextArea>>);
pub(crate) enum FieldDisplay {
Focused,
Unfocused,
}
impl Default for ProviderInput {
fn default() -> Self {
Self::from("")
}
}
impl From<&str> for ProviderInput {
fn from(text: &str) -> Self {
let mut editor = TextArea::new_single_line();
editor.insert_str(text);
Self(Arc::new(Mutex::new(editor)))
}
}
impl ProviderInput {
pub(crate) fn editor(&self) -> MutexGuard<'_, TextArea> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn input(&mut self, event: KeyEvent) {
self.editor().input(event);
}
pub(crate) fn paste(&mut self, pasted: &str) {
let text: String = pasted.chars().filter(|c| !c.is_control()).collect();
self.editor().insert_str(&text);
}
pub(crate) fn value(&self) -> Option<String> {
let editor = self.editor();
let text = editor.text().trim();
(!text.is_empty()).then(|| text.to_owned())
}
pub(crate) fn line(
&self,
label: &str,
placeholder: &str,
display: FieldDisplay,
width: u16,
) -> Line<'static> {
let editor = self.editor();
let mut line = Line::from(label.to_owned());
if editor.text().is_empty() && !placeholder.is_empty() {
line.push_span(placeholder.to_owned().dim());
return line;
}
let focused = matches!(display, FieldDisplay::Focused);
let field_width = usize::from(width).saturating_sub(line.width());
// When the label occupies a whole row, wrapping moves the value to the next row.
let mut remaining = if field_width == 0 {
usize::from(width)
} else {
field_width
};
let start = if focused {
editor.single_line_viewport(remaining as u16).0
} else {
0
};
for (offset, grapheme) in editor.text()[start..].grapheme_indices(true) {
let span = Span::raw(grapheme.to_owned());
let span = if focused { span.cyan() } else { span };
let Some(rest) = remaining.checked_sub(span.width()) else {
break;
};
remaining = rest;
line.push_span(if focused && start + offset == editor.cursor() {
span.reversed()
} else {
span
});
}
if focused && remaining > 0 && editor.cursor() == editor.text().len() {
line.push_span(" ".reversed());
}
line
}
}
/// Cycle focus among the inputs and actions in a provider form.
pub(crate) fn move_provider_field(key: KeyEvent, selected: &mut usize, count: usize) -> bool {
*selected = match (key.code, key.modifiers) {
(KeyCode::Up | KeyCode::BackTab, KeyModifiers::NONE)
| (KeyCode::Tab | KeyCode::BackTab, KeyModifiers::SHIFT) => (*selected + count - 1) % count,
(KeyCode::Down | KeyCode::Tab, KeyModifiers::NONE) => (*selected + 1) % count,
_ => return false,
};
true
}

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: screen(&widget)
---
Use a custom provider or gateway
○ Office office
› ○ Team gateway team-gateway
Create a custom provider or gateway
Press enter to use as default or esc to go back

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: screen(&widget)
---
Use a custom provider or gateway
› Create a custom provider or gateway
Press enter to create or esc to go back

View File

@@ -0,0 +1,10 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: error
---
Use a custom provider or gateway
The default provider is set by configuration policy or a launch
override.
› 1. Back

View File

@@ -0,0 +1,7 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
Finish signing in to your gateway in the browser.
https://office.example.test/authorize
Press Ctrl+C to quit.

View File

@@ -0,0 +1,6 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
Gateway sign-in expired.
Press Enter to retry or Ctrl+C to quit.

View File

@@ -0,0 +1,8 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
› Save
Enter an environment variable name such as TEAM_API_KEY.
* Required

View File

@@ -0,0 +1,8 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
› Save
* Required
Enter the environment variable name on the app server.

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: screen(&widget)
---
Use a custom provider or gateway
› ○ Office office
Create a custom provider or gateway
Press enter to use as default or esc to go back

View File

@@ -0,0 +1,10 @@
---
source: tui/src/onboarding/gateway_tests.rs
assertion_line: 38
expression: "screen(&widget, 8)"
---
Choose how you want to use Codex.
> 1. Use an OpenAI API key
2. Use a custom provider or gateway
Press enter to continue

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 8)"
---
Base URL* https://team.example.test/v1?
API key variable $TEAM_KEY
› Save
Enter an HTTP(S) base URL without credentials, a query, or a fragment.
* Required
Enter the environment variable name on the app server.
tab move · enter next/save · esc back

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/auth.rs
expression: terminal.backend().to_string()
---
> Use your own OpenAI API key for usage-based billing
Paste or type your API key below.
╭API key───────────────────────────────────────────────────────────────────────╮
│Paste or type your API key │
╰──────────────────────────────────────────────────────────────────────────────╯
Press enter to save
Press esc to go back

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/auth.rs
expression: terminal.backend().to_string()
---
> Use your own OpenAI API key for
usage-based billing
Paste or type your API key below.
╭API key───────────────────────────────╮
│Paste or type your API key │
╰──────────────────────────────────────╯
Press enter to save
Press esc to go back

View File

@@ -0,0 +1,18 @@
---
source: tui/src/onboarding/trust_directory.rs
assertion_line: 365
expression: terminal.backend()
---
Folder access
/workspace/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Keep current directory
enter continue · esc cancel

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
This existing task may retain settings and history, including
project configuration or hooks loaded while it was trusted. To use
restricted settings, start a new task. The folder's trust setting
will not change.
› 1. Open existing task
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project/long-nested-folde
r
Config, hooks, and exec policies
from untrusted folders stay
disabled. Trusted project folders
can still contribute settings.
Skills still load, and tools follow
your permission settings. Opening
will not change saved trust.
› 1. Open restricted
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().replace('\\\\', \"/\")"
---
Folder access
workspace/…/repository
Trust this folder? Codex can read,
edit, and run files here, subject to
your permission settings. Folder
settings can run code automatically,
even without a model request.
Continue only if you trust these
files. Your trust decision will be
saved.
› 1. Trust and continue
2. Quit
enter continue · esc quit

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().replace('\\\\', \"/\")"
---
Folder access
workspace/…/repository/checkout
Note: You’re in a subdirectory of a
Git project. Trusting will apply to
the repository root:
workspace/…/repository
Trust this folder? Codex can read,
edit, and run files here, subject to
your permission settings. Folder
settings can run code automatically,
even without a model request.
Continue only if you trust these
files. Your trust decision will be
saved.
› 1. Trust and continue
2. Quit
enter continue · esc quit

View File

@@ -0,0 +1,20 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().replace('\\\\', \"/\")"
---
Folder access
Note: You’re in a subdirectory of a
Git project. Trusting will apply to
the repository root:
workspace/…/repository
Trust this folder? Codex can read,
edit, and run files here, subject to
your permission settings. Folder
settings can run code automatically,
even without a model request.
Continue only if you trust these
files. Your trust decision will be
saved.
› 1. Trust and continue
2. Quit
enter continue · esc quit

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
Config, hooks, and exec policies from untrusted folders stay
disabled. Trusted project folders can still contribute settings.
Skills still load, and tools follow your permission settings.
Opening will not change saved trust.
› 1. Open restricted
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Quit
enter continue and create sandbox · esc quit

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().lines().map(str::trim_end).collect::<Vec<_>>().join(\"\\n\")"
---
Folder access
/srv/remote/project/nested
Note: You’re in a subdirectory of a Git project. Trusting will
apply to the repository root:
/srv/remote/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Quit
Failed to set trust for /workspace/project: config/batchWrite
failed in TUI: Invalid configuration: features.fast_mode=true is
not supported; allowed set [fast_mode=false]
enter continue · esc quit

View File

@@ -0,0 +1,25 @@
---
source: tui/src/onboarding/welcome.rs
expression: visible.trim_end()
---
⢀⣀⣠⣤⣤⣤⣤⣤⣤⣀⣀
⢀⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⡀
⢀⣠⣾⣿⣿⣿⣿⡿⠟⠛⠋⠉⠉⠙⠛⠛⠿⣿⣿⣿⣿⣿⣷⡄
⣠⣾⣿⣿⣿⠿⠋ ⠉⠛⣿⣿⣿⣿⣷⡀
⣰⣿⣿⣿⡟⠁ ⠹⣿⣿⣿⣿⡄
⣼⣿⣿⣿⠟ ⣀⣤⡀ ⠈⢿⣿⣿⣷⡀
⢠⣿⣿⣿⡟ ⣿⣿⣿⣄ ⠘⣿⣿⣿⣧
⢸⣿⣿⣿⠁ ⠙⣿⣿⣿⣆ ⢿⣿⣿⣿
⢾⣿⣿⣿ ⢸⣿⣿⣿⠆ ⢸⣿⣿⣿⠆
⣾⣿⣿⣿ ⣠⣿⣿⣿⠏ ⢀⣀⣀⣀⣀⣀⣀⡀ ⢸⣿⣿⣿
⠸⣿⣿⣿⡆ ⢰⣿⣿⣿⠇ ⣿⣿⣿⣿⣿⣿⣿⣿⡆ ⢀⣿⣿⣿⡟
⢻⣿⣿⣿⣄ ⠉⠛⠁ ⠙⠛⠛⠛⠛⠛⠛⠋ ⢀⣼⣿⣿⣿⠃
⠈⢻⣿⣿⣿⣦⡀ ⣠⣾⣿⣿⣿⠇
⠻⣿⣿⣿⣿⣤⣀ ⢀⣠⣾⣿⣿⣿⡿⠃
⠈⠻⣿⣿⣿⣿⣷⣶⣤⣄⣀⣀⣀⢀⣀⣠⣤⣴⣿⣿⣿⣿⣿⠛
⠙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠋
⠉⠙⠛⠿⠿⠿⠿⠿⠿⠿⠛⠋⠁
Welcome to Codex, OpenAI's command-line coding agent

View File

@@ -0,0 +1,483 @@
//! Folder trust disclosure with bounded paths, shared picker styling, and protected selection.
use std::path::Path;
use std::path::PathBuf;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
use crate::bottom_pane::picker_option_row;
use crate::bottom_pane::render_menu_surface;
use crate::key_hint::KeyBindingListExt;
use crate::onboarding::keys;
use crate::onboarding::onboarding_screen::KeyboardHandler;
use crate::onboarding::onboarding_screen::StepStateProvider;
use crate::render::Insets;
use crate::render::renderable::FlexRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableExt as _;
use crate::render::renderable::RenderableItem;
use crate::text_formatting::center_truncate_path;
use super::onboarding_screen::StepState;
pub(crate) struct TrustDirectoryWidget {
pub restricted: bool,
pub existing_task: bool,
pub cancel: TrustCancelAction,
pub cwd: PathBuf,
pub trust_target: PathBuf,
pub show_windows_create_sandbox_hint: bool,
pub should_quit: bool,
pub selection: Option<TrustDirectorySelection>,
pub highlighted: TrustDirectorySelection,
pub error: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TrustCancelAction {
Quit,
AgentsOverview,
CurrentTask,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrustDirectorySelection {
Trust,
Quit,
}
impl WidgetRef for &TrustDirectoryWidget {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
// Measure the mandatory content before giving any rows to variable-length paths.
let mut children = vec![(
0,
Paragraph::new(if self.restricted && self.existing_task {
"This existing task may retain settings \
and history, including project configuration or hooks loaded while it was trusted. \
To use restricted settings, start a new task. The folder's trust setting will not change."
} else if self.restricted {
"Config, hooks, and exec policies from untrusted folders stay disabled. \
Trusted project folders can still contribute settings. Skills still load, \
and tools follow your permission settings. Opening will not change saved trust."
} else {
"Trust this folder? aKode can read, edit, and run files here, subject to \
your permission settings. Folder settings can run code automatically, \
even without a model request. Continue only if you trust these files. \
Your trust decision will be saved."
})
.wrap(Wrap { trim: true })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
)];
children.push((1, RenderableItem::Borrowed(&"")));
let options: Vec<(&str, TrustDirectorySelection)> = vec![
(
if self.restricted && self.existing_task {
"Open existing task"
} else if self.restricted {
"Open restricted"
} else {
"Trust and continue"
},
TrustDirectorySelection::Trust,
),
(
match self.cancel {
TrustCancelAction::Quit => "Quit",
TrustCancelAction::AgentsOverview => "Back to Agent Command Center",
TrustCancelAction::CurrentTask => "Keep current directory",
},
TrustDirectorySelection::Quit,
),
];
for (idx, (text, selection)) in options.iter().enumerate() {
children.push((
0,
picker_option_row(idx, text.to_string(), self.highlighted == *selection).into(),
));
}
children.push((1, RenderableItem::Borrowed(&"")));
if let Some(error) = &self.error {
children.push((
0,
Paragraph::new(error.to_string())
.red()
.wrap(Wrap { trim: true })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
));
children.push((1, RenderableItem::Borrowed(&"")));
}
children.push((
0,
Paragraph::new(Line::from(vec![
keys::CONFIRM[0].into(),
if self.show_windows_create_sandbox_hint && !self.restricted {
" continue and create sandbox".dim()
} else {
" continue".dim()
},
" · ".dim(),
keys::CANCEL[0].into(),
match self.cancel {
TrustCancelAction::Quit => " quit",
TrustCancelAction::AgentsOverview => " back",
TrustCancelAction::CurrentTask => " cancel",
}
.dim(),
]))
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
));
children.push((1, RenderableItem::Borrowed(&"")));
#[allow(clippy::disallowed_methods)]
let git_root_warning = (!self.restricted && self.cwd != self.trust_target).then(|| {
Paragraph::new(
"Note: You’re in a subdirectory of a Git project. Trusting will apply to the repository root:",
)
.yellow()
.wrap(Wrap { trim: true })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2))
});
let reserved_height = children
.iter()
.filter(|(flex, _)| *flex == 0)
.map(|(_, child)| child.desired_height(area.width))
.fold(/*init*/ 1u16, u16::saturating_add)
.saturating_add(git_root_warning.desired_height(area.width));
let path_height = area.height.saturating_sub(reserved_height);
// If only one path row fits, show the repository root receiving trust.
let cwd_height = if git_root_warning.is_some() {
path_height / 2
} else {
path_height
};
let path = |path: &Path, max_height: u16| {
let text = path.display().to_string();
let paragraph = Paragraph::new(text.clone()).wrap(Wrap { trim: false });
let width = area.width.saturating_sub(/*rhs*/ 4);
if paragraph.desired_height(width) <= max_height {
paragraph.dim().inset(Insets::vh(/*v*/ 0, /*h*/ 2))
} else {
// A single line bounds even paths containing embedded newlines.
Line::from(center_truncate_path(&text, usize::from(width)))
.dim()
.inset(Insets::vh(/*v*/ 0, /*h*/ 2))
}
};
let mut column = FlexRenderable::new();
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
column.push(
/*flex*/ 0,
RenderableItem::Owned(Box::new(Line::from(" Folder access".bold()))),
);
if cwd_height > 0 {
column.push(/*flex*/ 0, path(&self.cwd, cwd_height));
}
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
if let Some(warning) = git_root_warning {
column.push(/*flex*/ 0, warning);
let root_height = path_height.saturating_sub(cwd_height);
if root_height > 0 {
column.push(/*flex*/ 0, path(&self.trust_target, root_height));
}
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
}
for (flex, child) in children {
column.push(flex, child);
}
let panel = Rect {
height: column.desired_height(area.width).min(area.height),
..area
};
render_menu_surface(panel, buf);
// The column owns flexible vertical padding; row highlights span the full panel.
column.render(panel, buf);
}
}
impl KeyboardHandler for TrustDirectoryWidget {
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind != KeyEventKind::Press {
return;
}
if keys::MOVE_UP.is_pressed(key_event) {
self.highlighted = TrustDirectorySelection::Trust;
} else if keys::MOVE_DOWN.is_pressed(key_event) {
self.highlighted = TrustDirectorySelection::Quit;
} else if keys::SELECT_FIRST.is_pressed(key_event) {
// A terminal response fragment can start with `1`; trust always requires an explicit
// Enter confirmation after the directory prompt is visible.
self.highlighted = TrustDirectorySelection::Trust;
} else if keys::SELECT_SECOND.is_pressed(key_event)
|| keys::QUIT.is_pressed(key_event)
|| keys::CANCEL.is_pressed(key_event)
{
self.handle_quit();
} else if keys::CONFIRM.is_pressed(key_event) {
match self.highlighted {
TrustDirectorySelection::Trust => self.handle_trust(),
TrustDirectorySelection::Quit => self.handle_quit(),
}
}
}
}
impl StepStateProvider for TrustDirectoryWidget {
fn get_step_state(&self) -> StepState {
if self.selection.is_some() || self.should_quit {
StepState::Complete
} else {
StepState::InProgress
}
}
}
impl TrustDirectoryWidget {
fn handle_trust(&mut self) {
self.highlighted = TrustDirectorySelection::Trust;
self.error = None;
self.selection = Some(TrustDirectorySelection::Trust);
}
fn handle_quit(&mut self) {
self.highlighted = TrustDirectorySelection::Quit;
self.should_quit = true;
}
pub fn should_quit(&self) -> bool {
self.should_quit
}
}
#[cfg(test)]
mod tests {
use crate::test_backend::VT100Backend;
use super::*;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use std::path::PathBuf;
fn widget(error: Option<String>) -> TrustDirectoryWidget {
TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: TrustCancelAction::Quit,
cwd: PathBuf::from("/workspace/project"),
trust_target: PathBuf::from("/workspace/project"),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Trust,
error,
}
}
#[test]
fn release_event_does_not_change_selection() {
let mut widget = TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: TrustCancelAction::Quit,
cwd: PathBuf::from("."),
trust_target: PathBuf::from("."),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Quit,
error: None,
};
let release = KeyEvent {
kind: KeyEventKind::Release,
..KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
};
widget.handle_key_event(release);
assert_eq!(widget.selection, None);
let repeat =
KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Repeat);
widget.handle_key_event(repeat);
assert_eq!(widget.selection, None);
let press = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
widget.handle_key_event(press);
assert!(widget.should_quit);
}
#[test]
fn fragmented_terminal_response_cannot_grant_directory_trust() {
let mut widget = widget(/*error*/ None);
widget.highlighted = TrustDirectorySelection::Quit;
// The prefix may have been consumed by the protected-screen input drain, leaving the
// numeric OSC slot as the first key delivered after the trust prompt becomes active.
for character in "10;rgb:ffff/ffff/ffff".chars() {
widget.handle_key_event(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE));
}
assert_eq!(widget.selection, None);
assert_eq!(widget.highlighted, TrustDirectorySelection::Trust);
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(widget.selection, Some(TrustDirectorySelection::Trust));
}
#[test]
fn renders_snapshot_for_git_repo() {
let mut widget = widget(/*error*/ None);
widget.show_windows_create_sandbox_hint = true;
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 14)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn directory_change_consent_can_keep_current_directory() {
let mut widget = widget(/*error*/ None);
widget.cancel = TrustCancelAction::CurrentTask;
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 18)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(terminal.backend());
widget.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(widget.should_quit());
}
#[test]
fn renders_snapshot_for_remote_git_subdirectory() {
let widget = TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: TrustCancelAction::AgentsOverview,
cwd: PathBuf::from("/srv/remote/project/nested"),
trust_target: PathBuf::from("/srv/remote/project"),
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 18)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(
terminal
.backend()
.to_string()
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
);
}
#[test]
fn renders_restricted_folder() {
for existing_task in [false, true] {
let widget = TrustDirectoryWidget {
restricted: true,
existing_task,
cancel: TrustCancelAction::AgentsOverview,
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 18)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
if existing_task {
insta::assert_snapshot!("existing_untrusted_task", terminal.backend());
} else {
insta::assert_snapshot!(terminal.backend());
}
}
}
#[test]
fn renders_snapshot_for_trust_error() {
let widget = widget(Some(
"Failed to set trust for /workspace/project: config/batchWrite failed in TUI: Invalid configuration: features.fast_mode=true is not supported; allowed set [fast_mode=false]"
.to_string(),
));
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 22)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn picker_wraps_paths_and_restricted_actions() {
let widget = TrustDirectoryWidget {
restricted: true,
cancel: TrustCancelAction::AgentsOverview,
cwd: PathBuf::from("/workspace/project/long-nested-folder"),
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 40, /*height*/ 24)).expect("terminal");
terminal
.draw(|frame| (&widget).render_ref(frame.area(), frame.buffer_mut()))
.expect("draw");
insta::assert_snapshot!("folder_picker_restricted_40x24", terminal.backend());
}
#[test]
fn long_paths_keep_disclosure_and_choices_visible() {
let trust_target: PathBuf = std::iter::once("workspace")
.chain(std::iter::repeat_n("nested-checkout", /*count*/ 60))
.chain(["repository"])
.collect();
for (subdirectory, height, snapshot) in [
(false, 13, "long_checkout_40x13"),
(true, 17, "long_repository_root_40x17"),
(true, 16, "only_repository_root_fits_40x16"),
] {
let widget = TrustDirectoryWidget {
cwd: if subdirectory {
trust_target.join("checkout")
} else {
trust_target.clone()
},
trust_target: trust_target.clone(),
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 40, height)).expect("terminal");
terminal
.draw(|frame| (&widget).render_ref(frame.area(), frame.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(snapshot, terminal.backend().to_string().replace('\\', "/"));
}
}
}

View File

@@ -0,0 +1,222 @@
//! Shared welcome header for the onboarding sign-in picker.
//! The logo occupies a fixed stage so its motion never shifts the choices below it.
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Clear;
use ratatui::widgets::Paragraph;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
use std::cell::Cell;
use std::cell::RefCell;
use crate::empty_state_animation::EmptyStateAnimation;
use crate::empty_state_animation::Presentation;
use crate::key_hint::KeyBindingListExt;
use crate::onboarding::keys;
use crate::onboarding::onboarding_screen::KeyboardHandler;
use crate::onboarding::onboarding_screen::StepStateProvider;
use crate::tui::FrameRequester;
use super::onboarding_screen::StepState;
const MIN_ANIMATION_HEIGHT: u16 = 41;
const MIN_ANIMATION_WIDTH: u16 = 64;
const ANIMATION_WIDTH: u16 = 60;
const ANIMATION_HEIGHT: u16 = 21;
pub(crate) struct WelcomeWidget {
pub is_logged_in: bool,
animation: RefCell<EmptyStateAnimation>,
request_frame: FrameRequester,
animations_enabled: bool,
presentation: Cell<Presentation>,
focused: Cell<bool>,
layout_area: Cell<Option<Rect>>,
}
impl KeyboardHandler for WelcomeWidget {
/// Replay the welcome animation when the existing logo shortcut fires.
///
/// The key list includes compatibility variants for terminals that report
/// modifier bits differently.
fn handle_key_event(&mut self, key_event: KeyEvent) {
if !self.animations_enabled {
return;
}
if key_event.kind == KeyEventKind::Press && keys::TOGGLE_ANIMATION.is_pressed(key_event) {
self.animation.get_mut().start_fresh();
self.request_frame.schedule_frame();
}
}
}
impl WelcomeWidget {
pub(crate) fn new(
is_logged_in: bool,
request_frame: FrameRequester,
animations_enabled: bool,
) -> Self {
let mut animation = EmptyStateAnimation::default();
animation.start_fresh();
Self {
is_logged_in,
animation: RefCell::new(animation),
request_frame,
animations_enabled,
presentation: Cell::new(Presentation::Animated),
focused: Cell::new(/*value*/ true),
layout_area: Cell::new(None),
}
}
pub(crate) fn update_layout_area(&self, area: Rect) {
self.layout_area.set(Some(area));
}
pub(crate) fn set_presentation(&self, presentation: Presentation) {
if presentation == Presentation::Hidden {
self.animation.borrow_mut().pause_clock();
}
self.presentation.set(presentation);
}
pub(crate) fn set_focused(&self, focused: bool) {
self.focused.set(focused);
}
}
impl WidgetRef for &WelcomeWidget {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
Clear.render(area, buf);
let layout_area = self.layout_area.get().unwrap_or(area);
// Skip the animation entirely when the viewport is too small so we don't clip frames.
let show_animation = self.animations_enabled
&& self.presentation.get() != Presentation::Hidden
&& layout_area.height >= MIN_ANIMATION_HEIGHT
&& layout_area.width >= MIN_ANIMATION_WIDTH;
let presentation = if !show_animation {
Presentation::Hidden
} else if !self.focused.get() {
Presentation::Faded
} else {
self.presentation.get()
};
let stage = Rect::new(area.x, area.y, ANIMATION_WIDTH, ANIMATION_HEIGHT);
if let Some(delay) = self
.animation
.borrow_mut()
.render_in(stage, buf, presentation)
{
self.request_frame.schedule_frame_in(delay);
}
let logo_rows = if show_animation {
ANIMATION_HEIGHT + 1
} else {
0
};
let mut lines: Vec<Line> = vec![Line::default(); usize::from(logo_rows)];
lines.push(Line::from(vec![
" ".into(),
"Welcome to ".into(),
"Codex".bold(),
", OpenAI's command-line coding agent".into(),
]));
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
}
}
impl StepStateProvider for WelcomeWidget {
fn get_step_state(&self) -> StepState {
match self.is_logged_in {
true => StepState::Hidden,
false => StepState::Complete,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
fn row_containing(buf: &Buffer, needle: &str) -> Option<u16> {
(0..buf.area.height).find(|&y| {
let mut row = String::new();
for x in 0..buf.area.width {
row.push_str(buf[(x, y)].symbol());
}
row.contains(needle)
})
}
#[test]
fn welcome_renders_animation_on_first_draw() {
let widget = WelcomeWidget::new(
/*is_logged_in*/ false,
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
);
let area = Rect::new(0, 0, MIN_ANIMATION_WIDTH, MIN_ANIMATION_HEIGHT);
let mut buf = Buffer::empty(area);
(&widget).render_ref(area, &mut buf);
let welcome_row = row_containing(&buf, "Welcome");
assert_eq!(welcome_row, Some(ANIMATION_HEIGHT + 1));
widget.set_focused(/*focused*/ false);
(&widget).render_ref(area, &mut buf);
assert_eq!(row_containing(&buf, "Welcome"), welcome_row);
}
#[test]
fn welcome_skips_animation_below_height_breakpoint() {
let widget = WelcomeWidget::new(
/*is_logged_in*/ false,
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
);
let area = Rect::new(0, 0, MIN_ANIMATION_WIDTH, MIN_ANIMATION_HEIGHT - 1);
let mut buf = Buffer::empty(area);
(&widget).render_ref(area, &mut buf);
let welcome_row = row_containing(&buf, "Welcome");
assert_eq!(welcome_row, Some(0));
}
#[test]
fn welcome_logo_layout() {
let (width, height) = (160, 48);
let widget = WelcomeWidget::new(
/*is_logged_in*/ false,
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
);
// The first focused draw shows the intact logo at exactly zero elapsed time.
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buf = Buffer::empty(area);
(&widget).render_ref(area, &mut buf);
let visible = (0..height)
.map(|y| {
(0..width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(format!("welcome_logo_{width}x{height}"), visible.trim_end());
}
}