| 1 | //! TUI event loop and rendering logic for `DeepSeek` CLI. |
| 2 | |
| 3 | use std::collections::{HashSet, VecDeque}; |
| 4 | use std::fmt::Write as _; |
| 5 | use std::future::Future; |
| 6 | use std::io::{self, IsTerminal, Stdout, Write}; |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | use std::pin::Pin; |
| 9 | use std::sync::{ |
| 10 | Arc, LazyLock, |
| 11 | atomic::{AtomicBool, Ordering}, |
| 12 | }; |
| 13 | use std::time::{Duration, Instant}; |
| 14 | |
| 15 | use anyhow::{Context, Result}; |
| 16 | use codewhale_config::AppMode; |
| 17 | use codewhale_core::ContextReference; |
| 18 | use codewhale_error_taxonomy::{ErrorCategory, ErrorEnvelope, ErrorSeverity}; |
| 19 | use codewhale_execpolicy::ApprovalMode; |
| 20 | use codewhale_release::InstallMethod; |
| 21 | // On Windows the push/pop helpers write the escapes directly; crossterm's |
| 22 | // PushKeyboardEnhancementFlags / PopKeyboardEnhancementFlags commands are |
| 23 | // never referenced, so the imports are gated to avoid -D warnings failures. |
| 24 | #[cfg(not(windows))] |
| 25 | use crossterm::event::{ |
| 26 | KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags, |
| 27 | }; |
| 28 | use crossterm::{ |
| 29 | event::{ |
| 30 | self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste, |
| 31 | EnableFocusChange, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind, |
| 32 | KeyModifiers, |
| 33 | }, |
| 34 | execute, |
| 35 | terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, |
| 36 | }; |
| 37 | use ratatui::{ |
| 38 | Frame, Terminal, |
| 39 | layout::{Constraint, Direction, Layout, Rect, Size}, |
| 40 | prelude::Widget, |
| 41 | style::Style, |
| 42 | widgets::Block, |
| 43 | }; |
| 44 | use tracing; |
| 45 | #[cfg(target_os = "windows")] |
| 46 | use windows::Win32::System::Console::{GetConsoleMode, GetStdHandle, SetConsoleMode}; |
| 47 | |
| 48 | use crate::commands; |
| 49 | use crate::tui::auto_router; |
| 50 | use crate::tui::color_compat::ColorCompatBackend; |
| 51 | use crate::tui::command_palette::{ |
| 52 | CommandPaletteView, build_entries_with_plugins as build_command_palette_entries, |
| 53 | }; |
| 54 | use crate::tui::composer_ui::*; |
| 55 | use crate::tui::context_inspector::ContextInspectorView; |
| 56 | use crate::tui::file_picker_relevance; |
| 57 | use crate::tui::footer_ui::friendly_subagent_progress; |
| 58 | use crate::tui::format_helpers; |
| 59 | use crate::tui::hotbar::actions::HotbarDispatch; |
| 60 | use crate::tui::key_shortcuts; |
| 61 | use crate::tui::live_transcript::LiveTranscriptOverlay; |
| 62 | use crate::tui::mcp_routing::{add_mcp_message, open_mcp_extensions}; |
| 63 | use crate::tui::mouse_ui::*; |
| 64 | use crate::tui::notifications; |
| 65 | use crate::tui::onboarding; |
| 66 | use crate::tui::pager::PagerView; |
| 67 | use crate::tui::persistence_actor::{self, PersistRequest}; |
| 68 | use codewhale_config::ProviderKind; |
| 69 | use codewhale_config::hooks::HookEvent; |
| 70 | use codewhale_engine::automation_manager::{ |
| 71 | AutomationManager, AutomationSchedulerConfig, spawn_scheduler, |
| 72 | }; |
| 73 | use codewhale_engine::client::{ |
| 74 | CACHE_WARMUP_MAX_TOKENS, CacheWarmupKey, CodewhaleClient, PromptInspection, |
| 75 | build_cache_warmup_request, inspect_prompt_for_request, |
| 76 | }; |
| 77 | use codewhale_engine::compaction::CompactionConfig; |
| 78 | use codewhale_engine::compaction::{estimate_input_tokens_conservative, estimate_tokens}; |
| 79 | use codewhale_engine::core::engine::{EngineConfig, EngineHandle}; |
| 80 | use codewhale_engine::core::events::Event as EngineEvent; |
| 81 | use codewhale_engine::core::ops::{Op, ProviderRuntimeStatus, UserInputProvenance}; |
| 82 | use codewhale_engine::hooks::{HookExecutor, TurnEndPayloadInput, TurnEndTotals}; |
| 83 | use codewhale_engine::llm_client::LlmClient; |
| 84 | use codewhale_engine::prompts; |
| 85 | #[cfg(test)] |
| 86 | use codewhale_engine::route_runtime::resolve_runtime_route; |
| 87 | use codewhale_engine::route_runtime::resolve_runtime_route_for_identity; |
| 88 | #[cfg(test)] |
| 89 | use codewhale_engine::session_manager::create_saved_session_with_id_and_mode; |
| 90 | use codewhale_engine::session_manager::{ |
| 91 | OfflineQueueState, QueuedSessionMessage, SavedSession, SessionManager, |
| 92 | }; |
| 93 | use codewhale_engine::task_manager::{ |
| 94 | NewTaskRequest, SharedTaskManager, TaskManager, TaskManagerConfig, TaskStatus, TaskSummary, |
| 95 | }; |
| 96 | use codewhale_engine::tools::goal::{GoalSnapshot, GoalStatus}; |
| 97 | use codewhale_engine::tools::shell::{ShellJobSnapshot, ShellStatus}; |
| 98 | use codewhale_engine::tools::spec::{RuntimeToolServices, ToolResult}; |
| 99 | use codewhale_engine::tools::subagent::{ |
| 100 | MailboxMessage, SubAgentStatus, subagent_progress_tool_display_name, |
| 101 | }; |
| 102 | use codewhale_engine::turn_route_plan::{PlannedTurnRoute, TurnRoutePlanRequest, plan_turn_route}; |
| 103 | use codewhale_engine::work_graph::task_owner_snapshot; |
| 104 | use codewhale_localization::{MessageId, tr}; |
| 105 | use codewhale_models::{ContentBlock, Message, MessageRequest, SystemPrompt, Usage}; |
| 106 | use codewhale_palette as palette; |
| 107 | use codewhale_runtime::audit::log_sensitive_event; |
| 108 | #[cfg(test)] |
| 109 | use codewhale_runtime::config::ProviderConfig; |
| 110 | use codewhale_runtime::config::{ |
| 111 | Config, ProviderIdentity, ProvidersConfig, StatusItem, UpdateConfig, |
| 112 | persist_external_credential_consent_for_at, revoke_external_credential_consent_for_at, |
| 113 | }; |
| 114 | use codewhale_runtime::settings::Settings; |
| 115 | use codewhale_tui_kit::event_broker::EventBroker; |
| 116 | use codewhale_tui_kit::scrolling::TranscriptScroll; |
| 117 | // SelectionAutoscroll unused |
| 118 | use crate::tui::history::text::history_cell_to_text; |
| 119 | use crate::tui::motion::{FrameRequester, MotionMode}; |
| 120 | use crate::tui::session_picker::SessionPickerView; |
| 121 | use crate::tui::shell_job_routing::{ |
| 122 | add_shell_job_message, format_shell_job_list, format_shell_poll, open_shell_job_pager, |
| 123 | }; |
| 124 | use crate::tui::streaming_thinking; |
| 125 | use crate::tui::subagent_routing::{ |
| 126 | apply_subagent_terminal_projection, format_task_list, handle_subagent_mailbox_for_turn, |
| 127 | open_task_pager, parent_stop_status, reconcile_subagent_activity_state, running_agent_count, |
| 128 | sort_subagents_in_place, subagent_message_refreshes_workspace_context, task_mode_label, |
| 129 | task_summary_to_panel_entry, |
| 130 | }; |
| 131 | #[cfg(test)] |
| 132 | use crate::tui::subagent_routing::{handle_subagent_mailbox, reconcile_subagent_activity_state_at}; |
| 133 | #[cfg(test)] |
| 134 | use crate::tui::tool_routing::exploring_label; |
| 135 | use crate::tui::tool_routing::{ |
| 136 | apply_owned_workflow_ui_event, handle_tool_call_complete, handle_tool_call_started, |
| 137 | }; |
| 138 | use crate::tui::user_input::UserInputView; |
| 139 | use crate::tui::views::subagent_view_agents; |
| 140 | use crate::tui::vim_mode; |
| 141 | use crate::tui::workspace_context; |
| 142 | use codewhale_tui_kit::streaming::StreamDisplayClock; |
| 143 | |
| 144 | use codewhale_engine::reasoning_preference::{EffectiveReasoningEffort, ReasoningEffort}; |
| 145 | |
| 146 | use super::key_actions; |
| 147 | |
| 148 | use super::app::{ |
| 149 | ActiveCompaction, ActiveTurnMetadata, AgentCurrentActivity, App, AppAction, |
| 150 | ComposerSubmitAction, ComposerSubmitChord, GoalControlIntent, OnboardingState, |
| 151 | PendingGoalControl, PendingProviderSwitch, QueuedMessage, RedactionGateNotice, StatusToast, |
| 152 | StatusToastKind, StatusToastLevel, SubmitDisposition, TaskPanelEntry, TaskPanelEntryKind, |
| 153 | ToolEvidence, TuiOptions, bound_agent_activity_text, is_stop_word, |
| 154 | looks_like_slash_command_input, shell_command_from_bang_input, |
| 155 | }; |
| 156 | use super::approval::{ |
| 157 | ApprovalRequest, ApprovalView, ElevationRequest, ElevationView, ReviewDecision, |
| 158 | }; |
| 159 | use super::history::CellFoldAction; |
| 160 | use super::history::ExecCell; |
| 161 | use super::history::HistoryCell; |
| 162 | use super::history::ToolCell; |
| 163 | use super::history::ToolStatus; |
| 164 | use super::history::TranscriptFold; |
| 165 | use super::history::history_cells_from_message; |
| 166 | use super::slash_menu::{ |
| 167 | apply_slash_menu_selection, partial_inline_skill_mention_at_cursor, |
| 168 | try_autocomplete_slash_command, visible_slash_menu_entries, |
| 169 | }; |
| 170 | use super::views::{ConfigView, HelpView, ModalKind, ViewAction, ViewEvent}; |
| 171 | use super::widgets::pending_input_preview::{ContextPreviewItem, PendingInputPreview}; |
| 172 | use super::widgets::{ChatWidget, ComposerWidget, Renderable}; |
| 173 | use codewhale_app_server::exec_agent::summarize_tool_output; |
| 174 | |
| 175 | // Activity Detail / raw-detail / pager-text helpers extracted into `activity_detail` |
| 176 | // (issue #4103). Re-export the cross-module entry points so existing |
| 177 | // `crate::tui::ui::{...}` importers (mouse_ui, footer_ui) keep resolving, and |
| 178 | // import the ui-internal entry points used from this file's own body. |
| 179 | pub(crate) use self::activity_detail::{ |
| 180 | completed_assistant_answer_text, copy_cell_to_clipboard, detail_target_label, |
| 181 | open_details_pager_for_cell, open_focused_cell_pager, turn_handoff_markdown, |
| 182 | }; |
| 183 | use self::activity_detail::{ |
| 184 | copy_focused_cell, detail_target_cell_index, extract_reasoning_header, |
| 185 | open_reasoning_detail_pager, open_tool_details_pager, open_turn_inspector_pager, |
| 186 | }; |
| 187 | // Ctrl+O now opens the full recorded Reasoning Detail for the selected or |
| 188 | // current reasoning block. The whole-turn Turn Inspector moved to Ctrl+Alt+O |
| 189 | // and `/turn inspect`. (`v` raw leaf detail keeps using `open_tool_details_pager`.) |
| 190 | |
| 191 | // === Constants === |
| 192 | |
| 193 | /// Upper bound on slash-menu entries returned to the renderer. The composer's |
| 194 | /// render path already paginates with center-tracking (see |
| 195 | /// `widgets::ComposerWidget::render`), so this only needs to be high enough to |
| 196 | /// encompass the full filtered command list — never the visible-row budget. |
| 197 | /// Bumped from 6 to 128 to fix #64 (selection couldn't reach commands beyond |
| 198 | /// the visible window because the source list itself was capped). |
| 199 | const SLASH_MENU_LIMIT: usize = 128; |
| 200 | const MIN_CHAT_HEIGHT: u16 = 3; |
| 201 | const MIN_COMPOSER_HEIGHT: u16 = 2; |
| 202 | use codewhale_runtime::context_budget::{ |
| 203 | CONTEXT_CRITICAL_THRESHOLD_PERCENT, CONTEXT_WARNING_THRESHOLD_PERCENT, |
| 204 | }; |
| 205 | const CONTEXT_SUGGEST_COMPACT_THRESHOLD_PERCENT: f64 = 60.0; |
| 206 | const UI_IDLE_POLL_MS: u64 = 48; |
| 207 | const UI_ACTIVE_POLL_MS: u64 = 24; |
| 208 | const SUBAGENT_HOOK_PREVIEW_LIMIT: usize = 2_048; |
| 209 | const DISPATCH_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(30); |
| 210 | /// Wall-clock time a turn may stay in `"in_progress"` with no activity before |
| 211 | /// the UI assumes the engine stalled (sub-agent hang, lost completion event, |
| 212 | /// engine panic) — unless the engine heartbeat reports a live bounded wait. |
| 213 | const TURN_STALL_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(300); |
| 214 | /// Running tools can legitimately exceed the silent-turn timeout, but a tool |
| 215 | /// with no progress heartbeat or output beyond this ceiling is treated as hung. |
| 216 | // Must stay comfortably above `turn_stall_watchdog_timeout` so a running tool |
| 217 | // gets extra grace beyond the turn-stall threshold (#1862 trimmed 15m → 10m). |
| 218 | const TOOL_HANG_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(600); |
| 219 | // Forced repaint cadence while a turn is live (model loading, compacting, |
| 220 | // sub-agents running). Drives the footer water-spout animation as well as |
| 221 | // the per-tool spinner pulse — keep this fast enough that the whale-spout |
| 222 | // braille pattern reads as continuous motion instead of teleport-frames. |
| 223 | const UI_STATUS_ANIMATION_MS: u64 = codewhale_tui_kit::spinner::BRAILLE_SPINNER_FRAME_MS; |
| 224 | const UI_QUIET_STATUS_ANIMATION_MS: u64 = 1_000; |
| 225 | const UI_ACTIVITY_ANIMATION_MS: u64 = |
| 226 | (1_000.0 / codewhale_ratatui::tokens::MOTION_LOOP_FPS_CAP) as u64; |
| 227 | /// Ambient fish, the idle-mark caustic, and the completion wake use a modest |
| 228 | /// ~12.5fps clock by default. On measured high-Hz displays the adaptive probe |
| 229 | /// may raise this (still bounded); low_motion always freezes the cadence. |
| 230 | /// Active markers run at 8fps; atmosphere stays subordinate. |
| 231 | pub(crate) const UI_UNDERWATER_ANIMATION_MS: u64 = 80; |
| 232 | /// Full-motion compatibility cadence for VTE, tmux, and other terminals that |
| 233 | /// explicitly request the 30 FPS safety cap. |
| 234 | pub(crate) const UI_CONSTRAINED_UNDERWATER_ANIMATION_MS: u64 = 34; |
| 235 | /// 30 FPS Ghostty atmosphere clock. Input, streaming, and other interactive |
| 236 | /// state still request immediate frames up to the separate 60 FPS draw cap; |
| 237 | /// idle water no longer forces a full-screen repaint at that rate. |
| 238 | pub(crate) const UI_GHOSTTY_UNDERWATER_ANIMATION_MS: u64 = 34; |
| 239 | // Minimum chat-host width at which the file-tree pane renders. At an |
| 240 | // 80-column terminal the file tree owns 20 columns, leaving a 60-column chat |
| 241 | // host; below this floor the tree is hidden rather than squeezing the |
| 242 | // transcript under 40 columns. (Named for the file tree — the legacy sidebar |
| 243 | // this constant once described no longer gates on it.) |
| 244 | pub(crate) const FILE_TREE_MIN_HOST_WIDTH: u16 = 60; |
| 245 | const SESSION_TITLE_MAX_CHARS: usize = 32; |
| 246 | const VERSION_HINT_TOAST_TTL_MS: u64 = 12_000; |
| 247 | |
| 248 | const REQUIRED_RELEASE_ASSETS: &[&str] = &[ |
| 249 | "codewhale-linux-x64", |
| 250 | "codew-linux-x64", |
| 251 | "codewhale-linux-arm64", |
| 252 | "codew-linux-arm64", |
| 253 | "codewhale-android-arm64", |
| 254 | "codew-android-arm64", |
| 255 | "codewhale-macos-x64", |
| 256 | "codew-macos-x64", |
| 257 | "codewhale-macos-arm64", |
| 258 | "codew-macos-arm64", |
| 259 | "codewhale-windows-x64.exe", |
| 260 | "codew-windows-x64.exe", |
| 261 | "codewhale.bat", |
| 262 | "codewhale-windows-arm64.exe", |
| 263 | "codew-windows-arm64.exe", |
| 264 | "codewhale-linux-x64.tar.gz", |
| 265 | "codewhale-linux-arm64.tar.gz", |
| 266 | "codewhale-android-arm64.tar.gz", |
| 267 | "codewhale-macos-x64.tar.gz", |
| 268 | "codewhale-macos-arm64.tar.gz", |
| 269 | "codewhale-windows-x64.zip", |
| 270 | "codewhale-windows-x64-portable.zip", |
| 271 | "codewhale-windows-arm64.zip", |
| 272 | "codewhale-windows-arm64-portable.zip", |
| 273 | "CodeWhaleSetup.exe", |
| 274 | "codewhale-bundles-sha256.txt", |
| 275 | "codewhale-artifacts-sha256.txt", |
| 276 | ]; |
| 277 | |
| 278 | type AppTerminal = Terminal<ColorCompatBackend<Stdout>>; |
| 279 | |
| 280 | type PendingToolUses = Vec<ContentBlock>; |
| 281 | |
| 282 | #[derive(Debug)] |
| 283 | enum TranslationEvent { |
| 284 | AssistantMessage { |
| 285 | origin_session_fingerprint: Option<String>, |
| 286 | origin_turn_fingerprint: Option<String>, |
| 287 | history_index: Option<usize>, |
| 288 | original_text: String, |
| 289 | translated: anyhow::Result<String>, |
| 290 | usage: Option<codewhale_models::Usage>, |
| 291 | thinking: Option<String>, |
| 292 | tool_uses: PendingToolUses, |
| 293 | }, |
| 294 | Thinking { |
| 295 | origin_session_fingerprint: Option<String>, |
| 296 | origin_turn_fingerprint: Option<String>, |
| 297 | translation_id: u64, |
| 298 | translated: anyhow::Result<String>, |
| 299 | usage: Option<codewhale_models::Usage>, |
| 300 | }, |
| 301 | } |
| 302 | |
| 303 | // Reset scroll region (`\x1b[r`), origin mode (`\x1b[?6l`), and home the cursor |
| 304 | // (`\x1b[H`) before letting ratatui's diff renderer repaint. The destructive |
| 305 | // `\x1b[2J\x1b[3J` pair was previously appended here to also wipe the visible |
| 306 | // screen and saved scrollback, but combined with the immediately-following |
| 307 | // `terminal.clear()` it produced a double-clear that several terminals |
| 308 | // (Ghostty, VSCode terminal, Win10 conhost) render as visible flicker on every |
| 309 | // TurnComplete / focus-gain / resize. The alt-screen buffer's double-buffering |
| 310 | // plus ratatui's `terminal.clear()` are sufficient to repaint cleanly. |
| 311 | const TERMINAL_ORIGIN_RESET: &[u8] = b"\x1b[r\x1b[?6l\x1b[H"; |
| 312 | // Xterm alternate-scroll mode (DECSET 1007) converts wheel input into arrow |
| 313 | // keys. It is only meaningful when mouse reporting is unavailable; while |
| 314 | // mouse capture is active the terminal must deliver wheel events as mouse |
| 315 | // events, so 1007 stays off (iTerm2 converts anyway, breaking transcript |
| 316 | // wheel-scroll — #5223). `--no-mouse-capture` also keeps it off so the host |
| 317 | // terminal owns raw mouse selection behavior end-to-end (#4026). |
| 318 | const ENABLE_ALT_SCROLL_MODE: &[u8] = b"\x1b[?1007h"; |
| 319 | const DISABLE_ALT_SCROLL_MODE: &[u8] = b"\x1b[?1007l"; |
| 320 | /// Begin synchronized update (DEC 2026): tell the terminal to defer |
| 321 | /// rendering until END_SYNC_UPDATE is received. Best-effort — |
| 322 | /// terminals that don't support this silently ignore the sequence. |
| 323 | /// Reduces flicker on GPU-accelerated terminals (Ghostty, VSCode |
| 324 | /// Terminal, Kitty, WezTerm) by batching ratatui's incremental |
| 325 | /// diff writes into a single frame. |
| 326 | const BEGIN_SYNC_UPDATE: &[u8] = b"\x1b[?2026h"; |
| 327 | /// End synchronized update (DEC 2026): tell the terminal to render |
| 328 | /// the complete frame now. |
| 329 | const END_SYNC_UPDATE: &[u8] = b"\x1b[?2026l"; |
| 330 | /// Throttled in-progress checkpoint while a turn is live (#1830 progress loss). |
| 331 | const RECOVERY_SNAPSHOT_INTERVAL: Duration = Duration::from_secs(45); |
| 332 | |
| 333 | /// Where a key goes while onboarding owns the screen (#4763). |
| 334 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 335 | pub(crate) enum OnboardingKeyRoute { |
| 336 | /// Terminate the session. Ctrl+C is unconditional during onboarding. |
| 337 | Quit, |
| 338 | /// Hand the key to the provider picker on the view stack. |
| 339 | ProviderPicker, |
| 340 | AccountLogin, |
| 341 | /// Take the advertised offline exit (#3927). Reachable from Provider |
| 342 | /// setup even while the provider picker owns the screen, so the choice is |
| 343 | /// never hidden behind a modal the user cannot satisfy. |
| 344 | ExploreOffline, |
| 345 | /// Fall through to the legacy onboarding key switch. |
| 346 | Legacy, |
| 347 | } |
| 348 | |
| 349 | fn surface_prompt_override_notices(app: &mut App) { |
| 350 | for notice in prompts::take_prompt_override_notices() { |
| 351 | app.add_message(HistoryCell::System { |
| 352 | content: format!("Warning: {notice}"), |
| 353 | }); |
| 354 | app.push_status_toast(notice, StatusToastLevel::Warning, Some(12_000)); |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | #[cfg(test)] |
| 359 | #[test] |
| 360 | fn tui_launch_preflight_explains_non_tty_failure() { |
| 361 | assert!(require_interactive_terminal(true, true).is_ok()); |
| 362 | for (stdin_is_tty, stdout_is_tty) in [(false, true), (true, false), (false, false)] { |
| 363 | let err = require_interactive_terminal(stdin_is_tty, stdout_is_tty) |
| 364 | .expect_err("a missing TTY must fail before raw mode"); |
| 365 | let message = err.to_string(); |
| 366 | assert!(message.contains("interactive terminal"), "{message}"); |
| 367 | assert!(message.contains("codewhale exec"), "{message}"); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | #[cfg(unix)] |
| 372 | #[test] |
| 373 | fn tui_launch_preflight_rejects_background_process_group() { |
| 374 | assert!(validate_foreground_process_group(41, 41).is_ok()); |
| 375 | let err = validate_foreground_process_group(41, 42) |
| 376 | .expect_err("a background process group must fail before raw mode"); |
| 377 | let message = err.to_string(); |
| 378 | assert!(message.contains("background or suspended"), "{message}"); |
| 379 | assert!(message.contains("Run `fg`"), "{message}"); |
| 380 | assert!(message.contains("codewhale exec"), "{message}"); |
| 381 | } |
| 382 | |
| 383 | fn resume_hint_text( |
| 384 | locale: codewhale_localization::Locale, |
| 385 | session_id: Option<&str>, |
| 386 | terminal_output: bool, |
| 387 | ) -> Option<String> { |
| 388 | use codewhale_localization::{MessageId, tr}; |
| 389 | if !terminal_output { |
| 390 | return None; |
| 391 | } |
| 392 | let session_id = session_id.filter(|id| !id.trim().is_empty())?; |
| 393 | // Reconstruct a canonical UUID rather than interpolating a stored string |
| 394 | // into a shell command or terminal output. Legacy/noncanonical identities |
| 395 | // get the existing picker, never an ambiguous "most recent" shortcut. |
| 396 | let canonical = uuid::Uuid::parse_str(session_id) |
| 397 | .ok() |
| 398 | .map(|id| id.hyphenated().to_string()) |
| 399 | .filter(|id| id == session_id); |
| 400 | let (message, command) = match canonical { |
| 401 | Some(id) => ( |
| 402 | MessageId::ResumeExactSessionHint, |
| 403 | format!("codewhale resume {id}"), |
| 404 | ), |
| 405 | None => ( |
| 406 | MessageId::ResumeSavedSessionHint, |
| 407 | "codewhale resume".to_string(), |
| 408 | ), |
| 409 | }; |
| 410 | Some(tr(locale, message).replace("{command}", &command)) |
| 411 | } |
| 412 | |
| 413 | struct TerminalCleanupGuard { |
| 414 | use_bracketed_paste: bool, |
| 415 | defused: bool, |
| 416 | } |
| 417 | |
| 418 | impl Drop for TerminalCleanupGuard { |
| 419 | fn drop(&mut self) { |
| 420 | if self.defused { |
| 421 | return; |
| 422 | } |
| 423 | |
| 424 | let mut stdout = io::stdout(); |
| 425 | pop_keyboard_enhancement_flags(&mut stdout); |
| 426 | disable_alternate_scroll_mode(&mut stdout); |
| 427 | let _ = execute!(stdout, DisableFocusChange); |
| 428 | let _ = disable_raw_mode(); |
| 429 | // The live screen, not the one startup chose: `/inline` moves it. |
| 430 | if live_alt_screen() { |
| 431 | let _ = leave_alt_screen(&mut stdout); |
| 432 | } |
| 433 | // Capture follows the screen at runtime too; disabling it when it was |
| 434 | // never on is harmless (the emergency path already does). |
| 435 | let _ = execute!(stdout, DisableMouseCapture); |
| 436 | if self.use_bracketed_paste { |
| 437 | disable_bracketed_paste_mode(&mut stdout); |
| 438 | } |
| 439 | let _ = execute!(stdout, crossterm::cursor::Show); |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | /// Recognise composer input that is a `# foo` memory quick-add (#492). |
| 444 | /// |
| 445 | /// Returns `true` for inputs that: |
| 446 | /// - start with `#`, |
| 447 | /// - have at least one non-whitespace character after the leading `#`, |
| 448 | /// - are a single line (no embedded `\n`), and |
| 449 | /// - are not a shebang (`#!`) or Markdown heading (`## …`, `### …`). |
| 450 | /// |
| 451 | /// Multi-`#` prefixes are deliberately rejected so users can paste |
| 452 | /// Markdown headings into the composer without triggering the quick-add. |
| 453 | #[must_use] |
| 454 | fn is_memory_quick_add(input: &str) -> bool { |
| 455 | let trimmed = input.trim_start(); |
| 456 | if !trimmed.starts_with('#') { |
| 457 | return false; |
| 458 | } |
| 459 | if trimmed.starts_with("##") || trimmed.starts_with("#!") { |
| 460 | return false; |
| 461 | } |
| 462 | if input.contains('\n') { |
| 463 | return false; |
| 464 | } |
| 465 | // Require something after the `#`. |
| 466 | !trimmed.trim_start_matches('#').trim().is_empty() |
| 467 | } |
| 468 | |
| 469 | fn should_intercept_memory_quick_add(config: &Config, input: &str) -> bool { |
| 470 | config.memory_enabled() && is_memory_quick_add(input) |
| 471 | } |
| 472 | |
| 473 | #[cfg(test)] |
| 474 | mod memory_quick_add_tests { |
| 475 | use super::should_intercept_memory_quick_add; |
| 476 | use codewhale_runtime::config::Config; |
| 477 | |
| 478 | #[test] |
| 479 | fn memory_quick_add_interception_requires_memory_opt_in() { |
| 480 | let enabled: Config = toml::from_str( |
| 481 | r#" |
| 482 | [memory] |
| 483 | enabled = true |
| 484 | "#, |
| 485 | ) |
| 486 | .expect("parse enabled memory config"); |
| 487 | assert!(should_intercept_memory_quick_add( |
| 488 | &enabled, |
| 489 | "# remember this" |
| 490 | )); |
| 491 | |
| 492 | let disabled: Config = Config::default(); |
| 493 | assert!(!should_intercept_memory_quick_add( |
| 494 | &disabled, |
| 495 | "# remember this" |
| 496 | )); |
| 497 | assert!(!should_intercept_memory_quick_add( |
| 498 | &enabled, |
| 499 | "## Markdown heading" |
| 500 | )); |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | async fn spawn_tui_engine( |
| 505 | app: &mut App, |
| 506 | api_config: &Config, |
| 507 | mcp_handoff: Option<codewhale_engine::mcp::McpHandoff>, |
| 508 | ) -> EngineHandle { |
| 509 | let handle = codewhale_engine::core::engine::spawn_tui_engine( |
| 510 | build_engine_config(app, api_config), |
| 511 | api_config, |
| 512 | mcp_handoff, |
| 513 | ) |
| 514 | .await; |
| 515 | app.mcp_snapshot_generation = 0; |
| 516 | app.mcp_snapshot_generation_invalidated = false; |
| 517 | // Prime durable agent + coordination state through the same engine event |
| 518 | // used by later refreshes. All TUI engine replacements use this wrapper, |
| 519 | // so workspace switches and provider recovery cannot retain stale Work. |
| 520 | let _ = handle.try_send(Op::ListSubAgents); |
| 521 | handle |
| 522 | } |
| 523 | |
| 524 | async fn retire_tui_engine( |
| 525 | app: &mut App, |
| 526 | engine_handle: &EngineHandle, |
| 527 | ) -> Option<codewhale_engine::mcp::McpHandoff> { |
| 528 | let mcp_handoff = engine_handle.retire_mcp_for_handoff(); |
| 529 | let active = app |
| 530 | .active_compaction |
| 531 | .as_ref() |
| 532 | .map(|active| (active.id.clone(), active.auto)); |
| 533 | let queued = (app.manual_compaction_queued && app.deferred_manual_compaction.is_none()) |
| 534 | .then(|| app.manual_compaction_id.clone().unwrap_or_default()); |
| 535 | for id in active.iter().map(|(id, _)| id).chain(queued.iter()) { |
| 536 | let _ = engine_handle.cancel_compaction(id.clone()); |
| 537 | } |
| 538 | let _ = engine_handle.send(Op::Shutdown).await; |
| 539 | if active.is_some() || queued.is_some() { |
| 540 | let (id, auto) = active.unwrap_or_else(|| (queued.unwrap_or_default(), false)); |
| 541 | app.manual_compaction_queued = false; |
| 542 | app.manual_compaction_id = None; |
| 543 | let text = app |
| 544 | .tr(MessageId::ContextCompactionStoppedOnEngineSwitch) |
| 545 | .into_owned(); |
| 546 | apply_compaction_cancelled(app, &id, auto, text); |
| 547 | } |
| 548 | if std::mem::take(&mut app.is_purging) { |
| 549 | let text = app |
| 550 | .tr(MessageId::ContextPurgeAbandonedOnEngineSwitch) |
| 551 | .into_owned(); |
| 552 | add_compaction_receipt(app, &text); |
| 553 | app.push_status_toast(text, StatusToastLevel::Warning, Some(5_000)); |
| 554 | } |
| 555 | mcp_handoff |
| 556 | } |
| 557 | |
| 558 | async fn replace_tui_engine(app: &mut App, api_config: &Config, engine_handle: &mut EngineHandle) { |
| 559 | let mcp_handoff = retire_tui_engine(app, engine_handle).await; |
| 560 | *engine_handle = spawn_tui_engine(app, api_config, mcp_handoff).await; |
| 561 | } |
| 562 | |
| 563 | /// Startup and consent-triggered replacement restore the same conversation |
| 564 | /// before admitting any pending input. The existing engine remains the sole |
| 565 | /// owner of model-facing history and the frozen system prefix. |
| 566 | async fn spawn_tui_engine_with_session( |
| 567 | app: &mut App, |
| 568 | config: &Config, |
| 569 | mcp_handoff: Option<codewhale_engine::mcp::McpHandoff>, |
| 570 | ) -> Result<EngineHandle> { |
| 571 | let handle = spawn_tui_engine(app, config, mcp_handoff).await; |
| 572 | let restored = async { |
| 573 | { |
| 574 | handle |
| 575 | .send(Op::SyncSession { |
| 576 | expected: None, |
| 577 | control: app.session_sync_control(), |
| 578 | session_id: app.current_session_id.clone(), |
| 579 | messages: app.api_messages.as_ref().clone(), |
| 580 | system_prompt: app.system_prompt.clone(), |
| 581 | system_prompt_override: false, |
| 582 | model: app.model.clone(), |
| 583 | workspace: app.workspace.clone(), |
| 584 | mode: app.mode, |
| 585 | agent_preset: app.agent_preset(), |
| 586 | }) |
| 587 | .await?; |
| 588 | } |
| 589 | // FIFO snapshot acknowledgement also proves the restore was processed. |
| 590 | let snapshot = handle.get_session_snapshot().await?; |
| 591 | app.system_prompt = snapshot.system_prompt; |
| 592 | Ok::<_, anyhow::Error>(()) |
| 593 | } |
| 594 | .await; |
| 595 | if let Err(error) = restored { |
| 596 | let _ = handle.send(Op::Shutdown).await; |
| 597 | return Err(error); |
| 598 | } |
| 599 | Ok(handle) |
| 600 | } |
| 601 | |
| 602 | fn configured_instruction_sources(config: &Config) -> Vec<prompts::InstructionSource> { |
| 603 | config |
| 604 | .instructions_paths() |
| 605 | .into_iter() |
| 606 | .map(Into::into) |
| 607 | .collect() |
| 608 | } |
| 609 | |
| 610 | /// Open the exact effective base-prompt preview (#3928). |
| 611 | /// |
| 612 | /// Assembles the prompt through [`build_app_system_prompt_with_goal`] — the same |
| 613 | /// function the dispatch path calls — so the preview is the next turn's bytes, |
| 614 | /// not a reconstruction of them. Nothing is sent and no tool catalog is |
| 615 | /// expanded; the preview is a pure read. |
| 616 | fn preview_effective_base_prompt(app: &mut App, config: &Config) { |
| 617 | use codewhale_engine::prompts::base_preview; |
| 618 | |
| 619 | let prompt = build_app_system_prompt_with_goal(app, config, app.goal.objective.as_deref()); |
| 620 | let home = codewhale_config::codewhale_home().ok(); |
| 621 | let constitution_path = codewhale_config::UserConstitution::path().ok(); |
| 622 | let sources = base_preview::PreviewSources { |
| 623 | base_prompt: Some(codewhale_engine::prompts::effective_base_prompt_source( |
| 624 | home.as_deref(), |
| 625 | )), |
| 626 | user_constitution_path: constitution_path.as_deref(), |
| 627 | workspace: Some(app.workspace.as_path()), |
| 628 | home: home.as_deref(), |
| 629 | }; |
| 630 | let report = base_preview::render_report(&base_preview::preview(&prompt, &sources)); |
| 631 | let width = app |
| 632 | .viewport |
| 633 | .last_transcript_area |
| 634 | .map(|area| area.width) |
| 635 | .unwrap_or(80); |
| 636 | app.view_stack.push(crate::tui::pager::PagerView::from_text( |
| 637 | codewhale_engine::prompts::base_preview::PREVIEW_TITLE, |
| 638 | &report, |
| 639 | width.saturating_sub(2), |
| 640 | )); |
| 641 | } |
| 642 | |
| 643 | /// Minimum interval between balance API fetches to avoid flooding. |
| 644 | const BALANCE_FETCH_COOLDOWN: Duration = Duration::from_secs(60); |
| 645 | |
| 646 | /// Shared `reqwest::Client` for balance fetches so connection pools are |
| 647 | /// reused across successive background polls. |
| 648 | static BALANCE_CLIENT: LazyLock<::reqwest::Client> = LazyLock::new(|| { |
| 649 | codewhale_net::proxy::install_loopback_proxy(codewhale_release::tls::reqwest_client_builder()) |
| 650 | .timeout(Duration::from_secs(10)) |
| 651 | .build() |
| 652 | .unwrap_or_default() |
| 653 | }); |
| 654 | |
| 655 | #[derive(Debug)] |
| 656 | pub(crate) struct CacheWarmupOutcome { |
| 657 | usage: Usage, |
| 658 | tool_projection_warning: Option<codewhale_models::ToolProjectionWarning>, |
| 659 | provider_identity: String, |
| 660 | model: String, |
| 661 | base_url: String, |
| 662 | inspection: PromptInspection, |
| 663 | } |
| 664 | |
| 665 | /// Install a completed constitution draft into the setup wizard (if still on |
| 666 | /// top) and open its ratification preview, or surface a failure. Called from |
| 667 | /// the event loop when the background draft lands, and directly on the |
| 668 | /// pre-spawn provider-construction failure. |
| 669 | fn deliver_constitution_draft_result( |
| 670 | app: &mut App, |
| 671 | model_label: String, |
| 672 | locale: codewhale_localization::Locale, |
| 673 | outcome: Result<Box<codewhale_config::UserConstitution>, String>, |
| 674 | ) { |
| 675 | match outcome { |
| 676 | Ok(constitution) => { |
| 677 | if app.view_stack.top_kind() == Some(ModalKind::SetupWizard) |
| 678 | && let Some(mut boxed) = app.view_stack.pop() |
| 679 | { |
| 680 | let preview = boxed |
| 681 | .as_any_mut() |
| 682 | .downcast_mut::<crate::tui::setup::SetupWizardView>() |
| 683 | .and_then(|wizard| { |
| 684 | wizard.install_model_draft(constitution, model_label.clone()) |
| 685 | }); |
| 686 | app.view_stack.push_boxed(boxed); |
| 687 | if let Some((title, content)) = preview { |
| 688 | open_text_pager(app, title, content); |
| 689 | app.show_command_result( |
| 690 | crate::tui::setup::model_draft_ready_message(locale, &model_label), |
| 691 | StatusToastLevel::Success, |
| 692 | ); |
| 693 | } |
| 694 | } |
| 695 | } |
| 696 | Err(reason) => { |
| 697 | app.show_command_result( |
| 698 | crate::tui::setup::model_draft_failed_message(locale, &model_label, &reason), |
| 699 | StatusToastLevel::Error, |
| 700 | ); |
| 701 | } |
| 702 | } |
| 703 | app.needs_redraw = true; |
| 704 | } |
| 705 | |
| 706 | /// Install a completed fleet-profile draft into the wizard (if it is still on |
| 707 | /// top), or surface a failure. Called from the event loop when the |
| 708 | /// background draft lands, and directly on the pre-spawn |
| 709 | /// provider-construction failure. |
| 710 | /// |
| 711 | /// The preview renders inline on the wizard's own Review step — deliberately |
| 712 | /// NOT in a separate pager (#4093): a standalone pager view owns its own |
| 713 | /// `g`/`G` scroll bindings and would swallow the ratify keypress, forcing an |
| 714 | /// Esc-then-g round trip before the user could actually save. |
| 715 | fn deliver_fleet_draft_result( |
| 716 | app: &mut App, |
| 717 | model_label: String, |
| 718 | picked_route: Option<(String, String)>, |
| 719 | reasoning_effort: Option<String>, |
| 720 | outcome: Result<Box<codewhale_engine::fleet::profile::FleetProfileDraft>, String>, |
| 721 | locale: codewhale_localization::Locale, |
| 722 | ) { |
| 723 | match outcome { |
| 724 | Ok(draft) => { |
| 725 | if app.view_stack.top_kind() == Some(ModalKind::FleetSetup) |
| 726 | && let Some(mut boxed) = app.view_stack.pop() |
| 727 | { |
| 728 | let installed = boxed |
| 729 | .as_any_mut() |
| 730 | .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>() |
| 731 | .and_then(|wizard| { |
| 732 | wizard.install_model_draft( |
| 733 | draft, |
| 734 | model_label.clone(), |
| 735 | picked_route.clone(), |
| 736 | reasoning_effort.clone(), |
| 737 | ) |
| 738 | }) |
| 739 | .is_some(); |
| 740 | app.view_stack.push_boxed(boxed); |
| 741 | if installed { |
| 742 | app.show_command_result(match locale { |
| 743 | codewhale_localization::Locale::ZhHans => { |
| 744 | format!("{model_label} 已起草配置。请查看下方 TOML,然后按 g 保存。") |
| 745 | } |
| 746 | _ => format!( |
| 747 | "{model_label} drafted the profile. Review the TOML below, then press g to save." |
| 748 | ), |
| 749 | }, StatusToastLevel::Success); |
| 750 | } |
| 751 | } |
| 752 | } |
| 753 | Err(reason) => { |
| 754 | app.show_command_result(match locale { |
| 755 | codewhale_localization::Locale::ZhHans => { |
| 756 | format!("{model_label} 未能起草配置({reason})。按 Enter 仍会插入编写提示。") |
| 757 | } |
| 758 | _ => format!( |
| 759 | "{model_label} could not draft the profile ({reason}). Enter still inserts the authoring prompt." |
| 760 | ), |
| 761 | }, StatusToastLevel::Error); |
| 762 | } |
| 763 | } |
| 764 | app.needs_redraw = true; |
| 765 | } |
| 766 | |
| 767 | // `format_*` chip/message builders moved to `tui/format_helpers.rs`. |
| 768 | |
| 769 | fn is_work_graph_mutation_tool(name: &str) -> bool { |
| 770 | matches!( |
| 771 | name, |
| 772 | "update_plan" |
| 773 | | "work_update" |
| 774 | | "checklist_write" |
| 775 | | "todo_write" |
| 776 | | "checklist_add" |
| 777 | | "todo_add" |
| 778 | | "checklist_update" |
| 779 | | "todo_update" |
| 780 | | "task_create" |
| 781 | | "task_cancel" |
| 782 | // Unified durable-task tool (piagent phase B): covers the |
| 783 | // create/cancel actions the legacy names above carried. |
| 784 | | "tasks" |
| 785 | | "exec_shell" |
| 786 | | "exec_shell_wait" |
| 787 | | "exec_shell_cancel" |
| 788 | | "agent" |
| 789 | | "workflow" |
| 790 | ) |
| 791 | } |
| 792 | |
| 793 | /// UI watchdog bound for an in-progress turn with no activity (#6184). |
| 794 | /// |
| 795 | /// Decoupled from `stream_chunk_timeout_secs`: tying it to that budget made |
| 796 | /// the UI watchdog unable to fire before the 900s stream idle timeout. A |
| 797 | /// quiet model wait is protected by the engine heartbeat instead — while the |
| 798 | /// engine reports a bounded wait it has not flagged as overdue, the UI defers |
| 799 | /// to it (`reconcile_turn_liveness_with`). |
| 800 | fn turn_stall_watchdog_timeout(_app: &App) -> Duration { |
| 801 | TURN_STALL_WATCHDOG_TIMEOUT |
| 802 | } |
| 803 | |
| 804 | fn active_turn_has_running_tool(app: &App) -> bool { |
| 805 | app.active_cell.as_ref().is_some_and(|active| { |
| 806 | active.entries().iter().any(|cell| match cell { |
| 807 | HistoryCell::Tool(tool) => tool.is_running(), |
| 808 | _ => false, |
| 809 | }) |
| 810 | }) |
| 811 | } |
| 812 | |
| 813 | // Per-turn notification composition (settings, message body, summary) |
| 814 | // moved to `tui/notifications.rs` alongside the dispatch primitives. |
| 815 | |
| 816 | /// The TUI's copy of a tool result for its API-message mirror. It is the same |
| 817 | /// view the engine gives the model (#6508): whole within the route's inline |
| 818 | /// budget, otherwise cut around a footer that names the saved full output. |
| 819 | /// A separate receipt here used to replace anything over 12,000 characters |
| 820 | /// with a 240-character preview, and that copy is what `SyncSession` sends |
| 821 | /// back to the engine. |
| 822 | fn tool_result_content_for_api_message(app: &App, name: &str, output: &ToolResult) -> String { |
| 823 | let (provider, model, limits, window) = app.effective_budget_route(); |
| 824 | codewhale_engine::core::engine::compact_tool_result_for_route_with_window( |
| 825 | provider, |
| 826 | model, |
| 827 | limits, |
| 828 | window.map(|window| window.tokens), |
| 829 | name, |
| 830 | output, |
| 831 | ) |
| 832 | } |
| 833 | |
| 834 | // Streaming-thinking lifecycle helpers moved to `tui/streaming_thinking.rs`. |
| 835 | |
| 836 | /// Data produced by the async dispatch phase that is needed to apply the |
| 837 | /// post-acceptance mutations to `App`. |
| 838 | #[derive(Debug, Clone)] |
| 839 | pub(crate) struct UserDispatchOutcome { |
| 840 | turn_compaction: CompactionConfig, |
| 841 | effective_provider: ProviderKind, |
| 842 | effective_model: String, |
| 843 | effective_provider_identity: String, |
| 844 | effective_provider_label: String, |
| 845 | effective_reasoning_effort: EffectiveReasoningEffort, |
| 846 | auto_selection: Option<codewhale_engine::model_routing::AutoRouteSelection>, |
| 847 | route_limits: codewhale_config::route::RouteLimits, |
| 848 | context_window: codewhale_engine::route_runtime::ContextWindowResolution, |
| 849 | } |
| 850 | |
| 851 | /// Tell the operator that an explicit "make this my default" request did not |
| 852 | /// take effect, instead of leaving a normal apply summary that reads like |
| 853 | /// success. Silence here is what made the sticky-default bug so confusing. |
| 854 | fn note_startup_default_not_saved(app: &mut App, save_as_startup_default: bool) { |
| 855 | if !save_as_startup_default { |
| 856 | return; |
| 857 | } |
| 858 | let note = "Startup default unchanged — the route was not applied."; |
| 859 | let (text, level) = match app.route_receipt() { |
| 860 | Some(receipt) => (format!("{} · {note}", receipt.text), receipt.level), |
| 861 | None => (note.to_owned(), StatusToastLevel::Warning), |
| 862 | }; |
| 863 | app.show_route_receipt(text, level); |
| 864 | } |
| 865 | |
| 866 | /// Route every Fleet-setup entry point to the storage surface that actually |
| 867 | /// controls the effective roster. A selected v2 Fleet always opens its exact |
| 868 | /// named editor; the legacy profile wizard is reachable only with no selected |
| 869 | /// Fleet. Selection resolution deliberately does not consult project trust. |
| 870 | async fn open_fleet_setup_target(app: &mut App, config: &Config, member_id: Option<&str>) { |
| 871 | use crate::tui::views::fleet_setup::{FleetSetupEditTarget, resolve_fleet_setup_edit_target}; |
| 872 | |
| 873 | let workspace = app.workspace.clone(); |
| 874 | let target = tokio::task::spawn_blocking(move || resolve_fleet_setup_edit_target(&workspace)) |
| 875 | .await |
| 876 | .map_err(|err| err.to_string()) |
| 877 | .and_then(|res| res); |
| 878 | match target { |
| 879 | Ok(FleetSetupEditTarget::SelectedFleet { name, scope }) => { |
| 880 | if app.view_stack.top_kind() == Some(ModalKind::FleetDetail) { |
| 881 | return; |
| 882 | } |
| 883 | let Some(mut view) = crate::tui::views::fleet_detail::FleetDetailView::load_for_member( |
| 884 | app, config, &name, scope, member_id, |
| 885 | ) |
| 886 | .await |
| 887 | else { |
| 888 | app.set_sticky_status( |
| 889 | "Selected team is invalid or unreadable; open /fleet teams to repair or clear the selection. Legacy profiles were not opened." |
| 890 | .to_string(), |
| 891 | StatusToastLevel::Error, |
| 892 | None, |
| 893 | ); |
| 894 | return; |
| 895 | }; |
| 896 | let fleet_name = codewhale_runtime::safe_label::SafeLabel::phrase(&name); |
| 897 | let picker = if member_id.is_some() { |
| 898 | let (editor_id, target) = view.direct_assignment(); |
| 899 | let (role, scope) = view.assignment_context(); |
| 900 | view.route_selection(editor_id, target).map(|selection| { |
| 901 | crate::tui::model_picker::ModelPickerView::new_for_fleet_route( |
| 902 | app, config, target, editor_id, selection, |
| 903 | ) |
| 904 | .with_assignment_context(role, scope) |
| 905 | }) |
| 906 | } else { |
| 907 | None |
| 908 | }; |
| 909 | app.view_stack.push(view); |
| 910 | if let Some(picker) = picker { |
| 911 | app.view_stack.push(picker); |
| 912 | } |
| 913 | app.show_command_result(format!( |
| 914 | "Editing selected team `{fleet_name}` ({}) — legacy profiles will not be changed.", |
| 915 | scope.label() |
| 916 | ), StatusToastLevel::Info); |
| 917 | } |
| 918 | Ok(FleetSetupEditTarget::LegacyProfiles) => { |
| 919 | if app.view_stack.top_kind() == Some(ModalKind::FleetSetup) { |
| 920 | return; |
| 921 | } |
| 922 | if let Some(member_id) = member_id { |
| 923 | match crate::tui::views::fleet_setup::FleetSetupView::new_for_route_assignment( |
| 924 | app, config, member_id, |
| 925 | ) { |
| 926 | Ok(view) => { |
| 927 | if let ViewAction::Emit(ViewEvent::FleetProfileRoutePickRequested { |
| 928 | editor_id, |
| 929 | }) = view.route_pick_request() |
| 930 | && let Some(selection) = view.route_selection(editor_id) |
| 931 | { |
| 932 | let (role, scope) = view.assignment_context(); |
| 933 | let picker = |
| 934 | crate::tui::model_picker::ModelPickerView::new_for_fleet_profile( |
| 935 | app, config, editor_id, selection, |
| 936 | ) |
| 937 | .with_assignment_context(role, scope); |
| 938 | app.view_stack.push(view); |
| 939 | app.view_stack.push(picker); |
| 940 | } |
| 941 | } |
| 942 | Err(reason) => app.set_sticky_status(reason, StatusToastLevel::Error, None), |
| 943 | } |
| 944 | return; |
| 945 | } |
| 946 | let _ = app.next_draft_gen(); |
| 947 | let view = match member_id { |
| 948 | Some(member_id) => crate::tui::views::fleet_setup::FleetSetupView::new_for_role( |
| 949 | app, config, member_id, |
| 950 | ), |
| 951 | None => crate::tui::views::fleet_setup::FleetSetupView::new(app, config), |
| 952 | }; |
| 953 | app.view_stack.push(view); |
| 954 | } |
| 955 | Err(message) => { |
| 956 | app.set_sticky_status(message, StatusToastLevel::Error, None); |
| 957 | } |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | pub(crate) struct ProviderFallbackRollback { |
| 962 | identity: ProviderIdentity, |
| 963 | chain: Option<codewhale_config::ProviderChain>, |
| 964 | } |
| 965 | |
| 966 | // File-picker relevance scoring moved to `tui/file_picker_relevance.rs`. |
| 967 | |
| 968 | #[cfg(test)] |
| 969 | use std::process::{Command, Stdio}; |
| 970 | |
| 971 | // `ui.rs` had grown past 19k lines. These three modules hold the same code, |
| 972 | // moved verbatim, and are re-exported so every existing path still resolves. |
| 973 | mod apply; |
| 974 | mod approval_routing; |
| 975 | pub(crate) mod feedback_host; |
| 976 | use approval_routing::*; |
| 977 | mod event_loop; |
| 978 | mod handlers; |
| 979 | |
| 980 | pub(crate) use apply::*; |
| 981 | pub(crate) use event_loop::*; |
| 982 | pub(crate) use handlers::*; |
| 983 | // The crate-wide glob would otherwise narrow this to `pub(crate)`; `tui/mod.rs` |
| 984 | // re-exports it as the binary's entry point. |
| 985 | pub use event_loop::run_tui; |
| 986 | |
| 987 | mod compaction_flow; |
| 988 | pub(crate) use compaction_flow::*; |
| 989 | pub(crate) use provider_setup::*; |
| 990 | mod dispatch; |
| 991 | mod dispatch_prepare; |
| 992 | mod external_catalog; |
| 993 | pub(crate) use dispatch_prepare::*; |
| 994 | pub(crate) use external_catalog::*; |
| 995 | pub(crate) mod fatal_signal_guard; |
| 996 | // #6169: runtime half of the foreground-ownership contract — restore on stop, |
| 997 | // rebuild on continue. Sits next to the fatal guard because both write the same |
| 998 | // teardown table. |
| 999 | pub(crate) mod job_control_guard; |
| 1000 | pub(crate) mod motion; |
| 1001 | mod observer_hooks; |
| 1002 | mod provider_setup; |
| 1003 | mod release_check; |
| 1004 | mod remote_control_bridge; |
| 1005 | mod task_projection; |
| 1006 | mod terminal; |
| 1007 | mod terminal_input; |
| 1008 | use remote_control_bridge::*; |
| 1009 | use terminal_input::*; |
| 1010 | // #6165: `external_editor` is a sibling of `ui`, and the pump pause now lives |
| 1011 | // inside its `with_suspended_tui` so no editor entry point can forget it. |
| 1012 | pub(crate) use terminal_input::pause_terminal_input_for_child; |
| 1013 | |
| 1014 | pub(crate) use dispatch::*; |
| 1015 | pub(crate) use motion::*; |
| 1016 | pub(crate) use release_check::*; |
| 1017 | pub(crate) use terminal::*; |
| 1018 | |
| 1019 | // `frame` is `pub(crate)` so sibling modules (e.g. the widgets ASCII-safety |
| 1020 | // test) can reach the topbar builders that project `App` state. |
| 1021 | pub(crate) mod frame; |
| 1022 | mod overlays; |
| 1023 | mod provider_routes; |
| 1024 | mod session_state; |
| 1025 | |
| 1026 | pub(crate) use frame::*; |
| 1027 | pub(crate) use overlays::*; |
| 1028 | pub(crate) use provider_routes::*; |
| 1029 | pub(crate) use session_state::*; |
| 1030 | |
| 1031 | #[cfg(test)] |
| 1032 | fn spawn_external_url_command(mut command: Command) -> Result<()> { |
| 1033 | command |
| 1034 | .stdin(Stdio::null()) |
| 1035 | .stdout(Stdio::null()) |
| 1036 | .stderr(Stdio::null()) |
| 1037 | .spawn() |
| 1038 | .map(|_| ()) |
| 1039 | .map_err(|err| anyhow::anyhow!("failed to launch browser command: {err}")) |
| 1040 | } |
| 1041 | |
| 1042 | async fn execute_command_input( |
| 1043 | terminal: &mut AppTerminal, |
| 1044 | app: &mut App, |
| 1045 | engine_handle: &mut EngineHandle, |
| 1046 | config: &mut Config, |
| 1047 | input: &str, |
| 1048 | ) -> Result<bool> { |
| 1049 | if app.pending_fresh_session.is_some() && !commands::pending_session_control_command(input) { |
| 1050 | app.show_command_result("A new session is awaiting Engine confirmation; the current draft and transcript are preserved.".to_string(), StatusToastLevel::Warning); |
| 1051 | return Ok(false); |
| 1052 | } |
| 1053 | let _ = app.note_manual_command_for_tip(input); |
| 1054 | if let Some(parsed_index) = parse_queue_send_command(input) { |
| 1055 | match parsed_index { |
| 1056 | Ok(index) => { |
| 1057 | send_queued_message_at_index_now(app, config, engine_handle, index).await?; |
| 1058 | } |
| 1059 | Err(message) => { |
| 1060 | app.show_command_result(message, StatusToastLevel::Error); |
| 1061 | } |
| 1062 | } |
| 1063 | return Ok(false); |
| 1064 | } |
| 1065 | |
| 1066 | let result = commands::execute_with_config(input, app, config); |
| 1067 | // The NOTES view reads the notes file off the render path on the |
| 1068 | // workspace-context tick; a `/note` change refreshes it at once (#6565). |
| 1069 | if input |
| 1070 | .split_whitespace() |
| 1071 | .next() |
| 1072 | .is_some_and(|command| command.eq_ignore_ascii_case("/note")) |
| 1073 | { |
| 1074 | workspace_context::refresh_now(app, Instant::now()); |
| 1075 | } |
| 1076 | // After /logout: clear the in-memory api_key fields so the next |
| 1077 | // onboarding round entering a new key doesn't see the stale value |
| 1078 | // (#343). The on-disk side is handled by clear_api_key() inside |
| 1079 | // commands::config::logout. |
| 1080 | if input.trim().eq_ignore_ascii_case("/logout") { |
| 1081 | // Only clear the active provider's in-memory API key, not every |
| 1082 | // provider. The on-disk clear_api_key() inside commands::config::logout |
| 1083 | // already removes all saved keys; clearing only the active slot here |
| 1084 | // prevents surprising side-effects when the user has multiple providers |
| 1085 | // configured. |
| 1086 | clear_active_provider_api_key_from_memory(app, config).map_err(anyhow::Error::msg)?; |
| 1087 | app.api_key_env_only = |
| 1088 | codewhale_runtime::config::active_provider_uses_env_only_api_key(config); |
| 1089 | } |
| 1090 | apply_command_result(terminal, app, engine_handle, config, result).await |
| 1091 | } |
| 1092 | |
| 1093 | fn use_bundled_constitution(app: &mut App, config: &Config) { |
| 1094 | let mut state = crate::tui::setup::load_setup_state_for_app(app, config); |
| 1095 | state.complete_constitution_checkpoint( |
| 1096 | codewhale_engine::prompts::CONSTITUTION_CHECKPOINT_VERSION, |
| 1097 | codewhale_config::ConstitutionChoice::Bundled, |
| 1098 | ); |
| 1099 | state.constitution_source = codewhale_config::ConstitutionSource::Bundled; |
| 1100 | state.constitution_validity = codewhale_config::ConstitutionValidity::Unknown; |
| 1101 | state.constitution_preview_hash = None; |
| 1102 | state.set_step( |
| 1103 | codewhale_config::SetupStep::Constitution, |
| 1104 | codewhale_config::StepEntry::new( |
| 1105 | codewhale_config::StepStatus::Verified, |
| 1106 | true, |
| 1107 | codewhale_engine::prompts::CONSTITUTION_CHECKPOINT_VERSION, |
| 1108 | ) |
| 1109 | .with_result("bundled/default constitution"), |
| 1110 | ); |
| 1111 | |
| 1112 | match state.save() { |
| 1113 | Ok(()) => { |
| 1114 | app.show_command_result( |
| 1115 | "Using the bundled/default constitution; custom user-global law is inactive." |
| 1116 | .to_string(), |
| 1117 | StatusToastLevel::Info, |
| 1118 | ); |
| 1119 | } |
| 1120 | Err(err) => { |
| 1121 | app.show_command_result( |
| 1122 | format!("Failed to save constitution choice: {err}"), |
| 1123 | StatusToastLevel::Error, |
| 1124 | ); |
| 1125 | app.add_message(HistoryCell::System { |
| 1126 | content: format!("Failed to save constitution choice: {err}"), |
| 1127 | }); |
| 1128 | } |
| 1129 | } |
| 1130 | app.needs_redraw = true; |
| 1131 | } |
| 1132 | |
| 1133 | fn prepare_config_update_result( |
| 1134 | mut result: commands::CommandResult, |
| 1135 | persist: bool, |
| 1136 | ) -> commands::CommandResult { |
| 1137 | // Live previews can fire on every navigation tick. Suppress routine |
| 1138 | // confirmations, but preserve errors and AppAction so one canonical path |
| 1139 | // remains responsible for both user-visible output and side effects. |
| 1140 | if !persist && !result.is_error { |
| 1141 | result.message = None; |
| 1142 | } |
| 1143 | result |
| 1144 | } |
| 1145 | |
| 1146 | pub(crate) struct ApprovalDecisionEvent { |
| 1147 | tool_id: String, |
| 1148 | tool_name: String, |
| 1149 | decision: ReviewDecision, |
| 1150 | timed_out: bool, |
| 1151 | approval_key: String, |
| 1152 | approval_grouping_key: String, |
| 1153 | persistent_rules: Vec<codewhale_config::ToolAskRule>, |
| 1154 | subject: Option<String>, |
| 1155 | } |
| 1156 | |
| 1157 | fn mark_active_turn_cancelled_locally(app: &mut App) { |
| 1158 | settle_pending_human_requests(app); |
| 1159 | app.retire_action_notices(None); |
| 1160 | // #2739: every local cancel surface (Esc, Ctrl+C, approval abort, paused |
| 1161 | // command abort) must snapshot before it clears turn state. Otherwise |
| 1162 | // --continue reloads the previous save and the interrupted turn vanishes. |
| 1163 | app.streaming_state.reset(); |
| 1164 | app.finalize_active_cell_as_interrupted(); |
| 1165 | app.finalize_streaming_assistant_as_interrupted(); |
| 1166 | persist_recovery_snapshot(app); |
| 1167 | app.is_loading = false; |
| 1168 | // #6800: a dispatch still waiting on engine admission fails back now, not |
| 1169 | // after its 60 s bound; its closure retires `dispatch_in_flight`. |
| 1170 | app.cancel_in_flight_dispatch(); |
| 1171 | app.dispatch_started_at = None; |
| 1172 | event_loop::bank_live_turn_time(app); |
| 1173 | app.turn_started_at = None; |
| 1174 | app.turn_last_activity_at = None; |
| 1175 | app.runtime_turn_id = None; |
| 1176 | app.runtime_turn_status = None; |
| 1177 | app.suppress_stream_events_until_turn_complete = true; |
| 1178 | codewhale_runtime::retry_status::clear(); |
| 1179 | crate::tui::notifications::clear_taskbar_progress(); |
| 1180 | crate::tui::notifications::stop_title_animation_quietly(); |
| 1181 | } |
| 1182 | |
| 1183 | /// The Esc-shaped "cancel the active turn" body, extracted verbatim from the |
| 1184 | /// event loop's `EscapeAction::CancelRequest` arm so the session control |
| 1185 | /// socket's `interrupt` verb and the Esc key cannot drift apart. Returns |
| 1186 | /// `true` when the caller should stop handling the event (compaction cancel |
| 1187 | /// or goal-continuation stop consumed it), `false` otherwise. The caller |
| 1188 | /// keeps its own Esc-specific state (backtrack reset) outside this body. |
| 1189 | pub(crate) fn escape_cancel_request( |
| 1190 | app: &mut App, |
| 1191 | engine_handle: &EngineHandle, |
| 1192 | current_streaming_text: &mut String, |
| 1193 | stream_display_clock: &mut StreamDisplayClock, |
| 1194 | ) -> bool { |
| 1195 | let compacting = app.is_compacting || app.manual_compaction_queued; |
| 1196 | if compacting { |
| 1197 | try_cancel_compaction(app, engine_handle); |
| 1198 | if !compact_interrupt_should_stop_turn(app) { |
| 1199 | return true; |
| 1200 | } |
| 1201 | // Mid-turn compact is collateral. Esc/interrupt stops the turn |
| 1202 | // (Codex/GrokBuild): cancel_compaction alone continues the loop. |
| 1203 | } |
| 1204 | if app.paused || app.paused_goal_objective.is_some() { |
| 1205 | clear_paused_command_state(app, engine_handle); |
| 1206 | if app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) { |
| 1207 | engine_handle.cancel(); |
| 1208 | mark_active_turn_cancelled_locally(app); |
| 1209 | current_streaming_text.clear(); |
| 1210 | stream_display_clock.reset(); |
| 1211 | } |
| 1212 | app.active_allowed_tools = None; |
| 1213 | app.goal.objective = None; |
| 1214 | app.goal.tokens_used = 0; |
| 1215 | app.goal.time_used_seconds = 0; |
| 1216 | app.goal.continuation_count = 0; |
| 1217 | app.show_command_result( |
| 1218 | parent_stop_status(app, "Paused command cancelled"), |
| 1219 | StatusToastLevel::Warning, |
| 1220 | ); |
| 1221 | false |
| 1222 | } else { |
| 1223 | let was_waiting = app.goal_continuation_waiting; |
| 1224 | engine_handle.cancel(); |
| 1225 | if was_waiting { |
| 1226 | app.goal_continuation_waiting = false; |
| 1227 | app.show_command_result( |
| 1228 | app.tr(MessageId::GoalContinuationStopped).to_string(), |
| 1229 | StatusToastLevel::Info, |
| 1230 | ); |
| 1231 | return true; |
| 1232 | } |
| 1233 | mark_active_turn_cancelled_locally(app); |
| 1234 | current_streaming_text.clear(); |
| 1235 | stream_display_clock.reset(); |
| 1236 | app.show_command_result( |
| 1237 | parent_stop_status(app, "Request cancelled"), |
| 1238 | StatusToastLevel::Warning, |
| 1239 | ); |
| 1240 | false |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | /// Stream events a local cancel hides until the turn completes. Approval, |
| 1245 | /// sandbox-elevation, and question requests are never silently hidden: |
| 1246 | /// `resolve_stale_parent_request` answers a stale parent request explicitly, |
| 1247 | /// and a child agent's request is always delivered (approvals C1). |
| 1248 | fn suppress_engine_event_after_local_cancel(event: &EngineEvent) -> bool { |
| 1249 | matches!( |
| 1250 | event, |
| 1251 | EngineEvent::MessageStarted { .. } |
| 1252 | | EngineEvent::MessageDelta { .. } |
| 1253 | | EngineEvent::MessageComplete { .. } |
| 1254 | | EngineEvent::ThinkingStarted { .. } |
| 1255 | | EngineEvent::ThinkingDelta { .. } |
| 1256 | | EngineEvent::ThinkingComplete { .. } |
| 1257 | | EngineEvent::ToolCallStarted { .. } |
| 1258 | | EngineEvent::ToolExecutionStarted { .. } |
| 1259 | | EngineEvent::ToolCallHeartbeat |
| 1260 | | EngineEvent::ToolCallComplete { .. } |
| 1261 | | EngineEvent::SessionUpdated { .. } |
| 1262 | ) |
| 1263 | } |
| 1264 | |
| 1265 | fn ignore_stale_stream_event_while_idle(event: &EngineEvent) -> bool { |
| 1266 | matches!( |
| 1267 | event, |
| 1268 | EngineEvent::MessageStarted { .. } |
| 1269 | | EngineEvent::MessageDelta { .. } |
| 1270 | | EngineEvent::MessageComplete { .. } |
| 1271 | | EngineEvent::ThinkingStarted { .. } |
| 1272 | | EngineEvent::ThinkingDelta { .. } |
| 1273 | | EngineEvent::ThinkingComplete { .. } |
| 1274 | | EngineEvent::ToolCallStarted { .. } |
| 1275 | | EngineEvent::ToolExecutionStarted { .. } |
| 1276 | | EngineEvent::ToolCallHeartbeat |
| 1277 | | EngineEvent::ToolCallComplete { .. } |
| 1278 | ) |
| 1279 | } |
| 1280 | |
| 1281 | /// `Ok` carries the `/models` roster the probe already downloaded, when it |
| 1282 | /// was one complete listing (see [`codewhale_engine::client::verify_provider_api_key`]). |
| 1283 | type ProviderKeyVerification<'a> = Pin< |
| 1284 | Box< |
| 1285 | dyn Future<Output = Result<Option<codewhale_config::catalog::ProviderCatalogDelta>, String>> |
| 1286 | + Send |
| 1287 | + 'a, |
| 1288 | >, |
| 1289 | >; |
| 1290 | |
| 1291 | pub(crate) fn request_shell_wait_detach(app: &mut App) { |
| 1292 | let (notice, level) = match request_active_shell_wait_detach(app) { |
| 1293 | Ok(Some(true)) => ( |
| 1294 | app.tr(MessageId::ShellWaitReleased) |
| 1295 | .replace("{jobs}", "/jobs"), |
| 1296 | StatusToastLevel::Info, |
| 1297 | ), |
| 1298 | Ok(Some(false)) => { |
| 1299 | let message = if terminal_pause_has_live_owner(app) { |
| 1300 | MessageId::ShellWaitInteractive |
| 1301 | } else if app.is_loading { |
| 1302 | MessageId::ShellWaitUnavailable |
| 1303 | } else { |
| 1304 | MessageId::ShellWaitNoActive |
| 1305 | }; |
| 1306 | (app.tr(message).to_string(), StatusToastLevel::Info) |
| 1307 | } |
| 1308 | Ok(None) => ( |
| 1309 | "Shell tracking is busy. Try releasing the wait again.".into(), |
| 1310 | StatusToastLevel::Warning, |
| 1311 | ), |
| 1312 | Err(err) => (err.to_string(), StatusToastLevel::Error), |
| 1313 | }; |
| 1314 | app.push_status_toast(notice, level, Some(6_000)); |
| 1315 | } |
| 1316 | |
| 1317 | fn request_active_shell_wait_detach(app: &App) -> Result<Option<bool>> { |
| 1318 | let Some(session_id) = app.current_session_id.as_deref() else { |
| 1319 | return Ok(Some(false)); |
| 1320 | }; |
| 1321 | let Some(shell_manager) = app.runtime_services.shell_manager.as_ref() else { |
| 1322 | return Ok(Some(false)); |
| 1323 | }; |
| 1324 | match shell_manager.try_lock() { |
| 1325 | Ok(mut manager) => Ok(Some(manager.request_shell_wait_detach(session_id))), |
| 1326 | Err(std::sync::TryLockError::WouldBlock) => Ok(None), |
| 1327 | Err(std::sync::TryLockError::Poisoned(_)) => { |
| 1328 | anyhow::bail!("Shell tracking hit an internal error — restart Codewhale to recover.") |
| 1329 | } |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | pub(crate) fn prefill_jobs_cancel_all_if_tasks_sidebar(app: &mut App) -> bool { |
| 1334 | if !app.view_stack.is_empty() |
| 1335 | || app.work_surface.panel != crate::tui::work_surface::RailPanel::Tasks |
| 1336 | || app.work_surface.last_area.is_none() |
| 1337 | || !app |
| 1338 | .task_panel |
| 1339 | .iter() |
| 1340 | .any(crate::tui::background_indicator::is_live_shell_entry) |
| 1341 | { |
| 1342 | return false; |
| 1343 | } |
| 1344 | |
| 1345 | app.input = "/jobs cancel-all".to_string(); |
| 1346 | app.cursor_position = app.input.len(); |
| 1347 | let prompt = tr(app.ui_locale, MessageId::JobsCancelAllPrompt).replace("{key}", "Enter"); |
| 1348 | app.push_status_toast(prompt, StatusToastLevel::Info, None); |
| 1349 | true |
| 1350 | } |
| 1351 | |
| 1352 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1353 | pub(crate) enum SearchDirection { |
| 1354 | Forward, |
| 1355 | Backward, |
| 1356 | } |
| 1357 | |
| 1358 | pub(crate) fn clamp_event_poll_timeout(timeout: Duration) -> Duration { |
| 1359 | const MIN_EVENT_POLL_TIMEOUT: Duration = Duration::from_millis(1); |
| 1360 | timeout.max(MIN_EVENT_POLL_TIMEOUT) |
| 1361 | } |
| 1362 | |
| 1363 | /// Announce the background work that finished since the last notice, when |
| 1364 | /// the `[notifications].subagent_completion` mode says it is time (#6565). |
| 1365 | /// |
| 1366 | /// Finite work still live (running agents that are not suspect ghosts, a |
| 1367 | /// running workflow, queued or running durable tasks that are not stale) |
| 1368 | /// holds a `final-only` |
| 1369 | /// batch; a running background shell never does. `parent_idle` forces the |
| 1370 | /// parent-turn half of the rule open, for the moment a turn completes. |
| 1371 | /// `settings()` still has the final say (method=off / condition=never). |
| 1372 | pub(crate) fn flush_background_finished(app: &mut App, config: &Config, parent_idle: bool) { |
| 1373 | use crate::tui::background_finished::{background_finished_payload, ready_to_flush}; |
| 1374 | if app.background_finished.is_empty() { |
| 1375 | return; |
| 1376 | } |
| 1377 | let mode = config.notifications_config().subagent_completion; |
| 1378 | let finite_work_live = session_state::live_running_agent_count(app, Instant::now()) > 0 |
| 1379 | || frame::workflow_tool_is_running(app) |
| 1380 | || app.task_panel.iter().any(|entry| { |
| 1381 | // A stale entry (a recovered task whose ownership is unverified) |
| 1382 | // is not known to be running and could hold the batch forever, |
| 1383 | // the same reason suspect ghost agents are left out. |
| 1384 | !entry.stale |
| 1385 | && entry.kind != TaskPanelEntryKind::Shell |
| 1386 | && matches!(entry.status.as_str(), "queued" | "running") |
| 1387 | }); |
| 1388 | let parent_busy = app.is_loading && !parent_idle; |
| 1389 | if !ready_to_flush( |
| 1390 | mode, |
| 1391 | &app.background_finished, |
| 1392 | finite_work_live, |
| 1393 | parent_busy, |
| 1394 | ) { |
| 1395 | return; |
| 1396 | } |
| 1397 | let batch = std::mem::take(&mut app.background_finished); |
| 1398 | if mode == codewhale_config::notifications::SubagentCompletionNotification::Off { |
| 1399 | return; |
| 1400 | } |
| 1401 | let Some((method, threshold, include_summary)) = notifications::settings(config) else { |
| 1402 | return; |
| 1403 | }; |
| 1404 | let in_tmux = std::env::var("TMUX").is_ok_and(|v| !v.is_empty()); |
| 1405 | let notices: Vec<&[crate::tui::background_finished::FinishedWork]> = |
| 1406 | if mode == codewhale_config::notifications::SubagentCompletionNotification::Always { |
| 1407 | batch.chunks(1).collect() |
| 1408 | } else { |
| 1409 | vec![batch.as_slice()] |
| 1410 | }; |
| 1411 | for items in notices { |
| 1412 | let elapsed = items |
| 1413 | .iter() |
| 1414 | .map(|item| item.elapsed) |
| 1415 | .max() |
| 1416 | .unwrap_or_default(); |
| 1417 | if let Some(payload) = background_finished_payload(app.ui_locale, items, include_summary) { |
| 1418 | notifications::notify_done(method, in_tmux, &payload, threshold, elapsed); |
| 1419 | } |
| 1420 | } |
| 1421 | } |
| 1422 | |
| 1423 | /// Settle the background-finished batch when the parent turn ends (#6565). |
| 1424 | /// |
| 1425 | /// A completed turn sends its own notice, which covers the shells and tasks |
| 1426 | /// that finished while it ran, so those are dropped rather than announced a |
| 1427 | /// second time. Whatever else was held for the turn is then flushed. |
| 1428 | pub(crate) fn settle_background_finished_at_turn_end( |
| 1429 | app: &mut App, |
| 1430 | config: &Config, |
| 1431 | turn_completed: bool, |
| 1432 | ) { |
| 1433 | if turn_completed { |
| 1434 | crate::tui::background_finished::drop_reported_by_turn(&mut app.background_finished); |
| 1435 | } |
| 1436 | flush_background_finished(app, config, true); |
| 1437 | } |
| 1438 | |
| 1439 | // Keyboard-shortcut predicates moved to `tui/key_shortcuts.rs`. |
| 1440 | |
| 1441 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1442 | pub(crate) enum StartupVersionCheckSource { |
| 1443 | Disabled, |
| 1444 | ConfiguredUrl(String), |
| 1445 | ReleaseResolver, |
| 1446 | } |
| 1447 | |
| 1448 | /// A newer-stable-release notice, carrying enough context to render both the |
| 1449 | /// short transient toast and the durable in-transcript update prompt (#3961). |
| 1450 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1451 | pub(crate) struct UpdateNotice { |
| 1452 | current: String, |
| 1453 | latest: String, |
| 1454 | staged: Option<bool>, |
| 1455 | } |
| 1456 | |
| 1457 | impl UpdateNotice { |
| 1458 | /// Short line for the transient status toast, naming the command that |
| 1459 | /// actually updates *this* install. |
| 1460 | fn toast_line(&self, install: InstallMethod) -> String { |
| 1461 | let exe = std::env::current_exe().unwrap_or_default(); |
| 1462 | self.toast_line_for_exe(install, &exe) |
| 1463 | } |
| 1464 | |
| 1465 | fn toast_line_for_exe(&self, install: InstallMethod, exe: &std::path::Path) -> String { |
| 1466 | match self.staged { |
| 1467 | Some(true) => { |
| 1468 | return format!( |
| 1469 | "v{latest} is downloaded and verified; it starts the next time you open Codewhale", |
| 1470 | latest = self.latest |
| 1471 | ); |
| 1472 | } |
| 1473 | Some(false) => { |
| 1474 | return format!( |
| 1475 | "v{latest} is downloaded - run /update install to use it", |
| 1476 | latest = self.latest |
| 1477 | ); |
| 1478 | } |
| 1479 | None => {} |
| 1480 | } |
| 1481 | if install == InstallMethod::DesktopApp { |
| 1482 | return format!( |
| 1483 | "v{latest} available - use {command}", |
| 1484 | latest = self.latest, |
| 1485 | command = install.update_command() |
| 1486 | ); |
| 1487 | } |
| 1488 | if matches!(install, InstallMethod::ReadOnly | InstallMethod::System) { |
| 1489 | return format!( |
| 1490 | "v{latest} available - {answer}", |
| 1491 | latest = self.latest, |
| 1492 | answer = codewhale_release::installs::update_answer(install, exe) |
| 1493 | ); |
| 1494 | } |
| 1495 | let command = if install.supports_self_update() { |
| 1496 | install.update_command().to_string() |
| 1497 | } else { |
| 1498 | codewhale_release::installs::manager_update_command(install, exe) |
| 1499 | }; |
| 1500 | format!( |
| 1501 | "v{latest} available - run `{command}` and restart", |
| 1502 | latest = self.latest |
| 1503 | ) |
| 1504 | } |
| 1505 | |
| 1506 | /// Compact metrics-line label shown once the check has landed. Quiet by |
| 1507 | /// design: no action verb, no repetition — the toast and transcript |
| 1508 | /// notice carry the update instructions (#14). |
| 1509 | fn chip_label(&self) -> String { |
| 1510 | if self.staged == Some(true) { |
| 1511 | format!("↑ v{latest} ready", latest = self.latest) |
| 1512 | } else { |
| 1513 | format!("↑ v{latest}", latest = self.latest) |
| 1514 | } |
| 1515 | } |
| 1516 | |
| 1517 | /// Durable, actionable notice pushed into the transcript so it survives the |
| 1518 | /// toast TTL. Includes current/latest versions, release notes, the exact |
| 1519 | /// update command, and restart guidance. |
| 1520 | /// |
| 1521 | /// Package-managed installs get their manager's command instead of |
| 1522 | /// `codewhale update`, plus an explicit warning: self-updating a binary |
| 1523 | /// Homebrew or npm owns leaves the manager's metadata lying about what is |
| 1524 | /// on disk, and the next upgrade silently reverts the user. |
| 1525 | fn notice_block(&self, install: InstallMethod) -> String { |
| 1526 | let action = if self.staged == Some(true) { |
| 1527 | "It is downloaded and verified, and starts the next time you open Codewhale. Turn this off with `codewhale config set update.mode notify`." |
| 1528 | .to_string() |
| 1529 | } else if self.staged == Some(false) { |
| 1530 | "It is downloaded and its checksum verified. Releases are not signed yet, so it waits for your OK: run `/update install`, or say yes when Codewhale next starts." |
| 1531 | .to_string() |
| 1532 | } else if install == InstallMethod::DesktopApp { |
| 1533 | codewhale_release::install::DESKTOP_APP_UPDATE_HELP.to_string() |
| 1534 | } else if install.supports_self_update() { |
| 1535 | "Run `/update install` here (preview it with a bare `/update`), or `codewhale update` in a shell, then restart Codewhale." |
| 1536 | .to_string() |
| 1537 | } else { |
| 1538 | let exe = std::env::current_exe().unwrap_or_default(); |
| 1539 | format!( |
| 1540 | "{} Then restart Codewhale.", |
| 1541 | codewhale_release::installs::update_answer(install, &exe) |
| 1542 | ) |
| 1543 | }; |
| 1544 | let failure = codewhale_config::codewhale_home() |
| 1545 | .ok() |
| 1546 | .and_then(|home| codewhale_release::autoupdate::load_state(&home).last_failure) |
| 1547 | .map(|reason| { |
| 1548 | format!("\nThe last automatic update failed: {reason}. Details: codewhale doctor") |
| 1549 | }) |
| 1550 | .unwrap_or_default(); |
| 1551 | format!( |
| 1552 | "Update available: v{current} -> v{latest}\n\ |
| 1553 | Release notes: {notes}\n\ |
| 1554 | {action}{failure}", |
| 1555 | current = self.current, |
| 1556 | latest = self.latest, |
| 1557 | notes = codewhale_release::autoupdate::changelog_url(&self.latest), |
| 1558 | ) |
| 1559 | } |
| 1560 | } |
| 1561 | |
| 1562 | mod activity_detail; |
| 1563 | |
| 1564 | #[cfg(test)] |
| 1565 | mod provider_key_validation_tests { |
| 1566 | use super::*; |
| 1567 | use codewhale_engine::core::engine::mock_engine_handle; |
| 1568 | use ratatui::{buffer::Buffer, layout::Rect}; |
| 1569 | use tempfile::TempDir; |
| 1570 | |
| 1571 | struct ConfigPathEnvGuard { |
| 1572 | _tmp: TempDir, |
| 1573 | // Onboarding completion runs the setup transaction (setup_state.json, |
| 1574 | // settings.toml) against `CODEWHALE_HOME`; without this guard the |
| 1575 | // fixture provider landed in the developer's real ~/.codewhale (#5932). |
| 1576 | _codewhale_home: crate::test_support::EnvVarGuard, |
| 1577 | _codewhale_config_path: crate::test_support::EnvVarGuard, |
| 1578 | _deepseek_config_path: crate::test_support::EnvVarGuard, |
| 1579 | _lock: crate::test_support::TestEnvLock, |
| 1580 | } |
| 1581 | |
| 1582 | impl ConfigPathEnvGuard { |
| 1583 | fn new() -> Self { |
| 1584 | let lock = crate::test_support::lock_test_env(); |
| 1585 | let tmp = TempDir::new().expect("config tempdir"); |
| 1586 | let home = tmp.path().join(".codewhale"); |
| 1587 | let config_path = home.join("config.toml"); |
| 1588 | std::fs::create_dir_all(config_path.parent().expect("config parent")) |
| 1589 | .expect("config dir"); |
| 1590 | Self { |
| 1591 | _tmp: tmp, |
| 1592 | _codewhale_home: crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home), |
| 1593 | _codewhale_config_path: crate::test_support::EnvVarGuard::set( |
| 1594 | "CODEWHALE_CONFIG_PATH", |
| 1595 | &config_path, |
| 1596 | ), |
| 1597 | _deepseek_config_path: crate::test_support::EnvVarGuard::set( |
| 1598 | "DEEPSEEK_CONFIG_PATH", |
| 1599 | &config_path, |
| 1600 | ), |
| 1601 | _lock: lock, |
| 1602 | } |
| 1603 | } |
| 1604 | |
| 1605 | fn config_path(&self) -> PathBuf { |
| 1606 | std::env::var_os("CODEWHALE_CONFIG_PATH") |
| 1607 | .map(PathBuf::from) |
| 1608 | .expect("config path set") |
| 1609 | } |
| 1610 | } |
| 1611 | |
| 1612 | fn create_test_app() -> App { |
| 1613 | let options = TuiOptions { |
| 1614 | start_in_agent_mode: true, |
| 1615 | skip_onboarding: false, |
| 1616 | ..crate::tui::test_support::test_tui_options(PathBuf::from(".")) |
| 1617 | }; |
| 1618 | let mut app = App::new(options, &Config::default()); |
| 1619 | // These suites assert legacy strip geometry (work surface above the |
| 1620 | // transcript). The Bottom default (round 3, 2026-09-01) has its own |
| 1621 | // coverage in work_surface::rail_panels_render_in_all_placements. |
| 1622 | app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Top; |
| 1623 | app.api_provider = ProviderKind::Deepseek; |
| 1624 | app.model = "deepseek-v4-pro".to_string(); |
| 1625 | app.auto_model = false; |
| 1626 | app |
| 1627 | } |
| 1628 | |
| 1629 | #[test] |
| 1630 | fn api_key_live_mirror_revokes_stale_external_credential_consent() { |
| 1631 | let external_path = if cfg!(windows) { |
| 1632 | PathBuf::from(r"C:\Users\test\grok-auth.json") |
| 1633 | } else { |
| 1634 | PathBuf::from("/tmp/grok-auth.json") |
| 1635 | }; |
| 1636 | let mut config = { |
| 1637 | let __cw_config_init_0_0 = Some(ProvidersConfig { |
| 1638 | xai: ProviderConfig { |
| 1639 | auth_mode: Some("oauth".to_string()), |
| 1640 | external_credentials: Some( |
| 1641 | codewhale_config::ExternalCredentialConsentToml::read_only( |
| 1642 | codewhale_config::ProviderKind::Xai, |
| 1643 | codewhale_config::ExternalCredentialSource::GrokCli, |
| 1644 | external_path, |
| 1645 | ), |
| 1646 | ), |
| 1647 | ..Default::default() |
| 1648 | }, |
| 1649 | ..Default::default() |
| 1650 | }); |
| 1651 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 1652 | __cw_config_init_0_value.providers = __cw_config_init_0_0; |
| 1653 | __cw_config_init_0_value |
| 1654 | }; |
| 1655 | |
| 1656 | { |
| 1657 | let captured_fixture_identity = (config).test_identity_for_kind(ProviderKind::Xai); |
| 1658 | mirror_saved_api_key_in_config( |
| 1659 | &mut config, |
| 1660 | &captured_fixture_identity, |
| 1661 | "codewhale-owned-api-key".to_string(), |
| 1662 | ) |
| 1663 | .expect("admitted API-key fixture") |
| 1664 | }; |
| 1665 | |
| 1666 | let xai = config |
| 1667 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::Xai)) |
| 1668 | .expect("xAI live config"); |
| 1669 | assert_eq!(xai.auth_mode.as_deref(), Some("api_key")); |
| 1670 | assert_eq!(xai.api_key.as_deref(), Some("codewhale-owned-api-key")); |
| 1671 | assert!(xai.external_credentials.is_none()); |
| 1672 | } |
| 1673 | |
| 1674 | struct MockProviderKeyVerifier { |
| 1675 | result: Result<(), String>, |
| 1676 | roster: Option<codewhale_config::catalog::ProviderCatalogDelta>, |
| 1677 | calls: std::sync::Mutex<Vec<(ProviderKind, String, String)>>, |
| 1678 | } |
| 1679 | |
| 1680 | impl MockProviderKeyVerifier { |
| 1681 | fn new(result: Result<(), String>) -> Self { |
| 1682 | Self { |
| 1683 | result, |
| 1684 | roster: None, |
| 1685 | calls: std::sync::Mutex::new(Vec::new()), |
| 1686 | } |
| 1687 | } |
| 1688 | |
| 1689 | fn with_roster(mut self, roster: codewhale_config::catalog::ProviderCatalogDelta) -> Self { |
| 1690 | self.roster = Some(roster); |
| 1691 | self |
| 1692 | } |
| 1693 | |
| 1694 | fn calls(&self) -> Vec<(ProviderKind, String, String)> { |
| 1695 | self.calls.lock().expect("calls lock").clone() |
| 1696 | } |
| 1697 | } |
| 1698 | |
| 1699 | impl ProviderKeyVerifier for MockProviderKeyVerifier { |
| 1700 | fn verify<'a>( |
| 1701 | &'a self, |
| 1702 | provider: ProviderKind, |
| 1703 | api_key: &'a str, |
| 1704 | base_url: &'a str, |
| 1705 | ) -> ProviderKeyVerification<'a> { |
| 1706 | self.calls.lock().expect("calls lock").push(( |
| 1707 | provider, |
| 1708 | api_key.to_string(), |
| 1709 | base_url.to_string(), |
| 1710 | )); |
| 1711 | Box::pin(std::future::ready( |
| 1712 | self.result.clone().map(|()| self.roster.clone()), |
| 1713 | )) |
| 1714 | } |
| 1715 | } |
| 1716 | |
| 1717 | fn openrouter_config(base_url: &str) -> Config { |
| 1718 | { |
| 1719 | let __cw_config_init_1_0 = Some(ProvidersConfig { |
| 1720 | openrouter: ProviderConfig { |
| 1721 | base_url: Some(base_url.to_string()), |
| 1722 | ..ProviderConfig::default() |
| 1723 | }, |
| 1724 | ..ProvidersConfig::default() |
| 1725 | }); |
| 1726 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 1727 | __cw_config_init_1_value.providers = __cw_config_init_1_0; |
| 1728 | __cw_config_init_1_value |
| 1729 | } |
| 1730 | } |
| 1731 | |
| 1732 | fn two_named_custom_routes() -> Config { |
| 1733 | { |
| 1734 | let __cw_config_init_2_0 = Some("custom-a".to_string()); |
| 1735 | let __cw_config_init_2_1 = Some(ProvidersConfig { |
| 1736 | custom: std::collections::HashMap::from([ |
| 1737 | ( |
| 1738 | "custom-a".to_string(), |
| 1739 | ProviderConfig { |
| 1740 | kind: Some("openai-compatible".to_string()), |
| 1741 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 1742 | model: Some("model-a".to_string()), |
| 1743 | api_key: Some("key-a".to_string()), |
| 1744 | ..Default::default() |
| 1745 | }, |
| 1746 | ), |
| 1747 | ( |
| 1748 | "custom-b".to_string(), |
| 1749 | ProviderConfig { |
| 1750 | kind: Some("openai-compatible".to_string()), |
| 1751 | base_url: Some("http://127.0.0.1:18182/v1".to_string()), |
| 1752 | model: Some("model-b".to_string()), |
| 1753 | ..Default::default() |
| 1754 | }, |
| 1755 | ), |
| 1756 | ]), |
| 1757 | ..Default::default() |
| 1758 | }); |
| 1759 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 1760 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 1761 | __cw_config_init_2_value.providers = __cw_config_init_2_1; |
| 1762 | __cw_config_init_2_value |
| 1763 | } |
| 1764 | } |
| 1765 | |
| 1766 | #[test] |
| 1767 | fn provider_key_check_classifies_transport_failures_truthfully() { |
| 1768 | assert_eq!( |
| 1769 | provider_verification_error_category("connection refused"), |
| 1770 | codewhale_error_taxonomy::ErrorCategory::Network |
| 1771 | ); |
| 1772 | assert_eq!( |
| 1773 | provider_verification_error_category("request timed out"), |
| 1774 | codewhale_error_taxonomy::ErrorCategory::Timeout |
| 1775 | ); |
| 1776 | assert_eq!( |
| 1777 | provider_verification_error_category("HTTP 429 rate limit"), |
| 1778 | codewhale_error_taxonomy::ErrorCategory::RateLimit |
| 1779 | ); |
| 1780 | assert_eq!( |
| 1781 | provider_verification_error_category("HTTP 401 unauthorized"), |
| 1782 | codewhale_error_taxonomy::ErrorCategory::Authentication |
| 1783 | ); |
| 1784 | assert_eq!( |
| 1785 | provider_verification_error_category("HTTP 403 forbidden"), |
| 1786 | codewhale_error_taxonomy::ErrorCategory::Authorization |
| 1787 | ); |
| 1788 | assert_eq!( |
| 1789 | provider_verification_error_category("HTTP 500 upstream failure"), |
| 1790 | codewhale_error_taxonomy::ErrorCategory::Network |
| 1791 | ); |
| 1792 | } |
| 1793 | |
| 1794 | /// Release QA: a DeepSeek key probe returned two served ids, yet guided |
| 1795 | /// setup offered catalog rows the endpoint rejects at the first turn. The |
| 1796 | /// roster the probe already downloaded must become the route's model list. |
| 1797 | #[tokio::test] |
| 1798 | async fn provider_key_probe_roster_becomes_the_model_pick_roster() { |
| 1799 | use codewhale_config::catalog::{ |
| 1800 | CatalogOffering, CatalogSource, ProviderCatalogDelta, base_url_fingerprint, now_unix, |
| 1801 | }; |
| 1802 | struct Reset; |
| 1803 | impl Drop for Reset { |
| 1804 | fn drop(&mut self) { |
| 1805 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 1806 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 1807 | } |
| 1808 | } |
| 1809 | let _config_env = ConfigPathEnvGuard::new(); |
| 1810 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 1811 | let _reset = Reset; |
| 1812 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 1813 | let mut app = create_test_app(); |
| 1814 | let mut engine = mock_engine_handle(); |
| 1815 | let mut config = Config::default(); |
| 1816 | let identity = picker_provider_identity(&config, ProviderKind::Deepseek, None) |
| 1817 | .expect("DeepSeek identity"); |
| 1818 | let mut scoped = config.clone(); |
| 1819 | scoped |
| 1820 | .scope_to_provider_identity(&identity) |
| 1821 | .expect("scope DeepSeek"); |
| 1822 | let base_url = scoped.active_route_base_url(); |
| 1823 | let fingerprint = base_url_fingerprint(&base_url); |
| 1824 | let fetched_at = now_unix(); |
| 1825 | let served = ["deepseek-flash", "deepseek-v4-pro"]; |
| 1826 | // Scoped to the provider kind, exactly as the live probe returns it, |
| 1827 | // plus an id the catalog does not offer as a chat model. |
| 1828 | let roster = ProviderCatalogDelta { |
| 1829 | provider: "deepseek".into(), |
| 1830 | base_url_fingerprint: fingerprint.clone(), |
| 1831 | fetched_at, |
| 1832 | offerings: served |
| 1833 | .iter() |
| 1834 | .chain(&["deepseek-embedding-fixture"]) |
| 1835 | .map(|id| CatalogOffering { |
| 1836 | provider: "deepseek".into(), |
| 1837 | wire_model_id: (*id).into(), |
| 1838 | endpoint_key: "chat".into(), |
| 1839 | source: CatalogSource::Live { |
| 1840 | base_url_fingerprint: fingerprint.clone(), |
| 1841 | fetched_at, |
| 1842 | }, |
| 1843 | ..Default::default() |
| 1844 | }) |
| 1845 | .collect(), |
| 1846 | }; |
| 1847 | assert_ne!( |
| 1848 | codewhale_engine::provider_lake::catalog_models_for_route( |
| 1849 | ProviderKind::Deepseek, |
| 1850 | identity.key.as_str(), |
| 1851 | &base_url, |
| 1852 | ), |
| 1853 | served, |
| 1854 | "precondition: the catalog fallback lists more than the endpoint serves" |
| 1855 | ); |
| 1856 | let verifier = MockProviderKeyVerifier::new(Ok(())).with_roster(roster); |
| 1857 | |
| 1858 | apply_provider_picker_api_key_with_verifier( |
| 1859 | &mut app, |
| 1860 | &mut engine.handle, |
| 1861 | &mut config, |
| 1862 | identity.clone(), |
| 1863 | "sk-verified".to_string(), |
| 1864 | None, |
| 1865 | &verifier, |
| 1866 | ) |
| 1867 | .await; |
| 1868 | |
| 1869 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::ProviderPicker)); |
| 1870 | assert_eq!( |
| 1871 | codewhale_engine::provider_lake::catalog_models_for_route( |
| 1872 | ProviderKind::Deepseek, |
| 1873 | identity.key.as_str(), |
| 1874 | &base_url, |
| 1875 | ), |
| 1876 | served |
| 1877 | ); |
| 1878 | |
| 1879 | let identity = |
| 1880 | picker_provider_identity(&config, ProviderKind::Ollama, None).expect("Ollama identity"); |
| 1881 | let base_url = "http://127.0.0.1:11434/v1"; |
| 1882 | let fingerprint = base_url_fingerprint(base_url); |
| 1883 | let make_roster = |ids: &[&str], fingerprint: &str| ProviderCatalogDelta { |
| 1884 | provider: "ollama".into(), |
| 1885 | base_url_fingerprint: fingerprint.to_string(), |
| 1886 | fetched_at, |
| 1887 | offerings: ids |
| 1888 | .iter() |
| 1889 | .map(|id| CatalogOffering { |
| 1890 | provider: "ollama".into(), |
| 1891 | wire_model_id: (*id).into(), |
| 1892 | endpoint_key: "chat".into(), |
| 1893 | source: CatalogSource::Live { |
| 1894 | base_url_fingerprint: fingerprint.to_string(), |
| 1895 | fetched_at, |
| 1896 | }, |
| 1897 | ..Default::default() |
| 1898 | }) |
| 1899 | .collect(), |
| 1900 | }; |
| 1901 | let mut native = make_roster(&["qwen3:4b"], &fingerprint); |
| 1902 | native.offerings[0].default_for_provider = true; |
| 1903 | let ticket = codewhale_engine::provider_catalog_live::begin_refresh_for_identity( |
| 1904 | ProviderKind::Ollama, |
| 1905 | identity.key.as_str(), |
| 1906 | base_url, |
| 1907 | ); |
| 1908 | assert_eq!( |
| 1909 | codewhale_engine::provider_catalog_live::record_success_if_current(&ticket, native), |
| 1910 | Some(codewhale_config::catalog::CatalogStatus::Fresh) |
| 1911 | ); |
| 1912 | let generic = make_roster(&["qwen3:4b", "nomic-embed-text:latest"], &fingerprint); |
| 1913 | publish_verified_roster(&config, &identity, base_url, Some(generic)); |
| 1914 | let cached = codewhale_engine::provider_catalog_live::cached_entry_for_route( |
| 1915 | ProviderKind::Ollama, |
| 1916 | identity.key.as_str(), |
| 1917 | base_url, |
| 1918 | ) |
| 1919 | .unwrap() |
| 1920 | .expect("native Ollama roster remains available"); |
| 1921 | assert_eq!( |
| 1922 | cached |
| 1923 | .offerings |
| 1924 | .iter() |
| 1925 | .map(|row| row.wire_model_id.as_str()) |
| 1926 | .collect::<Vec<_>>(), |
| 1927 | ["qwen3:4b"] |
| 1928 | ); |
| 1929 | let empty_base_url = "http://127.0.0.1:11435/v1"; |
| 1930 | assert!( |
| 1931 | codewhale_engine::provider_catalog_live::cached_entry_for_route( |
| 1932 | ProviderKind::Ollama, |
| 1933 | identity.key.as_str(), |
| 1934 | empty_base_url, |
| 1935 | ) |
| 1936 | .unwrap() |
| 1937 | .is_none() |
| 1938 | ); |
| 1939 | let generic = make_roster( |
| 1940 | &["qwen3:4b", "nomic-embed-text:latest"], |
| 1941 | &base_url_fingerprint(empty_base_url), |
| 1942 | ); |
| 1943 | publish_verified_roster(&config, &identity, empty_base_url, Some(generic)); |
| 1944 | assert!( |
| 1945 | codewhale_engine::provider_catalog_live::cached_entry_for_route( |
| 1946 | ProviderKind::Ollama, |
| 1947 | identity.key.as_str(), |
| 1948 | empty_base_url, |
| 1949 | ) |
| 1950 | .unwrap() |
| 1951 | .is_none() |
| 1952 | ); |
| 1953 | } |
| 1954 | |
| 1955 | #[tokio::test] |
| 1956 | async fn provider_key_submit_opens_model_pick_without_persisting_on_validation_success() { |
| 1957 | let config_env = ConfigPathEnvGuard::new(); |
| 1958 | let mut app = create_test_app(); |
| 1959 | let mut engine = mock_engine_handle(); |
| 1960 | let mut config = openrouter_config("https://mock.openrouter.test/v1"); |
| 1961 | let verifier = MockProviderKeyVerifier::new(Ok(())); |
| 1962 | let identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 1963 | .expect("OpenRouter identity"); |
| 1964 | |
| 1965 | apply_provider_picker_api_key_with_verifier( |
| 1966 | &mut app, |
| 1967 | &mut engine.handle, |
| 1968 | &mut config, |
| 1969 | identity, |
| 1970 | "sk-verified".to_string(), |
| 1971 | None, |
| 1972 | &verifier, |
| 1973 | ) |
| 1974 | .await; |
| 1975 | |
| 1976 | assert_eq!( |
| 1977 | verifier.calls(), |
| 1978 | vec![( |
| 1979 | ProviderKind::Openrouter, |
| 1980 | "sk-verified".to_string(), |
| 1981 | "https://mock.openrouter.test/v1".to_string() |
| 1982 | )] |
| 1983 | ); |
| 1984 | // Validation success must not persist or switch yet (#3875 residual): |
| 1985 | // the guided flow continues at model pick first. |
| 1986 | assert_eq!(app.api_provider, ProviderKind::Deepseek); |
| 1987 | assert_eq!(config.provider.as_deref(), None); |
| 1988 | assert_eq!( |
| 1989 | config |
| 1990 | .providers |
| 1991 | .as_ref() |
| 1992 | .and_then(|providers| providers.openrouter.api_key.as_deref()), |
| 1993 | None |
| 1994 | ); |
| 1995 | let saved = std::fs::read_to_string(config_env.config_path()).unwrap_or_default(); |
| 1996 | assert!(!saved.contains("sk-verified")); |
| 1997 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::ProviderPicker)); |
| 1998 | assert!( |
| 1999 | app.setup_notice() |
| 2000 | .map(|notice| notice.text.as_str()) |
| 2001 | .is_some_and(|status| { status.contains("The provider accepted the key") }), |
| 2002 | "status names connection-probe success: {:?}", |
| 2003 | app.setup_notice() |
| 2004 | ); |
| 2005 | // The probe proves only this temporary credential generation, not the |
| 2006 | // original uncredentialed Config or any model's entitlement. |
| 2007 | let mut probed_config = config.clone(); |
| 2008 | let probed_identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 2009 | .expect("captured OpenRouter identity"); |
| 2010 | probed_config |
| 2011 | .scope_to_provider_identity(&probed_identity) |
| 2012 | .expect("scope probe"); |
| 2013 | probed_config |
| 2014 | .set_provider_api_key_override(&probed_identity, Some("sk-verified".to_string())) |
| 2015 | .expect("temporary probe key"); |
| 2016 | let verified_route = codewhale_engine::provider_readiness::route_identity_for_model( |
| 2017 | &probed_config, |
| 2018 | &probed_identity, |
| 2019 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_MODEL, |
| 2020 | ); |
| 2021 | assert_eq!( |
| 2022 | codewhale_engine::provider_readiness::resolve_with_identity( |
| 2023 | &verified_route, |
| 2024 | codewhale_engine::provider_readiness::CredentialState::Saved, |
| 2025 | true, |
| 2026 | &app.provider_health, |
| 2027 | ), |
| 2028 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::ConnectionCheckedModelUnchecked, |
| 2029 | "the live connection probe must not be reported as model ready", |
| 2030 | ); |
| 2031 | |
| 2032 | let picker = app.view_stack.pop().expect("provider picker reopened"); |
| 2033 | let area = Rect::new(0, 0, 90, 16); |
| 2034 | let mut buf = Buffer::empty(area); |
| 2035 | picker.render(area, &mut buf); |
| 2036 | let rendered = (0..area.height) |
| 2037 | .map(|y| { |
| 2038 | (0..area.width) |
| 2039 | .map(|x| buf[(x, y)].symbol()) |
| 2040 | .collect::<String>() |
| 2041 | }) |
| 2042 | .collect::<Vec<_>>() |
| 2043 | .join("\n"); |
| 2044 | assert!( |
| 2045 | rendered.contains("The provider accepted the key") |
| 2046 | && rendered.contains("pick the model to use by default"), |
| 2047 | "expected model-pick stage UI, got:\n{rendered}" |
| 2048 | ); |
| 2049 | } |
| 2050 | |
| 2051 | #[tokio::test] |
| 2052 | async fn test_connection_records_models_probe_not_ready() { |
| 2053 | let config_env = ConfigPathEnvGuard::new(); |
| 2054 | let mut app = create_test_app(); |
| 2055 | let mut engine = mock_engine_handle(); |
| 2056 | let mut config = openrouter_config("https://mock.openrouter.test/v1"); |
| 2057 | config.provider = Some("openrouter".to_string()); |
| 2058 | if let Some(providers) = config.providers.as_mut() { |
| 2059 | providers.openrouter.api_key = Some("sk-saved".to_string()); |
| 2060 | } |
| 2061 | let verifier = MockProviderKeyVerifier::new(Ok(())); |
| 2062 | let identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 2063 | .expect("OpenRouter identity"); |
| 2064 | |
| 2065 | apply_provider_picker_test_connection_with_verifier( |
| 2066 | &mut app, |
| 2067 | &mut engine.handle, |
| 2068 | &mut config, |
| 2069 | identity, |
| 2070 | false, |
| 2071 | &verifier, |
| 2072 | ) |
| 2073 | .await; |
| 2074 | |
| 2075 | assert_eq!( |
| 2076 | verifier.calls(), |
| 2077 | vec![( |
| 2078 | ProviderKind::Openrouter, |
| 2079 | "sk-saved".to_string(), |
| 2080 | "https://mock.openrouter.test/v1".to_string() |
| 2081 | )] |
| 2082 | ); |
| 2083 | let _ = config_env; |
| 2084 | assert_eq!(config.provider.as_deref(), Some("openrouter")); |
| 2085 | assert!( |
| 2086 | app.status_toasts.iter().any(|toast| { |
| 2087 | toast.text.contains("The provider accepted the key") |
| 2088 | && !toast.text.contains("pick the model") |
| 2089 | }), |
| 2090 | "test connection names reachability only: {:?}", |
| 2091 | app.status_toasts |
| 2092 | ); |
| 2093 | let verified_route = codewhale_engine::provider_readiness::route_identity_for_model( |
| 2094 | &config, |
| 2095 | &(config).test_identity_for_kind(ProviderKind::Openrouter), |
| 2096 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_MODEL, |
| 2097 | ); |
| 2098 | assert_eq!( |
| 2099 | codewhale_engine::provider_readiness::resolve_with_identity( |
| 2100 | &verified_route, |
| 2101 | codewhale_engine::provider_readiness::CredentialState::Saved, |
| 2102 | true, |
| 2103 | &app.provider_health, |
| 2104 | ), |
| 2105 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::ConnectionCheckedModelUnchecked, |
| 2106 | ); |
| 2107 | assert_ne!( |
| 2108 | codewhale_engine::provider_readiness::resolve_with_identity( |
| 2109 | &verified_route, |
| 2110 | codewhale_engine::provider_readiness::CredentialState::Saved, |
| 2111 | true, |
| 2112 | &app.provider_health, |
| 2113 | ), |
| 2114 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::Ready, |
| 2115 | ); |
| 2116 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::ProviderPicker)); |
| 2117 | } |
| 2118 | |
| 2119 | #[tokio::test] |
| 2120 | async fn test_connection_without_key_does_not_mark_ready() { |
| 2121 | let config_env = ConfigPathEnvGuard::new(); |
| 2122 | let mut app = create_test_app(); |
| 2123 | let mut engine = mock_engine_handle(); |
| 2124 | let mut config = openrouter_config("https://mock.openrouter.test/v1"); |
| 2125 | let verifier = MockProviderKeyVerifier::new(Ok(())); |
| 2126 | let identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 2127 | .expect("OpenRouter identity"); |
| 2128 | |
| 2129 | apply_provider_picker_test_connection_with_verifier( |
| 2130 | &mut app, |
| 2131 | &mut engine.handle, |
| 2132 | &mut config, |
| 2133 | identity, |
| 2134 | false, |
| 2135 | &verifier, |
| 2136 | ) |
| 2137 | .await; |
| 2138 | |
| 2139 | assert!(verifier.calls().is_empty()); |
| 2140 | let _ = config_env; |
| 2141 | assert!( |
| 2142 | app.status_toasts |
| 2143 | .iter() |
| 2144 | .any(|toast| toast.text.contains("No API key saved")), |
| 2145 | "{:?}", |
| 2146 | app.status_toasts |
| 2147 | ); |
| 2148 | let verified_route = codewhale_engine::provider_readiness::route_identity_for_model( |
| 2149 | &config, |
| 2150 | &(config).test_identity_for_kind(ProviderKind::Openrouter), |
| 2151 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_MODEL, |
| 2152 | ); |
| 2153 | assert_eq!( |
| 2154 | codewhale_engine::provider_readiness::resolve_with_identity( |
| 2155 | &verified_route, |
| 2156 | codewhale_engine::provider_readiness::CredentialState::MissingKey, |
| 2157 | true, |
| 2158 | &app.provider_health, |
| 2159 | ), |
| 2160 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::MissingKey, |
| 2161 | ); |
| 2162 | } |
| 2163 | |
| 2164 | #[tokio::test] |
| 2165 | async fn test_connection_failure_redacts_the_api_key() { |
| 2166 | let config_env = ConfigPathEnvGuard::new(); |
| 2167 | let mut app = create_test_app(); |
| 2168 | let mut engine = mock_engine_handle(); |
| 2169 | let mut config = openrouter_config("https://mock.openrouter.test/v1"); |
| 2170 | config.provider = Some("openrouter".to_string()); |
| 2171 | if let Some(providers) = config.providers.as_mut() { |
| 2172 | providers.openrouter.api_key = Some("sk-saved".to_string()); |
| 2173 | } |
| 2174 | let verifier = MockProviderKeyVerifier::new(Err( |
| 2175 | "HTTP 401: upstream echoed sk-saved in a long diagnostic body that must not stay visible" |
| 2176 | .repeat(4), |
| 2177 | )); |
| 2178 | let identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 2179 | .expect("OpenRouter identity"); |
| 2180 | |
| 2181 | apply_provider_picker_test_connection_with_verifier( |
| 2182 | &mut app, |
| 2183 | &mut engine.handle, |
| 2184 | &mut config, |
| 2185 | identity, |
| 2186 | true, |
| 2187 | &verifier, |
| 2188 | ) |
| 2189 | .await; |
| 2190 | |
| 2191 | let _ = config_env; |
| 2192 | let status = app |
| 2193 | .status_toasts |
| 2194 | .iter() |
| 2195 | .map(|toast| toast.text.as_str()) |
| 2196 | .collect::<Vec<_>>() |
| 2197 | .join("\n"); |
| 2198 | assert!( |
| 2199 | !status.contains("sk-saved"), |
| 2200 | "probe toast leaked the API key: {status}" |
| 2201 | ); |
| 2202 | assert!(status.contains("***"), "{status}"); |
| 2203 | assert!( |
| 2204 | app.provider_picker_memory |
| 2205 | .as_ref() |
| 2206 | .is_some_and(|memory| memory.catalog_view), |
| 2207 | "catalog browsing context must survive the probe" |
| 2208 | ); |
| 2209 | let verified_route = codewhale_engine::provider_readiness::route_identity_for_model( |
| 2210 | &config, |
| 2211 | &(config).test_identity_for_kind(ProviderKind::Openrouter), |
| 2212 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_MODEL, |
| 2213 | ); |
| 2214 | assert!(matches!( |
| 2215 | codewhale_engine::provider_readiness::resolve_with_identity( |
| 2216 | &verified_route, |
| 2217 | codewhale_engine::provider_readiness::CredentialState::Saved, |
| 2218 | true, |
| 2219 | &app.provider_health, |
| 2220 | ), |
| 2221 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed { .. } |
| 2222 | )); |
| 2223 | } |
| 2224 | |
| 2225 | /// #4526: the wizard's StepFun billing-route choice must be the endpoint |
| 2226 | /// the key is probed against, and it must reach disk only once the user |
| 2227 | /// confirms — never as a side effect of validation. |
| 2228 | #[tokio::test] |
| 2229 | async fn stepfun_plan_route_is_validated_before_the_key_is_persisted() { |
| 2230 | let config_env = ConfigPathEnvGuard::new(); |
| 2231 | let mut app = create_test_app(); |
| 2232 | let mut engine = mock_engine_handle(); |
| 2233 | let mut config = Config::default(); |
| 2234 | let verifier = MockProviderKeyVerifier::new(Ok(())); |
| 2235 | let identity = picker_provider_identity(&config, ProviderKind::Stepfun, None) |
| 2236 | .expect("StepFun identity"); |
| 2237 | |
| 2238 | apply_provider_picker_api_key_with_verifier( |
| 2239 | &mut app, |
| 2240 | &mut engine.handle, |
| 2241 | &mut config, |
| 2242 | identity, |
| 2243 | "step-plan-key".to_string(), |
| 2244 | Some( |
| 2245 | codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_PLAN_BASE_URL.to_string(), |
| 2246 | ), |
| 2247 | &verifier, |
| 2248 | ) |
| 2249 | .await; |
| 2250 | |
| 2251 | assert_eq!( |
| 2252 | verifier.calls(), |
| 2253 | vec![( |
| 2254 | ProviderKind::Stepfun, |
| 2255 | "step-plan-key".to_string(), |
| 2256 | codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_PLAN_BASE_URL.to_string() |
| 2257 | )], |
| 2258 | "the chosen Step Plan endpoint must be the one live-validated" |
| 2259 | ); |
| 2260 | assert_eq!( |
| 2261 | config |
| 2262 | .providers |
| 2263 | .as_ref() |
| 2264 | .and_then(|providers| providers.stepfun.base_url.clone()), |
| 2265 | None, |
| 2266 | "validation must not mutate the live config" |
| 2267 | ); |
| 2268 | let saved = std::fs::read_to_string(config_env.config_path()).unwrap_or_default(); |
| 2269 | assert!( |
| 2270 | !saved.contains("step_plan"), |
| 2271 | "nothing persisted yet: {saved}" |
| 2272 | ); |
| 2273 | assert!(!saved.contains("step-plan-key"), "no secret yet: {saved}"); |
| 2274 | } |
| 2275 | |
| 2276 | /// The confirm stage writes the endpoint into `[providers.stepfun]` and |
| 2277 | /// leaves every other provider table alone. |
| 2278 | #[tokio::test] |
| 2279 | async fn stepfun_setup_confirm_writes_only_the_stepfun_base_url() { |
| 2280 | let config_env = ConfigPathEnvGuard::new(); |
| 2281 | let mut app = create_test_app(); |
| 2282 | let mut engine = mock_engine_handle(); |
| 2283 | let mut config = Config::default(); |
| 2284 | let identity = picker_provider_identity(&config, ProviderKind::Stepfun, None) |
| 2285 | .expect("StepFun identity"); |
| 2286 | |
| 2287 | apply_provider_picker_setup_confirmed( |
| 2288 | &mut app, |
| 2289 | &mut engine.handle, |
| 2290 | &mut config, |
| 2291 | identity, |
| 2292 | "step-plan-key".to_string(), |
| 2293 | codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_MODEL.to_string(), |
| 2294 | None, |
| 2295 | Some( |
| 2296 | codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_PLAN_BASE_URL.to_string(), |
| 2297 | ), |
| 2298 | ) |
| 2299 | .await; |
| 2300 | |
| 2301 | let saved = std::fs::read_to_string(config_env.config_path()).expect("config written"); |
| 2302 | let document: toml::Table = toml::from_str(&saved).expect("valid TOML"); |
| 2303 | let providers = document |
| 2304 | .get("providers") |
| 2305 | .and_then(toml::Value::as_table) |
| 2306 | .expect("providers table"); |
| 2307 | assert_eq!( |
| 2308 | providers |
| 2309 | .get("stepfun") |
| 2310 | .and_then(|entry| entry.get("base_url")) |
| 2311 | .and_then(toml::Value::as_str), |
| 2312 | Some(codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_PLAN_BASE_URL) |
| 2313 | ); |
| 2314 | assert_eq!( |
| 2315 | providers.keys().collect::<Vec<_>>(), |
| 2316 | vec!["stepfun"], |
| 2317 | "the route choice must not touch other provider tables" |
| 2318 | ); |
| 2319 | assert!( |
| 2320 | document.get("base_url").is_none(), |
| 2321 | "the root base_url must stay untouched: {saved}" |
| 2322 | ); |
| 2323 | assert_eq!( |
| 2324 | config |
| 2325 | .providers |
| 2326 | .as_ref() |
| 2327 | .and_then(|providers| providers.stepfun.base_url.as_deref()), |
| 2328 | Some(codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_PLAN_BASE_URL), |
| 2329 | "the live config mirrors the persisted endpoint" |
| 2330 | ); |
| 2331 | } |
| 2332 | |
| 2333 | #[tokio::test] |
| 2334 | async fn replacing_legacy_kimi_import_verifies_and_persists_the_kimi_code_api_key_route() { |
| 2335 | let config_env = ConfigPathEnvGuard::new(); |
| 2336 | std::fs::write( |
| 2337 | config_env.config_path(), |
| 2338 | r#"# preserve-kimi-comment |
| 2339 | [providers.moonshot] |
| 2340 | auth_mode = "kimi_oauth" |
| 2341 | "#, |
| 2342 | ) |
| 2343 | .expect("seed legacy Kimi import config"); |
| 2344 | let mut app = create_test_app(); |
| 2345 | let mut engine = mock_engine_handle(); |
| 2346 | let mut config = { |
| 2347 | let __cw_config_init_3_0 = Some(ProvidersConfig { |
| 2348 | moonshot: ProviderConfig { |
| 2349 | auth_mode: Some("kimi_oauth".to_string()), |
| 2350 | ..ProviderConfig::default() |
| 2351 | }, |
| 2352 | ..ProvidersConfig::default() |
| 2353 | }); |
| 2354 | let mut __cw_config_init_3_value: Config = Config::default(); |
| 2355 | __cw_config_init_3_value.providers = __cw_config_init_3_0; |
| 2356 | __cw_config_init_3_value |
| 2357 | }; |
| 2358 | let identity = picker_provider_identity(&config, ProviderKind::Moonshot, None) |
| 2359 | .expect("Moonshot identity"); |
| 2360 | let verifier = MockProviderKeyVerifier::new(Ok(())); |
| 2361 | |
| 2362 | apply_provider_picker_api_key_with_verifier( |
| 2363 | &mut app, |
| 2364 | &mut engine.handle, |
| 2365 | &mut config, |
| 2366 | identity.clone(), |
| 2367 | "sk-kimi-supported".to_string(), |
| 2368 | None, |
| 2369 | &verifier, |
| 2370 | ) |
| 2371 | .await; |
| 2372 | |
| 2373 | assert_eq!( |
| 2374 | verifier.calls(), |
| 2375 | vec![( |
| 2376 | ProviderKind::Moonshot, |
| 2377 | "sk-kimi-supported".to_string(), |
| 2378 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL.to_string(), |
| 2379 | )], |
| 2380 | "replacement keys must be verified against Kimi Code, not the ordinary Moonshot API" |
| 2381 | ); |
| 2382 | |
| 2383 | apply_provider_picker_setup_confirmed( |
| 2384 | &mut app, |
| 2385 | &mut engine.handle, |
| 2386 | &mut config, |
| 2387 | identity, |
| 2388 | "sk-kimi-supported".to_string(), |
| 2389 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_MODEL.to_string(), |
| 2390 | None, |
| 2391 | None, |
| 2392 | ) |
| 2393 | .await; |
| 2394 | |
| 2395 | let moonshot = config |
| 2396 | .providers |
| 2397 | .as_ref() |
| 2398 | .map(|providers| &providers.moonshot) |
| 2399 | .expect("in-memory Moonshot config"); |
| 2400 | assert_eq!(moonshot.auth_mode.as_deref(), Some("api_key")); |
| 2401 | assert_eq!( |
| 2402 | moonshot.base_url.as_deref(), |
| 2403 | Some(codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL) |
| 2404 | ); |
| 2405 | assert_eq!(moonshot.api_key.as_deref(), Some("sk-kimi-supported")); |
| 2406 | |
| 2407 | let saved = std::fs::read_to_string(config_env.config_path()).expect("saved config"); |
| 2408 | assert!(saved.contains("# preserve-kimi-comment")); |
| 2409 | assert!(saved.contains("auth_mode = \"api_key\"")); |
| 2410 | assert!(saved.contains(&format!( |
| 2411 | "base_url = \"{}\"", |
| 2412 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL |
| 2413 | ))); |
| 2414 | } |
| 2415 | |
| 2416 | #[tokio::test] |
| 2417 | async fn provider_setup_confirm_persists_provider_model_and_preserves_comments() { |
| 2418 | let config_env = ConfigPathEnvGuard::new(); |
| 2419 | // Seed a commented config so the confirm path must preserve it. |
| 2420 | std::fs::write( |
| 2421 | config_env.config_path(), |
| 2422 | r#"# keep-me-comment |
| 2423 | [providers.openrouter] |
| 2424 | # openrouter-table-comment |
| 2425 | base_url = "https://mock.openrouter.test/v1" |
| 2426 | |
| 2427 | [providers.anthropic] |
| 2428 | api_key = "fixture-other-provider-key" |
| 2429 | "#, |
| 2430 | ) |
| 2431 | .expect("seed config"); |
| 2432 | |
| 2433 | let mut app = create_test_app(); |
| 2434 | let mut engine = mock_engine_handle(); |
| 2435 | let mut config = openrouter_config("https://mock.openrouter.test/v1"); |
| 2436 | config |
| 2437 | .providers |
| 2438 | .get_or_insert_with(ProvidersConfig::default) |
| 2439 | .anthropic |
| 2440 | .api_key = Some("fixture-other-provider-key".to_string()); |
| 2441 | let model = "deepseek/deepseek-v4-pro".to_string(); |
| 2442 | let identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 2443 | .expect("OpenRouter identity"); |
| 2444 | |
| 2445 | apply_provider_picker_setup_confirmed( |
| 2446 | &mut app, |
| 2447 | &mut engine.handle, |
| 2448 | &mut config, |
| 2449 | identity, |
| 2450 | "sk-confirmed".to_string(), |
| 2451 | model.clone(), |
| 2452 | None, |
| 2453 | None, |
| 2454 | ) |
| 2455 | .await; |
| 2456 | |
| 2457 | assert_eq!(app.api_provider, ProviderKind::Openrouter); |
| 2458 | assert_eq!(config.provider.as_deref(), Some("openrouter")); |
| 2459 | assert_eq!( |
| 2460 | config |
| 2461 | .providers |
| 2462 | .as_ref() |
| 2463 | .and_then(|providers| providers.openrouter.api_key.as_deref()), |
| 2464 | Some("sk-confirmed") |
| 2465 | ); |
| 2466 | assert_eq!( |
| 2467 | config |
| 2468 | .providers |
| 2469 | .as_ref() |
| 2470 | .and_then(|providers| providers.openrouter.model.as_deref()), |
| 2471 | Some(model.as_str()) |
| 2472 | ); |
| 2473 | let saved = std::fs::read_to_string(config_env.config_path()).expect("saved config"); |
| 2474 | assert!( |
| 2475 | saved.contains("# keep-me-comment"), |
| 2476 | "root comment lost:\n{saved}" |
| 2477 | ); |
| 2478 | assert!( |
| 2479 | saved.contains("# openrouter-table-comment"), |
| 2480 | "table comment lost:\n{saved}" |
| 2481 | ); |
| 2482 | assert!(saved.contains("[providers.openrouter]")); |
| 2483 | assert!(saved.contains("api_key = \"sk-confirmed\"")); |
| 2484 | assert!(saved.contains(&format!("model = \"{model}\""))); |
| 2485 | assert!(saved.contains("[providers.anthropic]")); |
| 2486 | assert!(saved.contains("api_key = \"fixture-other-provider-key\"")); |
| 2487 | assert_eq!( |
| 2488 | config |
| 2489 | .providers |
| 2490 | .as_ref() |
| 2491 | .and_then(|providers| providers.anthropic.api_key.as_deref()), |
| 2492 | Some("fixture-other-provider-key"), |
| 2493 | "saving OpenRouter must not overwrite a different provider slot" |
| 2494 | ); |
| 2495 | } |
| 2496 | |
| 2497 | #[tokio::test] |
| 2498 | async fn provider_key_submit_reopens_picker_without_persisting_on_validation_failure() { |
| 2499 | let config_env = ConfigPathEnvGuard::new(); |
| 2500 | let mut app = create_test_app(); |
| 2501 | let mut engine = mock_engine_handle(); |
| 2502 | let mut config = openrouter_config("https://mock.openrouter.test/v1"); |
| 2503 | let verifier = MockProviderKeyVerifier::new(Err("HTTP 401: unauthorized".to_string())); |
| 2504 | let identity = picker_provider_identity(&config, ProviderKind::Openrouter, None) |
| 2505 | .expect("OpenRouter identity"); |
| 2506 | |
| 2507 | apply_provider_picker_api_key_with_verifier( |
| 2508 | &mut app, |
| 2509 | &mut engine.handle, |
| 2510 | &mut config, |
| 2511 | identity, |
| 2512 | "sk-rejected".to_string(), |
| 2513 | None, |
| 2514 | &verifier, |
| 2515 | ) |
| 2516 | .await; |
| 2517 | |
| 2518 | assert_eq!(app.api_provider, ProviderKind::Deepseek); |
| 2519 | assert_eq!(config.provider.as_deref(), None); |
| 2520 | assert_eq!( |
| 2521 | config |
| 2522 | .providers |
| 2523 | .as_ref() |
| 2524 | .and_then(|providers| providers.openrouter.api_key.as_deref()), |
| 2525 | None |
| 2526 | ); |
| 2527 | let saved = std::fs::read_to_string(config_env.config_path()).unwrap_or_default(); |
| 2528 | assert!(!saved.contains("sk-rejected")); |
| 2529 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::ProviderPicker)); |
| 2530 | assert!( |
| 2531 | app.setup_notice() |
| 2532 | .map(|notice| notice.text.as_str()) |
| 2533 | .is_some_and(|status| status.contains("The provider did not accept this key")), |
| 2534 | "status names validation failure: {:?}", |
| 2535 | app.setup_notice() |
| 2536 | ); |
| 2537 | |
| 2538 | let picker = app.view_stack.pop().expect("provider picker reopened"); |
| 2539 | let area = Rect::new(0, 0, 90, 14); |
| 2540 | let mut buf = Buffer::empty(area); |
| 2541 | picker.render(area, &mut buf); |
| 2542 | let rendered = (0..area.height) |
| 2543 | .map(|y| { |
| 2544 | (0..area.width) |
| 2545 | .map(|x| buf[(x, y)].symbol()) |
| 2546 | .collect::<String>() |
| 2547 | }) |
| 2548 | .collect::<Vec<_>>() |
| 2549 | .join("\n"); |
| 2550 | // #6566: a plain sentence with the next step, not the raw reply. |
| 2551 | assert!( |
| 2552 | rendered.contains("The provider did not accept this key"), |
| 2553 | "{rendered}" |
| 2554 | ); |
| 2555 | assert!(!rendered.contains("HTTP 401"), "{rendered}"); |
| 2556 | } |
| 2557 | |
| 2558 | #[tokio::test] |
| 2559 | async fn named_custom_verification_failure_and_dismiss_keep_committed_a_route() { |
| 2560 | let _config_env = ConfigPathEnvGuard::new(); |
| 2561 | let mut app = create_test_app(); |
| 2562 | app.set_provider_identity(ProviderKind::Custom, "custom-a"); |
| 2563 | app.set_model_selection("model-a".to_string()); |
| 2564 | let mut engine = mock_engine_handle(); |
| 2565 | let mut config = two_named_custom_routes(); |
| 2566 | let identity = picker_provider_identity(&config, ProviderKind::Custom, Some("custom-b")) |
| 2567 | .expect("custom B identity"); |
| 2568 | let verifier = MockProviderKeyVerifier::new(Err("HTTP 401: unauthorized".to_string())); |
| 2569 | |
| 2570 | apply_provider_picker_api_key_with_verifier( |
| 2571 | &mut app, |
| 2572 | &mut engine.handle, |
| 2573 | &mut config, |
| 2574 | identity, |
| 2575 | "rejected-b-key".to_string(), |
| 2576 | None, |
| 2577 | &verifier, |
| 2578 | ) |
| 2579 | .await; |
| 2580 | |
| 2581 | assert_eq!(config.provider.as_deref(), Some("custom-a")); |
| 2582 | assert_eq!(app.provider_identity_for_persistence(), "custom-a"); |
| 2583 | app.view_stack.pop().expect("failed verifier picker"); |
| 2584 | sync_config_provider_from_app(&mut config, &app); |
| 2585 | let route = validated_app_runtime_route(&app, &config).expect("committed A route"); |
| 2586 | assert_eq!(route.identity.key.as_str(), "custom-a"); |
| 2587 | assert_eq!(route.client.base_url(), "http://127.0.0.1:18181/v1"); |
| 2588 | } |
| 2589 | |
| 2590 | #[tokio::test] |
| 2591 | async fn named_custom_setup_persists_exact_provider_table_and_model() { |
| 2592 | let config_env = ConfigPathEnvGuard::new(); |
| 2593 | std::fs::write( |
| 2594 | config_env.config_path(), |
| 2595 | r#"provider = "custom-a" |
| 2596 | |
| 2597 | [providers.custom-a] |
| 2598 | kind = "openai-compatible" |
| 2599 | base_url = "http://127.0.0.1:18181/v1" |
| 2600 | model = "model-a" |
| 2601 | |
| 2602 | [providers.custom-b] |
| 2603 | kind = "openai-compatible" |
| 2604 | base_url = "http://127.0.0.1:18182/v1" |
| 2605 | model = "model-b" |
| 2606 | "#, |
| 2607 | ) |
| 2608 | .expect("seed named custom config"); |
| 2609 | let mut app = create_test_app(); |
| 2610 | app.set_provider_identity(ProviderKind::Custom, "custom-a"); |
| 2611 | app.set_model_selection("model-a".to_string()); |
| 2612 | let mut engine = mock_engine_handle(); |
| 2613 | let mut config = two_named_custom_routes(); |
| 2614 | let identity = picker_provider_identity(&config, ProviderKind::Custom, Some("custom-b")) |
| 2615 | .expect("custom B identity"); |
| 2616 | |
| 2617 | apply_provider_picker_setup_confirmed( |
| 2618 | &mut app, |
| 2619 | &mut engine.handle, |
| 2620 | &mut config, |
| 2621 | identity, |
| 2622 | "saved-b-key".to_string(), |
| 2623 | "model-b-confirmed".to_string(), |
| 2624 | None, |
| 2625 | None, |
| 2626 | ) |
| 2627 | .await; |
| 2628 | |
| 2629 | assert_eq!(app.provider_identity_for_persistence(), "custom-b"); |
| 2630 | assert_eq!(config.provider.as_deref(), Some("custom-b")); |
| 2631 | let saved = std::fs::read_to_string(config_env.config_path()).expect("saved config"); |
| 2632 | assert!(saved.contains("[providers.custom-b]")); |
| 2633 | assert!(saved.contains("api_key = \"saved-b-key\"")); |
| 2634 | assert!(saved.contains("model = \"model-b-confirmed\"")); |
| 2635 | assert!(!saved.contains("[providers.custom]\n")); |
| 2636 | } |
| 2637 | |
| 2638 | #[test] |
| 2639 | fn legacy_literal_custom_identity_persistence_moves_into_the_custom_table() { |
| 2640 | let config_env = ConfigPathEnvGuard::new(); |
| 2641 | std::fs::write( |
| 2642 | config_env.config_path(), |
| 2643 | r#"provider = "custom" |
| 2644 | base_url = "http://127.0.0.1:18180/v1" |
| 2645 | default_text_model = "legacy-model" |
| 2646 | "#, |
| 2647 | ) |
| 2648 | .expect("seed legacy root route"); |
| 2649 | let config = { |
| 2650 | let __cw_config_init_4_0 = Some("custom".to_string()); |
| 2651 | let __cw_config_init_4_1 = Some("legacy-model".to_string()); |
| 2652 | let mut __cw_config_init_4_value: Config = Default::default(); |
| 2653 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 2654 | __cw_config_init_4_value.default_text_model = __cw_config_init_4_1; |
| 2655 | __cw_config_init_4_value |
| 2656 | } |
| 2657 | .with_legacy_root(None, Some("http://127.0.0.1:18180/v1".to_string())); |
| 2658 | let identity = config |
| 2659 | .resolve_provider_identity("custom") |
| 2660 | .expect("legacy identity"); |
| 2661 | |
| 2662 | codewhale_runtime::config::save_api_key_for_identity( |
| 2663 | &identity, |
| 2664 | &config, |
| 2665 | "legacy-saved-key", |
| 2666 | ) |
| 2667 | .expect("save legacy key"); |
| 2668 | codewhale_runtime::config::save_provider_model_for_identity( |
| 2669 | &identity, |
| 2670 | &config, |
| 2671 | "legacy-model-updated", |
| 2672 | ) |
| 2673 | .expect("save legacy model"); |
| 2674 | |
| 2675 | // The literal custom route's top-level fields now live in |
| 2676 | // `[providers.custom]` (#6394); the saves write there and the write |
| 2677 | // moves the old top-level endpoint alongside. |
| 2678 | let saved = std::fs::read_to_string(config_env.config_path()).expect("saved config"); |
| 2679 | let table: toml::Table = toml::from_str(&saved).expect("saved config parses"); |
| 2680 | assert!( |
| 2681 | !codewhale_config::legacy_root::has_legacy_root_keys(&table), |
| 2682 | "{saved}" |
| 2683 | ); |
| 2684 | let custom = table["providers"]["custom"] |
| 2685 | .as_table() |
| 2686 | .expect("custom table"); |
| 2687 | assert_eq!(custom["api_key"].as_str(), Some("legacy-saved-key")); |
| 2688 | assert_eq!(custom["model"].as_str(), Some("legacy-model-updated")); |
| 2689 | assert_eq!( |
| 2690 | custom["base_url"].as_str(), |
| 2691 | Some("http://127.0.0.1:18180/v1") |
| 2692 | ); |
| 2693 | let reloaded = |
| 2694 | codewhale_plugins::providers::load_config(Some(config_env.config_path()), None) |
| 2695 | .expect("reload legacy"); |
| 2696 | assert!(reloaded.selects_literal_custom_provider()); |
| 2697 | assert_eq!( |
| 2698 | reloaded |
| 2699 | .resolve_provider_identity("custom") |
| 2700 | .expect("repeat legacy identity"), |
| 2701 | identity |
| 2702 | ); |
| 2703 | let route = resolve_runtime_route( |
| 2704 | &reloaded, |
| 2705 | ProviderKind::Custom, |
| 2706 | Some("legacy-model-updated"), |
| 2707 | ) |
| 2708 | .expect("resolve reloaded legacy") |
| 2709 | .validate() |
| 2710 | .expect("preflight reloaded legacy"); |
| 2711 | assert_eq!(route.client.base_url(), "http://127.0.0.1:18180/v1"); |
| 2712 | } |
| 2713 | |
| 2714 | #[test] |
| 2715 | fn legacy_active_route_does_not_redirect_named_custom_persistence_to_root() { |
| 2716 | let config_env = ConfigPathEnvGuard::new(); |
| 2717 | std::fs::write( |
| 2718 | config_env.config_path(), |
| 2719 | r#"provider = "custom" |
| 2720 | api_key = "legacy-root-key" |
| 2721 | base_url = "http://127.0.0.1:18180/v1" |
| 2722 | default_text_model = "legacy-model" |
| 2723 | |
| 2724 | [providers.custom-b] |
| 2725 | kind = "openai-compatible" |
| 2726 | base_url = "http://127.0.0.1:18182/v1" |
| 2727 | model = "model-b" |
| 2728 | "#, |
| 2729 | ) |
| 2730 | .expect("seed coexistence config"); |
| 2731 | let config = |
| 2732 | codewhale_plugins::providers::load_config(Some(config_env.config_path()), None) |
| 2733 | .expect("load config"); |
| 2734 | assert!(config.selects_literal_custom_provider()); |
| 2735 | let identity = config |
| 2736 | .resolve_provider_identity("custom-b") |
| 2737 | .expect("named custom identity"); |
| 2738 | |
| 2739 | codewhale_runtime::config::save_api_key_for_identity(&identity, &config, "saved-b-key") |
| 2740 | .expect("save named custom key"); |
| 2741 | codewhale_runtime::config::save_provider_model_for_identity( |
| 2742 | &identity, |
| 2743 | &config, |
| 2744 | "model-b-updated", |
| 2745 | ) |
| 2746 | .expect("save named custom model"); |
| 2747 | |
| 2748 | let saved = std::fs::read_to_string(config_env.config_path()).expect("saved config"); |
| 2749 | let table: toml::Table = toml::from_str(&saved).expect("saved config parses"); |
| 2750 | // The literal route's key moved into its own table, untouched by the |
| 2751 | // named route's save (#6394). |
| 2752 | assert_eq!( |
| 2753 | table["providers"]["custom"]["api_key"].as_str(), |
| 2754 | Some("legacy-root-key") |
| 2755 | ); |
| 2756 | assert!(saved.contains("default_text_model = \"legacy-model\"")); |
| 2757 | assert!(saved.contains("[providers.custom-b]")); |
| 2758 | assert!(saved.contains("api_key = \"saved-b-key\"")); |
| 2759 | assert!(saved.contains("model = \"model-b-updated\"")); |
| 2760 | } |
| 2761 | } |
| 2762 | |
| 2763 | /// Build the foreground receipt only from the immutable route captured when |
| 2764 | /// this turn started. The app's selected route may already have changed by the |
| 2765 | /// time `TurnComplete` is handled, so it is not accepted as an input here. |
| 2766 | fn completed_turn_cost_route_receipt( |
| 2767 | completed_turn: Option<&crate::tui::app::ActiveTurnMetadata>, |
| 2768 | audit: &codewhale_engine::pricing::TurnCostAudit, |
| 2769 | ) -> Option<String> { |
| 2770 | let route = completed_turn?.route.as_ref()?; |
| 2771 | Some(route.cost_envelope()?.receipt(audit)) |
| 2772 | } |
| 2773 | |
| 2774 | #[cfg(test)] |
| 2775 | mod tests; |
| 2776 | |
| 2777 | #[cfg(test)] |
| 2778 | #[tokio::test] |
| 2779 | async fn fleet_role_entry_opens_shared_picker_and_cancel_restores_parked_roster() { |
| 2780 | use crate::tui::views::ModalView; |
| 2781 | let _env = crate::test_support::lock_test_env(); |
| 2782 | let workspace = tempfile::tempdir().unwrap(); |
| 2783 | let config = Config::default(); |
| 2784 | let mut app = App::new( |
| 2785 | crate::tui::test_support::test_tui_options(workspace.path()), |
| 2786 | &config, |
| 2787 | ); |
| 2788 | app.view_stack |
| 2789 | .push(crate::tui::views::fleet_roster::FleetRosterView::new( |
| 2790 | &app, &config, |
| 2791 | )); |
| 2792 | open_fleet_setup_target(&mut app, &config, Some("manager")).await; |
| 2793 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::ModelPicker)); |
| 2794 | let mut picker = app.view_stack.pop().unwrap(); |
| 2795 | let action = picker |
| 2796 | .as_any_mut() |
| 2797 | .downcast_mut::<crate::tui::model_picker::ModelPickerView>() |
| 2798 | .unwrap() |
| 2799 | .handle_key(crossterm::event::KeyEvent::new( |
| 2800 | crossterm::event::KeyCode::Esc, |
| 2801 | crossterm::event::KeyModifiers::NONE, |
| 2802 | )); |
| 2803 | let ViewAction::EmitAndClose(ViewEvent::FleetAssignmentPickerDismissed { editor_id }) = action |
| 2804 | else { |
| 2805 | panic!("assignment cancel must identify its editor") |
| 2806 | }; |
| 2807 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::FleetSetup)); |
| 2808 | handlers::dismiss_fleet_assignment(&mut app, editor_id); |
| 2809 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::FleetRoster)); |
| 2810 | assert!( |
| 2811 | !workspace |
| 2812 | .path() |
| 2813 | .join(".codewhale/agents/manager.toml") |
| 2814 | .exists() |
| 2815 | ); |
| 2816 | } |
| 2817 |