返回 CodeWhale
app.rs
根目录 / crates / tui / src / tui / app.rs
1 //! Application state for the `DeepSeek` TUI.
2
3 use std::borrow::Cow;
4 use std::cell::RefCell;
5 use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
6 use std::path::{Path, PathBuf};
7 use std::sync::Arc;
8 use std::time::{Duration, Instant};
9
10 use chrono::{DateTime, Utc};
11 use ratatui::layout::Rect;
12 use ratatui::style::Color;
13 use serde_json::Value;
14
15 use codewhale_config::{AppMode, ProviderChain, route::RouteLimits};
16 use codewhale_core::ContextReference;
17 use codewhale_execpolicy::ApprovalMode;
18
19 use crate::tui::active_cell::ActiveCell;
20 use crate::tui::clipboard::ClipboardHandler;
21 use crate::tui::history::{
22 HistoryCell, TranscriptActionOwner, TranscriptFold, TranscriptRenderOptions,
23 };
24 use crate::tui::hotbar::HotbarActionRegistry;
25 use crate::tui::motion::MotionPolicy;
26 use crate::tui::selection::{SelectionAutoscroll, TranscriptSelection};
27 use crate::tui::shell_key_routing::Focus;
28 use crate::tui::transcript::TranscriptViewCache;
29 use crate::tui::views::{ModalKind, ViewStack};
30 use codewhale_config::ProviderKind;
31 use codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL;
32 use codewhale_config::hooks::HookEvent;
33 use codewhale_config::pricing::CostCurrency;
34 use codewhale_engine::client::{CacheWarmupKey, PromptInspection};
35 use codewhale_engine::compaction::CompactionConfig;
36 use codewhale_engine::core::authority::{ModeSessionPrefs, base_policy_for_mode};
37 use codewhale_engine::core::events::TurnRoute;
38 use codewhale_engine::hooks::{HookContext, HookExecutor};
39 use codewhale_engine::pricing::CostEstimate;
40 use codewhale_engine::provider_readiness::{has_api_key, has_api_key_for};
41 use codewhale_engine::reasoning_preference::{EffectiveReasoningEffort, ReasoningEffort};
42 use codewhale_engine::session_manager::{
43 SessionContextReference, SessionMetadata, SessionWorkState,
44 };
45 use codewhale_engine::tools::plan::{PlanState, SharedPlanState, new_shared_plan_state};
46 use codewhale_engine::tools::shell::new_shared_shell_manager;
47 use codewhale_engine::tools::spec::RuntimeToolServices;
48 use codewhale_engine::tools::subagent::{AgentWorkerStatus, SubAgentResult};
49 use codewhale_engine::tools::todo::{SharedTodoList, TodoList, new_shared_todo_list};
50 use codewhale_localization::{Locale, MessageId, resolve_locale, tr};
51 use codewhale_models::{ContentBlock, Message, SystemPrompt, Tool, Usage};
52 use codewhale_palette::{self as palette, UiTheme};
53 use codewhale_runtime::artifacts::ArtifactRecord;
54 use codewhale_runtime::config::{ApprovalPolicyControl, Config};
55 use codewhale_runtime::settings::{InlineDiffMode, Settings};
56 use codewhale_tui_kit::paste_burst::{FlushResult, PasteBurst};
57 use codewhale_tui_kit::scrolling::{MouseScrollState, TranscriptLineMeta, TranscriptScroll};
58 use codewhale_tui_kit::streaming::StreamingState;
59
60 mod composer;
61 mod init;
62 mod status;
63 mod types;
64
65 pub use composer::ComposerHistorySearch;
66 pub(crate) use composer::{InputHistoryDraft, char_count};
67 #[cfg(test)]
68 pub(crate) use composer::{
69 MAX_SUBMITTED_INPUT_CHARS, next_grapheme_boundary, prev_grapheme_boundary,
70 };
71 pub(crate) use status::StatusToastKind;
72 pub use status::{StatusToast, StatusToastLevel};
73
74 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
75 pub(crate) enum RedactionGateNotice {
76 EnterGuidance,
77 WriteFailure,
78 }
79 pub use types::{
80 AppAction, AppModeUi, AutomationAction, ComposerDensity, ComposerSubmitAction,
81 ComposerSubmitChord, DialStep, InflightSteer, InitialInput, McpUiAction, QueuedMessage,
82 SettingSelection, ShellJobAction, SubmitDisposition, TaskPanelEntry, TaskPanelEntryKind,
83 ToolCollapseMode, ToolDetailRecord, TranscriptSpacing, TuiOptions, VimMode,
84 };
85 pub(crate) use types::{
86 CacheReplayTarget, GoalControlIntent, PendingGoalControl, UnansweredSubmission,
87 };
88
89 const ACCOUNT_PREFERENCES_NOTICE: &str = "account-preferences-notice";
90 const AGENT_APPROVED_PLUGINS_NOTICE: &str = "agent-approved-plugins-notice";
91
92 fn account_sign_in_marker(profile: Option<&str>) -> String {
93 use sha2::{Digest, Sha256};
94 let api_base = codewhale_engine::profile_constitution::runtime_account_api_base();
95 let session = codewhale_secrets::account::AccountSessionStore::new(
96 codewhale_secrets::Secrets::file_backed_read_only(),
97 profile,
98 &api_base,
99 )
100 .runtime_info_at(Utc::now())
101 .ok()
102 .and_then(|info| info.session_id)
103 .unwrap_or_default();
104 Sha256::digest(session.as_bytes())
105 .iter()
106 .take(8)
107 .map(|byte| format!("{byte:02x}"))
108 .collect()
109 }
110
111 // === Types ===
112
113 /// One login owns one mailbox. A cancelled task can only write its abandoned
114 /// mailbox, so a late result cannot complete or clear a later login.
115 pub(crate) struct PendingMcpLogin {
116 pub server: String,
117 pub cancel: tokio_util::sync::CancellationToken,
118 pub progress: std::sync::Arc<std::sync::Mutex<Option<McpLoginProgress>>>,
119 }
120
121 pub(crate) enum McpLoginProgress {
122 AuthorizationUrl(String),
123 Finished(Result<(), String>),
124 }
125
126 /// One `/mcp retry <name>` in flight. The retry runs as an engine op from a
127 /// background task, so a running turn queues it in the engine mailbox instead
128 /// of parking the UI loop (#6159) or asking the person to press it again; the
129 /// outcome lands in `result` and `poll_mcp_retries` reports it.
130 pub(crate) struct PendingMcpRetry {
131 pub server: String,
132 /// A turn owned the engine when the retry was requested, so it waits for
133 /// that turn to finish before it connects.
134 pub queued: bool,
135 pub result: std::sync::Arc<
136 std::sync::Mutex<Option<Result<codewhale_engine::core::ops::McpManagerUpdate, String>>>,
137 >,
138 }
139
140 impl Drop for PendingMcpLogin {
141 fn drop(&mut self) {
142 self.cancel.cancel();
143 }
144 }
145
146 /// Lifecycle identity retained until the matching `TurnComplete` arrives.
147 ///
148 /// This survives local cancellation clearing the visible runtime status, so
149 /// observer records still carry a stable id, start time, and effective route.
150 #[derive(Debug, Clone, PartialEq, Eq)]
151 pub struct ActiveTurnMetadata {
152 pub turn_id: String,
153 pub created_at: DateTime<Utc>,
154 pub route: Option<TurnRoute>,
155 /// Auto decision metadata captured with this exact authoritative route.
156 pub auto_route_receipt: Option<codewhale_engine::model_routing::AutoRouteReceipt>,
157 /// Non-secret proof of the exact endpoint + credential this turn launched
158 /// against, adopted at `TurnStarted` from the engine's route receipt — not
159 /// re-resolved from mutable config. Only populated for routes that can
160 /// produce a follow-up prompt suggestion; see
161 /// [`crate::tui::prompt_suggestion::capture_route_authority`].
162 pub suggestion_authority: Option<crate::tui::prompt_suggestion::SuggestionRouteAuthority>,
163 }
164
165 /// Identity of the compaction pass currently rewriting session context.
166 ///
167 /// The event id prevents a delayed terminal event from clearing a newer pass,
168 /// while `auto` selects the truthful live label in the phase strip.
169 #[derive(Debug, Clone, PartialEq, Eq)]
170 pub(crate) struct ActiveCompaction {
171 pub(crate) id: String,
172 pub(crate) auto: bool,
173 }
174
175 /// Per-message context estimates used by the render-time context meter.
176 /// Messages are append-only in the steady state; only the streaming tail is
177 /// mutable, so the tail is refreshed while older entries remain cached.
178 #[derive(Debug, Default)]
179 pub(crate) struct ContextTokenCache {
180 pub(crate) message_tokens: Vec<usize>,
181 }
182
183 #[derive(Debug, Clone)]
184 pub(crate) struct AutoRouteBudget {
185 pub provider: ProviderKind,
186 pub provider_identity: String,
187 pub model: String,
188 pub limits: Option<RouteLimits>,
189 pub window: codewhale_engine::route_runtime::ContextWindowResolution,
190 pub restored: bool,
191 }
192
193 #[derive(Debug, Clone, PartialEq, Eq)]
194 struct CompletedAssistantOutputReceipt {
195 history_index: usize,
196 text: String,
197 }
198
199 impl ContextTokenCache {
200 pub(crate) fn clear(&mut self) {
201 self.message_tokens.clear();
202 }
203 }
204
205 /// State machine for onboarding new users: one decision per screen, and
206 /// only the decisions this install genuinely needs (#3938).
207 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
208 pub enum OnboardingState {
209 Welcome,
210 /// Pick the UI locale — shown only when it cannot be confidently
211 /// inferred from settings or `LC_ALL` / `LANG` (#566). Explicit picks
212 /// land in the persisted settings.toml via `Settings::set("locale", …)`.
213 Language,
214 /// Choose a provider/model route — shown only when no usable local,
215 /// authenticated, or BYOK route is configured. The canonical provider
216 /// picker modal carries the choice itself.
217 Provider,
218 /// Trust the workspace — shown only when a trust decision is required.
219 TrustDirectory,
220 /// "You're ready." Enter opens the real composer pre-seeded with a
221 /// first task for this folder. Never an educational surface.
222 Ready,
223 None,
224 }
225
226 /// Pick the session's primary skills dir. A workspace directory is chosen only
227 /// when the workspace-trust gate admits it; an untrusted repository falls back
228 /// to the global dir so its skills neither load nor become the install target.
229 pub(crate) fn resolve_skills_dir(
230 workspace: &Path,
231 global_skills_dir: &Path,
232 config: &Config,
233 ) -> PathBuf {
234 let admitted =
235 |dir: &Path| codewhale_skills::skills_dir_allowed_by_workspace_trust(workspace, dir);
236 if config.skills_config().scan_codewhale_only() {
237 if config.skills_dir.is_some() {
238 return global_skills_dir.to_path_buf();
239 }
240 if let Some(codewhale_skills_dir) =
241 codewhale_skills::codewhale_workspace_skills_dir(workspace)
242 && admitted(&codewhale_skills_dir)
243 {
244 return codewhale_skills_dir;
245 }
246 return global_skills_dir.to_path_buf();
247 }
248
249 for local_skills_dir in [
250 workspace.join(".codewhale/skills"),
251 workspace.join(".agents/skills"),
252 workspace.join(".claude/skills"),
253 workspace.join(".opencode/skills"),
254 workspace.join(".cursor/skills"),
255 ] {
256 if local_skills_dir.exists() && admitted(&local_skills_dir) {
257 return local_skills_dir;
258 }
259 }
260
261 let flat = workspace.join("skills");
262 if config.skills_config().flat_workspace_root() && flat.exists() && admitted(&flat) {
263 return flat;
264 }
265 if global_skills_dir.exists() {
266 return global_skills_dir.to_path_buf();
267 }
268 if config.skills_dir.is_none()
269 && let Some(global_agents) = codewhale_skills::agents_global_skills_dir()
270 && global_agents.exists()
271 {
272 return global_agents;
273 }
274
275 global_skills_dir.to_path_buf()
276 }
277
278 pub(crate) fn looks_like_slash_command_input(input: &str) -> bool {
279 let trimmed = input.trim_start();
280 // `$skillname` at the start of input is treated like a slash command so the
281 // skill-completion menu appears.
282 let Some(rest) = trimmed
283 .strip_prefix('/')
284 .or_else(|| trimmed.strip_prefix('$'))
285 else {
286 return false;
287 };
288 if rest.chars().next().is_some_and(|ch| ch.is_whitespace()) {
289 return false;
290 }
291 let Some(command) = rest.split_whitespace().next() else {
292 return rest.is_empty();
293 };
294
295 !command.contains('/')
296 }
297
298 pub(crate) fn shell_command_from_bang_input(input: &str) -> Result<Option<&str>, &'static str> {
299 let Some(rest) = input.trim_start().strip_prefix('!') else {
300 return Ok(None);
301 };
302 let command = rest.trim();
303 if command.is_empty() {
304 return Err("Usage: ! <shell command>");
305 }
306
307 Ok(Some(command))
308 }
309
310 pub(crate) fn is_stop_word(input: &str, stop_words: &[String]) -> Option<String> {
311 let trimmed = input.trim();
312 let after_prefix = trimmed
313 .strip_prefix('+')
314 .or_else(|| trimmed.strip_prefix('!'))
315 .map_or(trimmed, str::trim_start);
316 let word = after_prefix.trim_end_matches(|c: char| c.is_ascii_punctuation());
317 if word.is_empty() || word.chars().any(char::is_whitespace) {
318 return None;
319 }
320 let lower = word.to_ascii_lowercase();
321 stop_words
322 .iter()
323 .find(|stop_word| stop_word.to_ascii_lowercase() == lower)
324 .cloned()
325 }
326
327 fn initial_onboarding_state(
328 skip_onboarding: bool,
329 _was_onboarded: bool,
330 _needs_language: bool,
331 needs_api_key: bool,
332 needs_workspace_trust: bool,
333 ) -> OnboardingState {
334 if skip_onboarding || needs_api_key {
335 return OnboardingState::None;
336 }
337
338 if needs_workspace_trust {
339 OnboardingState::TrustDirectory
340 } else {
341 OnboardingState::None
342 }
343 }
344
345 fn onboarding_is_workspace_trust_gate(
346 skip_onboarding: bool,
347 _was_onboarded: bool,
348 needs_api_key: bool,
349 needs_workspace_trust: bool,
350 ) -> bool {
351 !skip_onboarding && !needs_api_key && needs_workspace_trust
352 }
353
354 /// Resolve the launch onboarding state and the missing-key-recovery flag in one
355 /// place. When the active xAI OAuth credential is missing (`xai_oauth_needs_reauth`),
356 /// the user already chose xAI and only needs to re-authenticate it — so the
357 /// generic provider picker must NOT reopen (returns `OnboardingState::None` and
358 /// `missing_key_recovery = false`); the caller surfaces a re-auth message (#5032).
359 fn launch_onboarding_decision(
360 skip_onboarding: bool,
361 was_onboarded: bool,
362 needs_language: bool,
363 needs_api_key: bool,
364 needs_workspace_trust: bool,
365 xai_oauth_needs_reauth: bool,
366 ) -> (OnboardingState, bool) {
367 let onboarding = if xai_oauth_needs_reauth {
368 OnboardingState::None
369 } else {
370 initial_onboarding_state(
371 skip_onboarding,
372 was_onboarded,
373 needs_language,
374 needs_api_key,
375 needs_workspace_trust,
376 )
377 };
378 // A launch with no usable key opens the composer. The provider picker
379 // opens when the first message is sent (`keep_unsent_message_for_connect`),
380 // and Esc there returns to the composer. An explicitly configured route is
381 // focused even on first run (see `onboarding_recovers_configured_route`).
382 let missing_key_recovery = !skip_onboarding && needs_api_key && !xai_oauth_needs_reauth;
383 (onboarding, missing_key_recovery)
384 }
385
386 /// One row in the per-turn cache-telemetry ring (`/cache` debug surface, #263).
387 #[derive(Debug, Clone)]
388 pub struct TurnCacheRecord {
389 /// API provider used for the turn. This is recorded so cache misses can be
390 /// correlated with provider/model route changes.
391 pub provider: Option<ProviderKind>,
392 /// Exact non-secret configured route key. This distinguishes named custom
393 /// providers which all share [`ProviderKind::Custom`].
394 pub provider_identity: Option<String>,
395 /// Concrete model used for the turn. For auto-model turns this is the
396 /// routed model, not the literal `auto` setting.
397 pub model: Option<String>,
398 /// Whether the route came from the auto-model selector.
399 pub auto_model: bool,
400 /// Provider-reported total input tokens for the turn (cache-hit +
401 /// cache-miss + uncategorized). Useful for sanity-checking that hits +
402 /// misses sum back to roughly the prompt size.
403 pub input_tokens: u32,
404 /// Provider-reported output tokens.
405 pub output_tokens: u32,
406 /// `prompt_cache_hit_tokens` from DeepSeek's usage payload. `None` when
407 /// the model in use does not report cache telemetry (see
408 /// `Capabilities::cache_telemetry_supported`).
409 pub cache_hit_tokens: Option<u32>,
410 /// `prompt_cache_miss_tokens`. `None` when the provider did not report it
411 /// — in that case the `/cache` formatter infers the miss as
412 /// `input_tokens − cache_hit_tokens`.
413 pub cache_miss_tokens: Option<u32>,
414 /// Cache-creation tokens (`cache_creation_input_tokens` on Anthropic-style
415 /// payloads). Billed at a premium where the provider publishes one, so
416 /// they are recorded as their own class rather than folded into misses.
417 pub cache_write_tokens: Option<u32>,
418 /// Reasoning tokens the provider reported. **Informational only**: every
419 /// provider counts these inside `output_tokens`, so they are never added
420 /// to billable output.
421 pub reasoning_tokens: Option<u32>,
422 /// The turn's cost with its provenance and per-class completeness, taken
423 /// from the same call that fed the session total. `None` for records made
424 /// without route provenance (legacy rows, synthetic test rows).
425 pub cost_audit: Option<codewhale_engine::pricing::TurnCostAudit>,
426 /// Approximate tokens spent re-sending prior `reasoning_content` on
427 /// V4-thinking tool-calling turns (chars/3 heuristic). Helps separate
428 /// cache misses caused by reasoning-replay churn from misses caused by
429 /// real prefix instability.
430 pub reasoning_replay_tokens: Option<u32>,
431 /// Local timestamp the turn telemetry was recorded.
432 pub recorded_at: Instant,
433 }
434
435 /// Browsing context captured when the `/model` picker is dismissed (#4109).
436 /// Plain data so `App` does not depend on the picker's internal view enum.
437 #[derive(Debug, Clone, PartialEq, Eq)]
438 pub struct ModelPickerMemory {
439 /// True when the user left the picker in the full-catalog view
440 /// (`A` toggle), false for the configured-only default view.
441 ///
442 /// Kept for backward compatibility with older dismiss events; prefer
443 /// [`Self::view`] when present (#4115).
444 pub catalog_view: bool,
445 /// Named catalog view left open (`configured` / `catalog` / `recent` /
446 /// `coding` / `cheap` / `long_context`). When `None`, [`Self::catalog_view`]
447 /// is the fallback.
448 pub view: Option<String>,
449 /// Model row id highlighted at dismissal, if it was a real row.
450 pub selected_row_id: Option<String>,
451 }
452
453 /// Browsing context captured when the `/provider` picker is dismissed.
454 /// Mirrors [`ModelPickerMemory`] so reopen restores view + highlight.
455 #[derive(Debug, Clone, PartialEq, Eq)]
456 pub struct ProviderPickerMemory {
457 /// True when the user left the picker in the full-catalog view
458 /// (`A` toggle), false for the configured-only default view.
459 pub catalog_view: bool,
460 /// Provider id highlighted at dismissal, if it was a real row.
461 pub selected_provider_id: Option<String>,
462 }
463
464 /// Bounded status vocabulary for the per-agent current-activity projection.
465 ///
466 /// This is presentation state derived from structured worker/mailbox events;
467 /// renderers map these variants to labels but never infer them from strings.
468 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
469 pub enum AgentCurrentActivityStatus {
470 Queued,
471 Starting,
472 Running,
473 ModelWait,
474 RunningTool,
475 Waiting,
476 /// Settled because the parent's turn ended before this child did, not
477 /// because it asked anyone anything (#5906).
478 ///
479 /// The runtime parks such a child with a `needs_input` note that reads
480 /// like a question, so every surface used to render it as
481 /// `waiting for input` — indistinguishable from a child a user can
482 /// actually answer. It is its own state here because the recovery is
483 /// different: nobody will answer it, and it is continued through
484 /// `resume_from` (a *new* agent) or dismissed with `cancel`.
485 Parked,
486 Done,
487 Failed,
488 Canceled,
489 Interrupted,
490 }
491
492 impl From<AgentWorkerStatus> for AgentCurrentActivityStatus {
493 /// Never yields [`Self::Parked`]: the worker status vocabulary cannot
494 /// express it (a parked child reports `WaitingForUser` /`Interrupted`
495 /// like any other settled one). Parked is derived from the checkpoint
496 /// flag by `crate::tui::subagent_routing::subagent_is_parked` and layered
497 /// over this mapping there — the one place that distinction is made.
498 fn from(status: AgentWorkerStatus) -> Self {
499 match status {
500 AgentWorkerStatus::Queued => Self::Queued,
501 AgentWorkerStatus::Starting => Self::Starting,
502 AgentWorkerStatus::Running => Self::Running,
503 AgentWorkerStatus::WaitingForUser => Self::Waiting,
504 AgentWorkerStatus::ModelWait => Self::ModelWait,
505 AgentWorkerStatus::RunningTool => Self::RunningTool,
506 AgentWorkerStatus::Completed => Self::Done,
507 AgentWorkerStatus::Failed => Self::Failed,
508 AgentWorkerStatus::Cancelled => Self::Canceled,
509 AgentWorkerStatus::Interrupted => Self::Interrupted,
510 }
511 }
512 }
513
514 #[derive(Debug, Clone, PartialEq, Eq)]
515 pub struct AgentCurrentActivity {
516 pub status: AgentCurrentActivityStatus,
517 /// Safe bounded context, never a raw child transcript or tool result.
518 pub detail: Option<String>,
519 /// Safe display name for the one tool currently executing.
520 pub current_tool: Option<String>,
521 pub step: Option<u32>,
522 }
523
524 impl AgentCurrentActivity {
525 #[must_use]
526 pub fn bounded(
527 status: AgentCurrentActivityStatus,
528 detail: Option<String>,
529 current_tool: Option<String>,
530 step: Option<u32>,
531 ) -> Self {
532 fn bounded_nonempty(value: Option<String>) -> Option<String> {
533 value
534 .map(|value| bound_agent_activity_text(&value))
535 .filter(|value| !value.trim().is_empty())
536 }
537
538 Self {
539 status,
540 detail: bounded_nonempty(detail),
541 current_tool: bounded_nonempty(current_tool),
542 step,
543 }
544 }
545 }
546
547 /// Convert untrusted child-agent text into a compact UI-safe projection.
548 /// Full transcript artifacts remain the source of truth; only summaries that
549 /// can enter the parent transcript/sidebar pass through this seam.
550 pub(crate) fn bound_agent_activity_text(value: &str) -> String {
551 let mut visible = String::with_capacity(value.len());
552 codewhale_sanitize::sanitize::strip_ansi_into(value, &mut visible);
553 let redacted = codewhale_config::persistence::redact_secrets(&visible);
554 codewhale_app_server::exec_agent::summarize_tool_output(&redacted)
555 }
556
557 /// One bounded, structured tool outcome for the Agent Details projection.
558 ///
559 /// This is populated only from `ToolCallCompleted` mailbox envelopes. It is
560 /// deliberately not inferred from free-form progress text.
561 #[derive(Debug, Clone, PartialEq, Eq)]
562 pub struct AgentRecentAction {
563 pub tool: String,
564 pub step: u32,
565 pub ok: bool,
566 }
567
568 impl AgentRecentAction {
569 #[must_use]
570 pub fn bounded(tool: &str, step: u32, ok: bool) -> Self {
571 Self {
572 tool: bound_agent_activity_text(tool),
573 step,
574 ok,
575 }
576 }
577 }
578
579 pub(crate) const MAX_AGENT_RECENT_ACTIONS: usize = 3;
580
581 /// Most blocked-transition task rows named before the rest are summarized;
582 /// an error message must not become a screenful.
583 const MAX_TRANSITION_BLOCKER_TASKS: usize = 5;
584
585 /// Display columns one blocked-transition task row may occupy. The row is
586 /// rendered as a transcript Note, whose content width in an 80-column
587 /// terminal is 74; a wider row wraps into the message and strands its own
588 /// continuation lines.
589 const TRANSITION_BLOCKER_LINE_WIDTH: usize = 74;
590
591 /// Floor for the summary budget when the other columns are unusually wide;
592 /// below this a row names an id and nothing useful about it.
593 const MIN_TRANSITION_BLOCKER_SUMMARY_WIDTH: usize = 16;
594
595 #[derive(Debug, Clone, Default, PartialEq, Eq)]
596 pub struct AgentProgressMeta {
597 pub parent_run_id: Option<String>,
598 pub spawn_depth: u32,
599 /// Structured, bounded answer to "what is this agent doing now?".
600 pub current_activity: Option<AgentCurrentActivity>,
601 /// Last tool observed running for this child. Cleared by the matching
602 /// completion envelope so Work never presents a settled tool as live.
603 pub current_tool: Option<String>,
604 /// Successful file mutations observed for this child in this session.
605 pub files_touched: u32,
606 /// At most three tool outcomes observed through structured lifecycle
607 /// envelopes, oldest to newest.
608 pub recent_actions: VecDeque<AgentRecentAction>,
609 /// Effective route facts observed from the child's installed spawn route
610 /// or a later provider usage envelope. The launch event carries the exact
611 /// model frozen into the child runtime; usage may confirm it while also
612 /// supplying provider identity.
613 pub resolved_provider: Option<String>,
614 pub resolved_model: Option<String>,
615 /// Tokens this child has *used* (input + output), accumulated across its
616 /// own usage envelopes — the same total the worker budget tracks.
617 /// `None` until the provider actually reports usage: a sub-agent whose
618 /// spend is unknown renders no token figure at all rather than a
619 /// fabricated `0`.
620 pub received_tokens: Option<u64>,
621 pub received_usage_sources: HashMap<String, u64>,
622 /// Unsettled items on this child's own To-do list, from the latest
623 /// `WorkState` envelope. `None` until a real list is published — the
624 /// strip never invents a `0 left` chip for agents with no checklist.
625 pub todos_remaining: Option<u32>,
626 /// The engine's name for this agent from its spawn or completion event
627 /// (`subagent_display_name`), used until a manager snapshot arrives.
628 pub display_name: Option<String>,
629 /// When the TUI last received any mailbox envelope from this child. The
630 /// manager's `idle_ms` is only as fresh as the last `AgentList` snapshot,
631 /// and ordinary progress does not refresh that snapshot, so the quiet
632 /// readout caps the engine's clock with this one.
633 pub last_progress_at: Option<Instant>,
634 pub started_at: Option<Instant>,
635 }
636
637 /// Per-turn LSP repair-loop summary for the Turn Inspector (#4107).
638 /// Observable state only — no raw diagnostic text or prompt internals.
639 #[derive(Debug, Clone, PartialEq, Eq)]
640 pub struct LspRepairState {
641 pub diagnostics_found: usize,
642 pub files_touched: usize,
643 pub injected: bool,
644 pub repair_attempted: bool,
645 /// "resolved" | "still_failing" | "unknown" | "unavailable"
646 pub latest: &'static str,
647 }
648
649 impl Default for LspRepairState {
650 fn default() -> Self {
651 Self {
652 diagnostics_found: 0,
653 files_touched: 0,
654 injected: false,
655 repair_attempted: false,
656 latest: "unavailable",
657 }
658 }
659 }
660
661 /// One recent session for the startup card's recent-work list (PRD 4.1).
662 /// Loaded once with the launch state — never on the render path — and
663 /// refreshed whenever the card is restored after a picker closes.
664 #[derive(Debug, Clone, PartialEq, Eq)]
665 pub struct LaunchRecentSession {
666 pub id: String,
667 pub title: String,
668 pub updated_at: DateTime<Utc>,
669 pub message_count: usize,
670 pub interrupted: bool,
671 }
672
673 /// Identity of one interactive row on the startup card. The card's rows are
674 /// a single ordered list — the prominent new-session entry first, then
675 /// recent work, then the see-all overflow — so keyboard, mouse, and paint
676 /// share one indexing through
677 /// [`crate::tui::underwater::launch_card_rows`].
678 #[derive(Debug, Clone, PartialEq, Eq)]
679 pub enum LaunchRowId {
680 ConnectModel,
681 NewSession,
682 ReturnToSession,
683 Recent(String),
684 SeeAll,
685 ShowRecent,
686 /// Open the MCP manager from the status summary, including healthy servers.
687 McpManager,
688 Skills,
689 }
690
691 /// How many recent sessions the startup card lists inline before the
692 /// see-all overflow opens the full picker.
693 pub(crate) const LAUNCH_RECENT_INLINE_LIMIT: usize = 5;
694
695 /// Pre-session launch menu state for the underwater shell.
696 ///
697 /// This is deliberately separate from onboarding and from the post-launch
698 /// empty session. It selects a fresh session or recent work before the
699 /// transcript and composer become active.
700 #[derive(Debug, Clone, PartialEq, Eq)]
701 pub struct LaunchState {
702 pub visible: bool,
703 /// Home temporarily covers the current conversation; it does not own a session.
704 pub return_to_session: bool,
705 pub status: Option<String>,
706 /// Canonical workspace this launch state is scoped to. Recent work is
707 /// the workspace's own sessions (archived and empty auto-created ones
708 /// excluded, like the resume picker); the row hitboxes below are
709 /// refreshed with it.
710 pub workspace: PathBuf,
711 /// Recent workspace sessions, most recent first, capped at
712 /// [`LAUNCH_RECENT_INLINE_LIMIT`].
713 pub recent: Vec<LaunchRecentSession>,
714 /// All workspace sessions behind the inline list; when this exceeds
715 /// `recent.len()` the card paints the see-all overflow row.
716 pub total_workspace_sessions: usize,
717 /// Whether this workspace has any sessions at all — including the
718 /// empty auto-created shells `recent` deliberately drops. The card
719 /// must not say "no recent sessions yet" while `/resume` lists them;
720 /// when they exist it shows the see-all row instead of the lie.
721 pub has_scoped_sessions: bool,
722 pub recent_expanded: bool,
723 /// Whether launch keys type into the pre-session composer. The composer
724 /// is the launch screen's one focus owner, so this is `true` from first
725 /// paint. The composer itself is the session `App`'s own
726 /// `ComposerState` — this flag only decides where keystrokes go.
727 pub composer_focus: bool,
728 /// Clickable rects for the card's rows from the most recent launch
729 /// render, in the same order as
730 /// [`crate::tui::underwater::launch_card_rows`].
731 pub row_hitboxes: Vec<(LaunchRowId, Rect)>,
732 /// Card row under the pointer, if any (index into `row_hitboxes`).
733 /// Painted with the shared selected-row treatment so every clickable
734 /// element responds visibly on hover.
735 pub hovered_row: Option<usize>,
736 /// The launch card's highlighted row (index into the rows the card
737 /// paints). `None` until the user arrows onto the list: nothing is
738 /// pre-selected, so a reflexive Enter at launch does nothing rather
739 /// than starting or resuming a session by accident (founder live-test,
740 /// 2026-09-02). Esc clears it again.
741 pub menu_selected: Option<usize>,
742 /// Ambient-clock millisecond reading when the card began dissolving, if
743 /// it has. The first keystroke or a launched command dissolves the card
744 /// (founder decision, 2026-09-02).
745 pub dissolve_started_ms: Option<u128>,
746 /// One bounded reveal of the canonical mark, anchored at first paint.
747 /// Kept when the launcher is revisited so it never replays on navigation.
748 pub mark_reveal_started_at: Option<Instant>,
749 /// Claude Code config was detected on this host (probed once at
750 /// construction); drives the launch card's migration notice line.
751 pub claude_code_detected: bool,
752 pub whats_new: Option<crate::whats_new::WhatsNewNotice>,
753 }
754
755 /// The launch card's dissolve motion budget. One bounded motion; reduced
756 /// motion dissolves instantly (same drawing at its endpoint).
757 pub(crate) const LAUNCH_CARD_DISSOLVE_MS: u128 = 240;
758
759 /// Load the startup card's recent-work list: the workspace's own sessions,
760 /// most recent first (`list_sessions` already sorts that way), skipping
761 /// archived sessions and — unlike the resume picker, which lists them —
762 /// empty auto-created shells. Returns the inline-capped list, the total
763 /// behind it for the see-all overflow, and whether any scoped sessions
764 /// exist at all so the card never claims "no recent sessions" while
765 /// `/resume` has some.
766 fn load_launch_recent(workspace: &std::path::Path) -> (Vec<LaunchRecentSession>, usize, bool) {
767 let manager = codewhale_engine::session_manager::SessionManager::default_location().ok();
768 let sessions = manager
769 .as_ref()
770 .map(|manager| manager.list_sessions_lenient())
771 .unwrap_or_default();
772 let any_scoped = sessions.iter().any(|session| {
773 !session.archived
774 && codewhale_engine::session_manager::workspace_scope_matches(
775 &session.workspace,
776 workspace,
777 )
778 });
779 let mut scoped: Vec<LaunchRecentSession> = sessions
780 .into_iter()
781 .filter(|session| {
782 !session.archived
783 && !codewhale_engine::session_manager::is_empty_auto_created_session(session)
784 && codewhale_engine::session_manager::workspace_scope_matches(
785 &session.workspace,
786 workspace,
787 )
788 })
789 .map(|session| LaunchRecentSession {
790 interrupted: false,
791 id: session.id,
792 title: session.title,
793 updated_at: session.updated_at,
794 message_count: session.message_count,
795 })
796 .collect();
797 let total = scoped.len();
798 scoped.truncate(LAUNCH_RECENT_INLINE_LIMIT);
799 if let Some(manager) = manager.as_ref() {
800 for session in &mut scoped {
801 session.interrupted = manager.session_has_checkpoint(&session.id)
802 && manager.session_from_prior_instance(&session.id)
803 && !manager.is_session_live_anywhere(&session.id);
804 }
805 }
806 (scoped, total, any_scoped)
807 }
808
809 impl LaunchState {
810 #[must_use]
811 pub fn new(visible: bool, workspace: &std::path::Path) -> Self {
812 let (recent, total_workspace_sessions, has_scoped_sessions) = load_launch_recent(workspace);
813 // The migration notice answers a question you have exactly once:
814 // "I have Claude Code, what comes over?". It used to key on
815 // `~/.claude/projects` alone, so anyone who keeps Claude Code
816 // installed saw it on every single launch forever. It now retires as
817 // soon as `/import-claude` has been run — that command always writes
818 // its report, so the report is the durable receipt that the question
819 // has been answered. Two stats at construction, never on the render
820 // path.
821 let has_claude_code = std::env::var_os("HOME")
822 .as_ref()
823 .map(|home| {
824 std::path::Path::new(home)
825 .join(".claude")
826 .join("projects")
827 .is_dir()
828 })
829 .unwrap_or(false);
830 let import_already_reviewed = codewhale_config::codewhale_home()
831 .map(|home| {
832 home.join("imports")
833 .join("claude-import-report.md")
834 .exists()
835 })
836 .unwrap_or(false);
837 let claude_code_detected = has_claude_code && !import_already_reviewed;
838 Self {
839 visible,
840 return_to_session: false,
841 status: None,
842 workspace: workspace.to_path_buf(),
843 recent,
844 total_workspace_sessions,
845 has_scoped_sessions,
846 recent_expanded: false,
847 composer_focus: true,
848 row_hitboxes: Vec::new(),
849 hovered_row: None,
850 menu_selected: None,
851 dissolve_started_ms: None,
852 mark_reveal_started_at: None,
853 claude_code_detected,
854 whats_new: None,
855 }
856 }
857
858 /// Leave home without resetting the conversation, draft, or reveal clock.
859 pub fn dismiss(&mut self) {
860 self.dissolve_started_ms = None;
861 self.visible = false;
862 self.return_to_session = false;
863 self.row_hitboxes.clear();
864 self.menu_selected = None;
865 self.hovered_row = None;
866 }
867
868 pub(crate) fn leave_for_new_session(&mut self, now_ms: u128, motion_allowed: bool) {
869 let handoff = self.visible && self.dissolve_started_ms.is_none() && motion_allowed;
870 self.dismiss();
871 if handoff {
872 self.dissolve_card(now_ms);
873 }
874 }
875
876 /// Re-read the recent-work list from disk (same filter as
877 /// construction). Called when the card is restored after a picker
878 /// closes so a session created or renamed behind the picker shows up.
879 pub fn refresh_recent(&mut self) {
880 let (recent, total, any_scoped) = load_launch_recent(&self.workspace.clone());
881 self.recent = recent;
882 self.total_workspace_sessions = total;
883 self.has_scoped_sessions = any_scoped;
884 }
885
886 pub fn expand_recent(&mut self) {
887 self.recent_expanded = true;
888 self.menu_selected = None;
889 self.hovered_row = None;
890 }
891
892 /// Begin the card dissolve once (idempotent). The first keystroke or a
893 /// launched command dissolves the launch card.
894 pub fn dissolve_card(&mut self, now_ms: u128) {
895 if self.dissolve_started_ms.is_none() {
896 self.dissolve_started_ms = Some(now_ms);
897 }
898 }
899
900 /// Bring the card back after a launch flow (the sessions picker) is
901 /// left with Esc: every launch path has a way back to the card, so a
902 /// dismissed picker never strands the user on an empty stage. The list
903 /// comes back with nothing highlighted, and the recent-work list is
904 /// re-read so sessions created behind the picker show up.
905 pub fn restore_card(&mut self) {
906 self.dissolve_started_ms = None;
907 self.menu_selected = None;
908 self.hovered_row = None;
909 self.status = None;
910 self.recent_expanded = false;
911 self.refresh_recent();
912 }
913
914 /// True while the card is still painting — visible and not fully
915 /// dissolved. Hitboxes and clicks follow the paint, so a dissolved card
916 /// owns no rows.
917 #[must_use]
918 pub fn card_paintable(&self, now_ms: u128, motion_allowed: bool) -> bool {
919 self.visible && self.card_dissolve_progress(now_ms, motion_allowed) < 1.0
920 }
921
922 pub(crate) fn session_handoff_active(&self, now_ms: u128, motion_allowed: bool) -> bool {
923 !self.visible
924 && self.dissolve_started_ms.is_some()
925 && self.card_dissolve_progress(now_ms, motion_allowed) < 1.0
926 }
927
928 /// How far the card has dissolved, `[0.0 intact ..= 1.0 gone]`. Reduced
929 /// motion dissolves instantly: the same drawing at its endpoint.
930 #[must_use]
931 pub fn card_dissolve_progress(&self, now_ms: u128, motion_allowed: bool) -> f32 {
932 match self.dissolve_started_ms {
933 None => 0.0,
934 Some(_) if !motion_allowed => 1.0,
935 Some(started) => {
936 let elapsed = now_ms.saturating_sub(started);
937 (elapsed as f32 / LAUNCH_CARD_DISSOLVE_MS as f32).clamp(0.0, 1.0)
938 }
939 }
940 }
941 }
942
943 /// Cached @-mention completion results to avoid re-walking the filesystem when
944 /// the cursor moves inside the same mention token.
945 #[derive(Debug, Clone)]
946 pub struct MentionCompletionCache {
947 /// Workspace root used for this completion walk.
948 pub workspace: PathBuf,
949 /// Process cwd captured for cwd-relative completion entries.
950 pub cwd: Option<PathBuf>,
951 /// The partial text after `@` that triggered this completion.
952 pub partial: String,
953 /// Candidate limit used for this completion walk.
954 pub limit: usize,
955 /// Workspace depth limit used for this completion walk. Included so live
956 /// config changes invalidate cached popup results.
957 pub walk_depth: usize,
958 /// Completion behavior used for this walk. Included so live config changes
959 /// invalidate cached popup results.
960 pub behavior: String,
961 /// Whether symlink following was enabled for this completion walk.
962 /// Included so live config changes invalidate cached popup results.
963 pub follow_links: bool,
964 /// Cached completion entries.
965 pub entries: Vec<String>,
966 }
967
968 /// Composer input state — grouped fields for the text input area.
969 pub struct ComposerState {
970 /// Current composer text content.
971 pub input: String,
972 /// Cursor position within `input` (in characters).
973 pub cursor_position: usize,
974 /// Single-entry kill buffer for emacs-style `Ctrl+K` cut / `Ctrl+Y` yank.
975 pub kill_buffer: String,
976 pub paste_burst: PasteBurst,
977 /// When a large paste is consolidated at submit time, the file @mention
978 /// is stored here so it can be appended to the submitted text without
979 /// replacing the visible composer content (#3263).
980 pub(crate) pending_paste_reference: Option<String>,
981 /// When composer content is oversized, the full text is stored here
982 /// while `self.input` shows a truncated preview. At submit time the
983 /// full text is restored for model submission (#3263).
984 pub(crate) oversized_paste_full_text: Option<String>,
985 pub input_history: Vec<String>,
986 pub draft_history: VecDeque<String>,
987 pub clear_undo_buffer: Option<String>,
988 pub history_index: Option<usize>,
989 pub(crate) history_navigation_draft: Option<InputHistoryDraft>,
990 pub composer_history_search: Option<ComposerHistorySearch>,
991 pub selected_attachment_index: Option<usize>,
992 pub slash_menu_selected: usize,
993 pub slash_menu_hidden: bool,
994 pub mention_menu_selected: usize,
995 pub mention_menu_hidden: bool,
996 /// Cached @-mention completions to avoid re-walking the filesystem when
997 /// the cursor moves inside the same mention token.
998 pub mention_completion_cache: Option<MentionCompletionCache>,
999 /// Serialized background discovery and its bounded candidate cache. All
1000 /// filesystem traversal for composer completions lives behind this owner.
1001 pub(crate) mention_discovery: crate::tui::mention_completion::MentionDiscovery,
1002 /// Launch directory captured once so rendering a completion popup never
1003 /// needs to call `getcwd` on the UI thread.
1004 pub(crate) mention_cwd: Option<PathBuf>,
1005 /// Whether vim modal editing is enabled for this composer.
1006 /// Sourced from `Settings::composer_vim_mode` at startup.
1007 pub vim_enabled: bool,
1008 /// Current vim editing mode. Only meaningful when `vim_enabled` is true.
1009 pub vim_mode: VimMode,
1010 /// Pending `d` prefix for the `dd` delete-line operator. Set when the
1011 /// user presses `d` in Normal mode; cleared on the next key (either `d`
1012 /// to complete `dd`, or any other key to cancel).
1013 pub vim_pending_d: bool,
1014 /// When set, the cursor is the active end of a text selection and
1015 /// `selection_anchor` is the fixed end. Both are char-indexed.
1016 /// `None` means no selection is active.
1017 pub selection_anchor: Option<usize>,
1018 /// The first character typed into this composer line was `/` (#5925).
1019 ///
1020 /// A line that began as a command stays a command until Enter: if the
1021 /// leading `/` is gone at submit time and no edit removed it, bytes were
1022 /// lost between the terminal and the composer, and the line must not be
1023 /// re-interpreted as a prose prompt for the model. Composer edits
1024 /// re-derive the claim through
1025 /// [`ComposerState::resync_command_line_claim`]; `clear_input` drops it.
1026 pub(crate) line_began_with_slash: bool,
1027 /// Startup consumed bytes it could not replay, so the shell cannot prove
1028 /// it saw the whole line (#5925). Set once from the startup input
1029 /// receipt; cleared by the first submit it holds.
1030 pub(crate) startup_input_unproven: bool,
1031 }
1032
1033 impl Default for ComposerState {
1034 fn default() -> Self {
1035 Self {
1036 input: String::new(),
1037 cursor_position: 0,
1038 kill_buffer: String::new(),
1039 paste_burst: PasteBurst::default(),
1040 pending_paste_reference: None,
1041 oversized_paste_full_text: None,
1042 input_history: Vec::new(),
1043 draft_history: VecDeque::new(),
1044 clear_undo_buffer: None,
1045 history_index: None,
1046 history_navigation_draft: None,
1047 composer_history_search: None,
1048 selected_attachment_index: None,
1049 slash_menu_selected: 0,
1050 slash_menu_hidden: false,
1051 mention_menu_selected: 0,
1052 mention_menu_hidden: false,
1053 mention_completion_cache: None,
1054 mention_discovery: crate::tui::mention_completion::MentionDiscovery::default(),
1055 mention_cwd: std::env::current_dir().ok(),
1056 vim_enabled: false,
1057 vim_mode: VimMode::Normal,
1058 vim_pending_d: false,
1059 selection_anchor: None,
1060 line_began_with_slash: false,
1061 startup_input_unproven: false,
1062 }
1063 }
1064 }
1065
1066 /// Viewport/scroll state — fields related to transcript scrolling and caching.
1067 pub struct ViewportState {
1068 pub(crate) working_glow_visible: bool,
1069 pub(crate) activity_sweep_visible: bool,
1070 pub(crate) settle_flash_visible: bool,
1071 pub(crate) detected_background: Option<ratatui::style::Color>,
1072 /// Per-draw copy of the owning backend's negotiated capability facts.
1073 /// Unavailable outside a backend draw; never redetect or infer depth.
1074 pub(crate) ocean_caps: Option<codewhale_ratatui::Caps>,
1075 /// Explicit semantic grounds projected by the current transcript painter.
1076 /// Like hitboxes, cleared/rebuilt each frame, never persisted authority.
1077 pub(crate) ocean_semantic_surfaces: Vec<Rect>,
1078 pub transcript_scroll: TranscriptScroll,
1079 pub pending_scroll_delta: i32,
1080 /// Applied inside the next synchronized frame, including resize clears.
1081 pub(crate) pending_terminal_size: Option<ratatui::layout::Size>,
1082 pub mouse_scroll: MouseScrollState,
1083 pub transcript_cache: TranscriptViewCache,
1084 pub transcript_selection: TranscriptSelection,
1085 pub selection_autoscroll: Option<SelectionAutoscroll>,
1086 pub transcript_scrollbar_dragging: bool,
1087 /// Copy transcript drag selections as Markdown source (see
1088 /// `TuiConfig::selection_copy_markdown`). Resolved from config at startup;
1089 /// defaults to on.
1090 pub selection_copy_markdown: bool,
1091 pub last_transcript_area: Option<Rect>,
1092 pub last_composer_area: Option<Rect>,
1093 /// Selectable targets from the latest painted frame. Cleared before every
1094 /// render so resized or hidden controls can never swallow a click.
1095 pub interaction_targets: crate::tui::tideline::InteractionRegistry,
1096 /// Last left-click trace over the composer, for double/triple-click
1097 /// word/line selection (crossterm does not decode click counts).
1098 pub composer_click_trace: Option<crate::tui::mouse_ui::ComposerClickTrace>,
1099 pub transcript_click_trace: Option<crate::tui::mouse_ui::ComposerClickTrace>,
1100 /// Painted band occupied by the active approval or question sheet. Stored
1101 /// so wheel routing can prefer the prompt over side surfaces underneath it.
1102 pub last_prompt_area: Option<Rect>,
1103 /// The workbar's painted rows under the posture bar; a click there opens
1104 /// `/workflows`.
1105 pub last_workbar_area: Option<Rect>,
1106 /// Info-line segment rects (Tideline shell, spec §6), recorded at render so
1107 /// hover and — in a follow-up slice — click routing can hit-test the
1108 /// painted cells. Mirrors the workflow-panel cancel-area storage pattern.
1109 pub last_infoline_hitboxes: Vec<crate::tui::infoline::InfoLineHitbox>,
1110 /// Live plugin CTA row above the composer, plus review/dismiss hitboxes.
1111 pub last_plugin_cta_area: Option<Rect>,
1112 pub last_plugin_cta_review_area: Option<Rect>,
1113 pub last_plugin_cta_dismiss_area: Option<Rect>,
1114 pub last_transcript_top: usize,
1115 pub last_transcript_visible: usize,
1116 pub last_transcript_total: usize,
1117 pub last_transcript_padding_top: usize,
1118 pub jump_to_latest_button_area: Option<Rect>,
1119 /// Painted rect of the pinned user-prompt header above the transcript,
1120 /// when one is shown and mouse capture is on. A left click there jumps
1121 /// the viewport to the message named by `pinned_prompt_message`.
1122 pub pinned_prompt_area: Option<Rect>,
1123 /// Original history index of the user message the pinned header
1124 /// describes; the click target for `pinned_prompt_area`. Stored as a
1125 /// message identity, not a line offset, because line offsets are
1126 /// frame-bound and a rewrite between paint and click would otherwise
1127 /// land the jump on whatever now sits at the stale offset.
1128 pub pinned_prompt_message: Option<usize>,
1129 /// Inner content rect of the composer (excluding border/padding),
1130 /// stored at render time for mouse coordinate mapping.
1131 pub last_composer_content: Option<Rect>,
1132 /// Number of rendered text lines scrolled off the top of the composer,
1133 /// stored at render time for mouse coordinate mapping.
1134 pub last_composer_scroll_offset: usize,
1135 /// Vertical padding above the first text line in the composer,
1136 /// stored at render time for mouse coordinate mapping.
1137 pub last_composer_top_padding: usize,
1138 /// Slash-autocomplete rows painted inside the composer on the latest
1139 /// frame. Cleared and rewritten during `ComposerWidget::render` so a
1140 /// resized or closed menu cannot swallow a click. Index is the entry
1141 /// index into the visible slash menu (same as `slash_menu_selected`).
1142 pub last_slash_menu_hitboxes: RefCell<Vec<(usize, Rect)>>,
1143 }
1144
1145 impl Default for ViewportState {
1146 fn default() -> Self {
1147 Self {
1148 working_glow_visible: false,
1149 activity_sweep_visible: false,
1150 settle_flash_visible: false,
1151 detected_background: None,
1152 ocean_caps: None,
1153 ocean_semantic_surfaces: Vec::new(),
1154 transcript_scroll: TranscriptScroll::to_bottom(),
1155 pending_scroll_delta: 0,
1156 pending_terminal_size: None,
1157 mouse_scroll: MouseScrollState::new(),
1158 transcript_cache: TranscriptViewCache::new(),
1159 transcript_selection: TranscriptSelection::default(),
1160 selection_autoscroll: None,
1161 transcript_scrollbar_dragging: false,
1162 selection_copy_markdown: true,
1163 last_transcript_area: None,
1164 last_composer_area: None,
1165 interaction_targets: crate::tui::tideline::InteractionRegistry::default(),
1166 composer_click_trace: None,
1167 transcript_click_trace: None,
1168 last_prompt_area: None,
1169 last_workbar_area: None,
1170 last_infoline_hitboxes: Vec::new(),
1171 last_plugin_cta_area: None,
1172 last_plugin_cta_review_area: None,
1173 last_plugin_cta_dismiss_area: None,
1174 last_transcript_top: 0,
1175 last_transcript_visible: 0,
1176 last_transcript_total: 0,
1177 last_transcript_padding_top: 0,
1178 jump_to_latest_button_area: None,
1179 pinned_prompt_area: None,
1180 pinned_prompt_message: None,
1181 last_composer_content: None,
1182 last_composer_scroll_offset: 0,
1183 last_composer_top_padding: 0,
1184 last_slash_menu_hitboxes: RefCell::new(Vec::new()),
1185 }
1186 }
1187 }
1188
1189 /// Host-side tracking state for the active thread goal. Mirrors the
1190 /// engine's authoritative `SharedGoalState` snapshot (`GoalUpdated`) so the
1191 /// sidebar, top bar, and system prompt all read one truth.
1192 #[derive(Debug, Clone, Default)]
1193 pub struct HostGoalState {
1194 pub objective: Option<String>,
1195 pub token_budget: Option<u32>,
1196 pub tokens_used: u64,
1197 pub time_used_seconds: u64,
1198 pub continuation_count: u32,
1199 /// Why an unfinished goal is paused. Kept separate from the four-state
1200 /// status so usage, budget, and run-limit stops stay distinguishable.
1201 pub pause_reason: Option<codewhale_engine::tools::goal::GoalPauseReason>,
1202 pub started_at: Option<Instant>,
1203 /// When the goal reached a terminal status (Complete/Blocked).
1204 /// While `None`, elapsed time keeps growing; once set, the sidebar freezes
1205 /// the timer at `finished_at - started_at` so completed goals stop ticking.
1206 pub finished_at: Option<Instant>,
1207 /// Latest progress the model reported for the active goal. Runtime-only
1208 /// display state; never persisted and never treated as verified.
1209 pub progress: Option<codewhale_engine::tools::goal::GoalProgressReport>,
1210 pub status: codewhale_engine::tools::goal::GoalStatus,
1211 }
1212
1213 /// Session cost and token telemetry state.
1214 #[derive(Debug, Clone)]
1215 pub struct SessionState {
1216 pub session_cost: f64,
1217 pub session_cost_cny: f64,
1218 /// Priced estimate accumulated from the in-flight turn's per-step
1219 /// `TurnUsage` receipts, so the cost surfaces move while a long agentic
1220 /// turn is still running. Display-only: cleared at `TurnComplete`, which
1221 /// re-prices the whole turn's cumulative usage authoritatively into
1222 /// `session_cost`. Never persisted.
1223 pub pending_turn_cost: f64,
1224 pub pending_turn_cost_cny: f64,
1225 /// Display-only per-step token deltas for the active turn. These are
1226 /// cleared at `TurnComplete` before authoritative cumulative totals land.
1227 pub pending_turn_total_tokens: u32,
1228 pub pending_turn_input_tokens: u32,
1229 pub pending_turn_output_tokens: u32,
1230 pub pending_turn_cache_hit_tokens: u32,
1231 pub pending_turn_cache_miss_tokens: u32,
1232 pub pending_turn_cache_write_tokens: u32,
1233 pub subagent_cost: f64,
1234 pub subagent_cost_cny: f64,
1235 /// Redacted provider-response identities settled by parent or routed owners.
1236 /// Membership never adds a child amount; parent usage keeps its own pricing.
1237 pub subagent_usage_sources: codewhale_engine::cost_status::OrderedFingerprintSet,
1238 pub pinned_late_usage_sources: HashSet<String>,
1239 pub accounted_usage_sources:
1240 std::collections::BTreeMap<String, codewhale_engine::cost_status::UsageSourceContribution>,
1241 pub displayed_cost_high_water: f64,
1242 pub displayed_cost_high_water_cny: f64,
1243 pub last_prompt_tokens: Option<u32>,
1244 pub last_completion_tokens: Option<u32>,
1245 pub last_prompt_cache_hit_tokens: Option<u32>,
1246 pub last_prompt_cache_miss_tokens: Option<u32>,
1247 pub last_reasoning_replay_tokens: Option<u32>,
1248 pub total_tokens: u32,
1249 pub total_conversation_tokens: u32,
1250 /// Accumulated token breakdown for the session.
1251 pub total_input_tokens: u32,
1252 pub total_cache_hit_tokens: u32,
1253 pub total_cache_miss_tokens: u32,
1254 /// Cache-creation (cache-write) tokens across the session. Tracked as its
1255 /// own class because providers that publish a write premium bill it above
1256 /// the ordinary input rate, so folding it into misses understated spend.
1257 pub total_cache_write_tokens: u32,
1258 pub total_output_tokens: u32,
1259 /// Prompt-cache classes the session's sub-agents and other background
1260 /// routes reported, from their drained cost batches (#6565). The same
1261 /// per-runtime-session scope as the parent's totals above. `None` until a
1262 /// background route reports cache telemetry: absent, never 0%.
1263 pub subagent_cache_hit_tokens: Option<u64>,
1264 pub subagent_cache_miss_tokens: Option<u64>,
1265 pub subagent_cache_write_tokens: Option<u64>,
1266 /// Turns whose route was money-metered and produced an authoritative
1267 /// price. These are exactly the turns inside `session_cost`.
1268 pub cost_priced_turns: u32,
1269 /// Turns whose route was money-metered — or of unknown billing basis — but
1270 /// produced no authoritative price, so they are missing from `session_cost`
1271 /// entirely. `/cost` reports this instead of presenting the subtotal as a
1272 /// complete figure.
1273 pub cost_unpriced_turns: u32,
1274 /// CNY-specific coverage. Most providers publish USD only, so these cannot
1275 /// share the USD counters without falsely calling a mixed-route CNY subtotal
1276 /// complete.
1277 pub cost_cny_priced_turns: u32,
1278 pub cost_cny_unpriced_turns: u32,
1279 /// Stable reason labels for the unpriced turns, in sorted order.
1280 ///
1281 /// `String` rather than `&'static str` because this state round-trips
1282 /// through a saved session: a label read back from disk was written by some
1283 /// build's vocabulary, not necessarily this one's.
1284 pub cost_unpriced_reasons: BTreeSet<String>,
1285 pub cost_cny_unpriced_reasons: BTreeSet<String>,
1286 /// Token classes used on some route this session that carry no published
1287 /// price. Their turns fail closed rather than under-report.
1288 pub cost_unpriced_classes: BTreeSet<String>,
1289 /// Provenance labels of the pricing rows behind the priced turns
1290 /// (`models_dev_bundled`, `provider_live`, `provider_docs`, …).
1291 pub cost_pricing_provenances: BTreeSet<String>,
1292 /// Live-pricing downgrade receipts: a live catalog row that could not be
1293 /// verified for the endpoint that served a turn, so the bundled snapshot was
1294 /// used instead of claiming authoritative live provenance.
1295 pub cost_live_pricing_defects: BTreeSet<String>,
1296 /// Live-pricing defects for which no bundled row could produce a price.
1297 pub cost_live_pricing_unusable_defects: BTreeSet<String>,
1298 /// One redacted receipt per distinct audited route:
1299 /// provider, configured identity, wire model, billing surface, endpoint
1300 /// fingerprint, billing mode, currency. Never a URL, credential, or filesystem path.
1301 pub cost_route_receipts: BTreeSet<String>,
1302 /// True when the restored session has no coverage state at all.
1303 ///
1304 /// Sessions written before coverage was tracked deserialize their new fields
1305 /// from serde defaults, which look exactly like "0 priced, 0 unpriced" — i.e.
1306 /// a complete total covering nothing. That reading is false, so the load path
1307 /// marks the session explicitly unknown and `/cost` says so rather than
1308 /// presenting fabricated completeness, even for an all-zero record (#4318).
1309 pub cost_coverage_unknown_legacy: bool,
1310 pub turn_cache_history: VecDeque<TurnCacheRecord>,
1311 pub last_cache_inspection: Option<PromptInspection>,
1312 pub last_warmup_key: Option<CacheWarmupKey>,
1313 /// Tool catalog from the most recent model request.
1314 ///
1315 /// `/cache inspect` uses this to inspect the same tool schema bytes
1316 /// that were eligible for the provider's prefix cache.
1317 pub last_tool_catalog: Option<Vec<Tool>>,
1318 /// Exact tool field captured at the latest model request seam.
1319 pub last_tool_request_snapshot:
1320 Option<codewhale_engine::tool_inspection::ToolInspectionSnapshot>,
1321 /// API base URL used by the most recent model request or cache warmup.
1322 pub last_base_url: Option<String>,
1323 }
1324
1325 /// Sidebar hover state for mouse tooltip support.
1326 #[derive(Debug, Clone, Default)]
1327 pub struct SidebarHoverState {
1328 /// Rendered sections with their areas and full-text lines.
1329 pub sections: Vec<SidebarHoverSection>,
1330 }
1331
1332 /// Per-row metadata for sidebar detail popovers.
1333 #[derive(Debug, Clone, PartialEq, Eq)]
1334 pub enum SidebarRowAction {
1335 Command(String),
1336 /// Select the persistent Agents panel. This is deliberately a navigation
1337 /// action rather than a modal: the Subagents summary is a group door, so
1338 /// it should reveal the standing register instead of fabricating a detail
1339 /// page for the count itself.
1340 ShowSubagentsPanel,
1341 /// Open the child's bounded, safe status projection. Exact transcript
1342 /// evidence is a separate explicit action (#2889).
1343 OpenAgentDetail {
1344 agent_id: String,
1345 },
1346 /// Open the child's artifact-first exact transcript. This is separate
1347 /// from the safe default details projection (#2889).
1348 OpenAgentTranscript {
1349 agent_id: String,
1350 },
1351 CancelAgent {
1352 agent_id: String,
1353 },
1354 /// Open the Work Graph inspector in the shared pager. Any lifecycle stop
1355 /// action is carried into that inspector instead of consuming row width.
1356 InspectWork {
1357 title: String,
1358 body: String,
1359 stop_action: Option<Box<SidebarRowAction>>,
1360 },
1361 }
1362
1363 /// Per-row metadata for sidebar detail popovers.
1364 #[derive(Debug, Clone, PartialEq, Eq)]
1365 pub struct SidebarHoverRow {
1366 /// Absolute row position in the terminal.
1367 pub row_y: u16,
1368 /// Text shown in the compact sidebar row.
1369 pub display_text: String,
1370 /// Full untruncated text for the popover.
1371 pub full_text: String,
1372 /// Optional additional detail line.
1373 pub detail: Option<String>,
1374 /// Whether the compact row lost information.
1375 pub is_truncated: bool,
1376 /// Slash command to execute when this row is clicked (#3028).
1377 /// `shell_*` job ids route through `/jobs` (e.g. `/jobs cancel
1378 /// shell_abc123`); task-manager ids route through `/task` (e.g.
1379 /// `/task show task_abc123`).
1380 pub click_action: Option<SidebarRowAction>,
1381 /// Optional narrower stop target for rows that show an inline `[x]`.
1382 pub stop_action: Option<SidebarRowAction>,
1383 pub stop_zone_start_col: Option<u16>,
1384 pub stop_zone_end_col: Option<u16>,
1385 }
1386
1387 /// Per-section metadata for sidebar hover detection.
1388 #[derive(Debug, Clone)]
1389 pub struct SidebarHoverSection {
1390 /// Content area within the section (inside border + padding).
1391 pub content_area: Rect,
1392 /// Full original text for each content line rendered.
1393 pub lines: Vec<String>,
1394 /// Per-row metadata for rich hover popovers.
1395 pub rows: Vec<SidebarHoverRow>,
1396 }
1397
1398 impl Default for SessionState {
1399 fn default() -> Self {
1400 Self {
1401 session_cost: 0.0,
1402 session_cost_cny: 0.0,
1403 pending_turn_cost: 0.0,
1404 pending_turn_cost_cny: 0.0,
1405 pending_turn_total_tokens: 0,
1406 pending_turn_input_tokens: 0,
1407 pending_turn_output_tokens: 0,
1408 pending_turn_cache_hit_tokens: 0,
1409 pending_turn_cache_miss_tokens: 0,
1410 pending_turn_cache_write_tokens: 0,
1411 subagent_cost: 0.0,
1412 subagent_cost_cny: 0.0,
1413 subagent_usage_sources: codewhale_engine::cost_status::OrderedFingerprintSet::new(),
1414 pinned_late_usage_sources: HashSet::new(),
1415 accounted_usage_sources: Default::default(),
1416 displayed_cost_high_water: 0.0,
1417 displayed_cost_high_water_cny: 0.0,
1418 last_prompt_tokens: None,
1419 last_completion_tokens: None,
1420 last_prompt_cache_hit_tokens: None,
1421 last_prompt_cache_miss_tokens: None,
1422 last_reasoning_replay_tokens: None,
1423 total_tokens: 0,
1424 total_conversation_tokens: 0,
1425 total_input_tokens: 0,
1426 total_cache_hit_tokens: 0,
1427 total_cache_miss_tokens: 0,
1428 total_cache_write_tokens: 0,
1429 total_output_tokens: 0,
1430 subagent_cache_hit_tokens: None,
1431 subagent_cache_miss_tokens: None,
1432 subagent_cache_write_tokens: None,
1433 cost_priced_turns: 0,
1434 cost_unpriced_turns: 0,
1435 cost_cny_priced_turns: 0,
1436 cost_cny_unpriced_turns: 0,
1437 cost_unpriced_reasons: BTreeSet::new(),
1438 cost_cny_unpriced_reasons: BTreeSet::new(),
1439 cost_unpriced_classes: BTreeSet::new(),
1440 cost_pricing_provenances: BTreeSet::new(),
1441 cost_live_pricing_defects: BTreeSet::new(),
1442 cost_live_pricing_unusable_defects: BTreeSet::new(),
1443 cost_route_receipts: BTreeSet::new(),
1444 cost_coverage_unknown_legacy: false,
1445 turn_cache_history: VecDeque::new(),
1446 last_cache_inspection: None,
1447 last_warmup_key: None,
1448 last_tool_catalog: None,
1449 last_tool_request_snapshot: None,
1450 last_base_url: None,
1451 }
1452 }
1453 }
1454
1455 impl SessionState {
1456 /// Reset the accumulated token breakdown fields to zero.
1457 pub fn reset_token_breakdown(&mut self) {
1458 self.total_input_tokens = 0;
1459 self.total_cache_hit_tokens = 0;
1460 self.total_cache_miss_tokens = 0;
1461 self.total_cache_write_tokens = 0;
1462 self.total_output_tokens = 0;
1463 self.subagent_cache_hit_tokens = None;
1464 self.subagent_cache_miss_tokens = None;
1465 self.subagent_cache_write_tokens = None;
1466 self.clear_pending_turn_usage();
1467 }
1468
1469 /// Add one provider-reported model-call receipt to the display-only
1470 /// in-flight ledger. The cache split mirrors the authoritative
1471 /// `TurnComplete` accounting path.
1472 pub fn accrue_pending_turn_usage(&mut self, usage: &Usage) {
1473 self.pending_turn_total_tokens = self
1474 .pending_turn_total_tokens
1475 .saturating_add(usage.input_tokens.saturating_add(usage.output_tokens));
1476 self.pending_turn_input_tokens = self
1477 .pending_turn_input_tokens
1478 .saturating_add(usage.input_tokens);
1479 self.pending_turn_output_tokens = self
1480 .pending_turn_output_tokens
1481 .saturating_add(usage.output_tokens);
1482 if usage.prompt_cache_hit_tokens.is_some()
1483 || usage.prompt_cache_miss_tokens.is_some()
1484 || usage.prompt_cache_write_tokens.is_some()
1485 {
1486 let classes = codewhale_engine::pricing::token_usage_for_pricing(usage);
1487 self.pending_turn_cache_hit_tokens = self
1488 .pending_turn_cache_hit_tokens
1489 .saturating_add(u32::try_from(classes.cache_read).unwrap_or(u32::MAX));
1490 self.pending_turn_cache_miss_tokens = self
1491 .pending_turn_cache_miss_tokens
1492 .saturating_add(u32::try_from(classes.input).unwrap_or(u32::MAX));
1493 self.pending_turn_cache_write_tokens = self
1494 .pending_turn_cache_write_tokens
1495 .saturating_add(u32::try_from(classes.cache_write).unwrap_or(u32::MAX));
1496 }
1497 }
1498
1499 /// Clear the active turn's display-only token deltas before the
1500 /// authoritative cumulative usage is reconciled.
1501 pub fn clear_pending_turn_usage(&mut self) {
1502 self.pending_turn_total_tokens = 0;
1503 self.pending_turn_input_tokens = 0;
1504 self.pending_turn_output_tokens = 0;
1505 self.pending_turn_cache_hit_tokens = 0;
1506 self.pending_turn_cache_miss_tokens = 0;
1507 self.pending_turn_cache_write_tokens = 0;
1508 }
1509
1510 pub fn displayed_total_tokens(&self) -> u32 {
1511 self.total_tokens
1512 .saturating_add(self.pending_turn_total_tokens)
1513 }
1514
1515 pub fn displayed_total_conversation_tokens(&self) -> u32 {
1516 self.total_conversation_tokens
1517 .saturating_add(self.pending_turn_total_tokens)
1518 }
1519
1520 pub fn displayed_total_input_tokens(&self) -> u32 {
1521 self.total_input_tokens
1522 .saturating_add(self.pending_turn_input_tokens)
1523 }
1524
1525 pub fn displayed_total_output_tokens(&self) -> u32 {
1526 self.total_output_tokens
1527 .saturating_add(self.pending_turn_output_tokens)
1528 }
1529
1530 pub fn displayed_total_cache_hit_tokens(&self) -> u32 {
1531 self.total_cache_hit_tokens
1532 .saturating_add(self.pending_turn_cache_hit_tokens)
1533 }
1534
1535 pub fn displayed_total_cache_miss_tokens(&self) -> u32 {
1536 self.total_cache_miss_tokens
1537 .saturating_add(self.pending_turn_cache_miss_tokens)
1538 }
1539
1540 pub fn displayed_total_cache_write_tokens(&self) -> u32 {
1541 self.total_cache_write_tokens
1542 .saturating_add(self.pending_turn_cache_write_tokens)
1543 }
1544 }
1545
1546 /// Evidence collected during a turn for the post-turn receipt.
1547 #[derive(Debug, Clone)]
1548 pub struct ToolEvidence {
1549 pub tool_name: String,
1550 pub summary: String,
1551 }
1552
1553 pub(crate) struct LocalOllamaProbe {
1554 pub task:
1555 tokio::task::JoinHandle<Option<codewhale_engine::local_ollama::LiveLocalOllamaCatalog>>,
1556 pub requested: bool,
1557 }
1558
1559 #[derive(Debug, Clone)]
1560 pub(crate) struct PendingProviderSwitch {
1561 pub previous_provider: ProviderKind,
1562 pub previous_model: String,
1563 pub previous_model_ids_passthrough: bool,
1564 pub previous_route_limits: Option<RouteLimits>,
1565 pub previous_route_base_url: String,
1566 pub previous_context_window_source: codewhale_engine::route_runtime::ContextWindowSource,
1567 pub previous_context_window: Option<codewhale_engine::route_runtime::ContextWindowResolution>,
1568 pub previous_context_window_override: Option<u32>,
1569 pub previous_config: Config,
1570 pub previous_onboarding: OnboardingState,
1571 pub previous_onboarding_needs_api_key: bool,
1572 pub previous_api_key_env_only: bool,
1573 }
1574
1575 /// Opaque completion returned by a spawned dispatch task. It carries the
1576 /// captured data needed to apply success or rollback on the event loop.
1577 pub type DispatchApplyFn = Box<
1578 dyn FnOnce(
1579 &mut App,
1580 &codewhale_engine::core::engine::EngineHandle,
1581 &codewhale_runtime::config::Config,
1582 ) -> anyhow::Result<()>
1583 + Send,
1584 >;
1585
1586 /// Global UI state for the TUI.
1587 #[allow(clippy::struct_excessive_bools)]
1588 /// A route change made in-session that the user has not yet decided how to
1589 /// save. Route changes are temporary by default; persisting them requires an
1590 /// explicit command (`/fleet save`, `/fleet save-as` or `/model save-default`).
1591 #[derive(Debug, Clone, PartialEq, Eq)]
1592 pub struct PendingRouteSave {
1593 /// Provider identity the session is now on.
1594 pub provider_identity: String,
1595 /// Exact model id the session is now on.
1596 pub model: String,
1597 /// The selected Fleet at change time, when one exists.
1598 pub fleet: Option<(String, codewhale_engine::fleet::store::FleetScope)>,
1599 }
1600
1601 /// Write `provider_identity`/`model` to the user-global config as the route the next
1602 /// launch should open with, and return the line to show the operator.
1603 fn persist_route_as_startup_default(
1604 locale: Locale,
1605 identity: &codewhale_runtime::config::ProviderIdentity,
1606 model: &str,
1607 ) -> String {
1608 let route = format!("{}/{model}", identity.key);
1609 match try_persist_route_as_startup_default(identity, model) {
1610 Ok(()) => tr(locale, MessageId::RouteSaveRememberedDefault).replace("{route}", &route),
1611 Err(err) => tr(locale, MessageId::RouteSaveFailed).replace("{error}", &err.to_string()),
1612 }
1613 }
1614
1615 fn try_persist_route_as_startup_default(
1616 identity: &codewhale_runtime::config::ProviderIdentity,
1617 model: &str,
1618 ) -> anyhow::Result<()> {
1619 let path = codewhale_runtime::config::home_config_path()
1620 .ok_or_else(|| anyhow::anyhow!("Cannot resolve the user-global model configuration."))?;
1621 codewhale_engine::route_preferences::persist_provider_selection(
1622 Some(&path),
1623 identity,
1624 Some(model),
1625 )
1626 .map(|_| ())
1627 }
1628
1629 /// Caller scope captured by a background catalog scan; results never install
1630 /// into a different workspace, plugin snapshot or extension lifetime.
1631 #[derive(Clone)]
1632 pub(crate) struct SkillCacheScope {
1633 pub(crate) epoch: u64,
1634 pub(crate) workspace: std::path::PathBuf,
1635 pub(crate) skills_dir: std::path::PathBuf,
1636 pub(crate) config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>,
1637 pub(crate) plugins: std::sync::Arc<codewhale_plugins::PluginRegistry>,
1638 }
1639
1640 pub(crate) const MAX_QUEUED_MESSAGES: usize = 64;
1641
1642 pub struct App {
1643 pub mode: AppMode,
1644 /// Registered hotbar actions available for future slot config/render layers.
1645 pub hotbar_actions: HotbarActionRegistry,
1646 /// Composer sub-state (input, cursor, history, menus).
1647 pub composer: ComposerState,
1648 /// Viewport sub-state (scroll, cache, selection).
1649 pub viewport: ViewportState,
1650 /// Ocean work-surface state. Kept separate from transcript/sidebar state
1651 /// so the replacement shell can be removed or promoted as one unit.
1652 pub work_surface: crate::tui::work_surface::WorkSurfaceState,
1653 pub pet_watch: crate::tui::pet_watch::PetWatch,
1654 /// Cell-rendered previews of the images attached to this draft. Decoded
1655 /// off-thread; painting only ever reads a ready thumbnail. Boxed so the
1656 /// cache's channels and maps do not grow every `App` on the stack.
1657 pub attachment_preview: Box<crate::tui::image_preview::ThumbnailCache>,
1658 /// Goal sub-state.
1659 pub goal: HostGoalState,
1660 /// Session sub-state (cost, tokens, telemetry).
1661 pub session: SessionState,
1662 /// Active tool restriction from custom slash command frontmatter.
1663 /// `None` means the current turn may use the normal tool set.
1664 pub active_allowed_tools: Option<Vec<String>>,
1665 /// True when the active custom slash command opted into pause/resume.
1666 pub pausable: bool,
1667 /// A route change made in-session awaits an explicit save decision. When
1668 /// set, the next key press opens the route-save prompt unless a modal is
1669 /// already open.
1670 pub pending_route_save: Option<PendingRouteSave>,
1671 /// True after Esc paused a pausable command and before it is resumed or cancelled.
1672 pub paused: bool,
1673 /// Saved custom-command objective while the command is paused.
1674 pub paused_goal_objective: Option<String>,
1675 pub history: Vec<HistoryCell>,
1676 pub history_version: u64,
1677 /// Bumped when destructive reindexing could make a cached Space owner name
1678 /// a different cell before redraw; ordinary streaming revisions preserve it.
1679 pub(crate) transcript_identity_epoch: u64,
1680 /// Per-cell revision counter, kept in lockstep with `history`.
1681 pub history_revisions: Vec<u64>,
1682 /// Cached tool-run grouping for transcript collapse. The detector is
1683 /// keyed by the same mutation generation that invalidates transcript
1684 /// cells, so idle frames do not rescan the full history.
1685 pub(crate) tool_run_cache: ToolRunCache,
1686 /// Monotonic counter used to issue fresh per-cell revisions.
1687 pub next_history_revision: u64,
1688 /// Engine transcript mirror, shared rather than copied per event
1689 /// (#6214 T2). Reads dereference to the `Vec`; mutations go through
1690 /// [`App::api_messages_mut`] and copy-on-write only while an engine
1691 /// snapshot is outstanding.
1692 pub api_messages: Arc<Vec<Message>>,
1693 /// When each `api_messages` entry landed, index-aligned. The persisted
1694 /// journal's `created_at` reads from these stamps, so a save rewrites
1695 /// neither an entry's content nor its time — appends during a turn stay
1696 /// spread across the session's real timeline instead of collapsing to
1697 /// the save instant. Maintained by the `*_api_messages` helpers; a
1698 /// length-mismatched site degrades to save-time stamps, never to a
1699 /// dropped message.
1700 pub api_message_stamps: Vec<DateTime<Utc>>,
1701 /// Why the live window's first message last changed, kept until the next
1702 /// snapshot reports it in `session.window.rerooted`.
1703 pub(crate) window_reroot_cause: Option<&'static str>,
1704 /// Full saved history, including inactive branches. API messages remain
1705 /// the active projection; snapshots reconcile it without rebuilding IDs.
1706 pub session_journal: codewhale_runtime::session_tree::SessionJournal,
1707 /// User-visible assistant text that crossed typed completion boundaries.
1708 /// Receipts are aligned to transcript cells because provider context can
1709 /// be compacted or purged without changing what remains visible.
1710 completed_assistant_outputs: Vec<CompletedAssistantOutputReceipt>,
1711 /// Exact completed Plan text awaiting this session/turn's host answer.
1712 pub(crate) pending_plan_handoff: Option<crate::tui::plan_handoff::PendingPlanHandoff>,
1713 pub(crate) context_token_cache: RefCell<ContextTokenCache>,
1714 /// Typed account-owned browser relay for this exact TUI session.
1715 pub remote_control: codewhale_app_server::remote_control::RemoteControlController,
1716 pub start_remote_control_on_launch: bool,
1717 pub is_loading: bool,
1718 /// One local report edit awaiting the ordinary composer dispatch.
1719 pub(crate) feedback_dispatch: Option<crate::tui::ui::feedback_host::EditReady>,
1720 /// Sender for spawned dispatch tasks to report completion back to the
1721 /// event loop. The closure is called with `&mut App` so the async phase
1722 /// never needs `&mut App` while awaiting network I/O (#4605).
1723 pub dispatch_completion_tx: Option<tokio::sync::mpsc::Sender<DispatchApplyFn>>,
1724 /// True while a spawned dispatch task is in flight (#4605). Set in the
1725 /// sync prepare phase and cleared when the completion closure runs, so a
1726 /// submit after an Esc-cancel (which clears `is_loading`) still queues
1727 /// instead of spawning a second dispatch that could reorder ops.
1728 pub dispatch_in_flight: bool,
1729 /// Cancels the in-flight dispatch task (#6800). Tripped by a local turn
1730 /// cancel or stall recovery so the dispatch fails back to the composer
1731 /// instead of holding `dispatch_in_flight` for its whole bound.
1732 pub dispatch_cancel: Option<tokio_util::sync::CancellationToken>,
1733 pub(crate) preparing_steers: VecDeque<crate::tui::ui::PreparingSteer>,
1734 pub(crate) steer_cancel: tokio_util::sync::CancellationToken,
1735 pub(crate) preview_cancel: tokio_util::sync::CancellationToken,
1736 /// A clipboard read still running off the UI thread.
1737 pub(crate) pending_paste: Option<crate::tui::paste::PendingPaste>,
1738 pub paste_shortcut_press_seen: bool,
1739 /// Whether the once-per-turn provider-wait incident (#3095) has already
1740 /// been logged for the current turn.
1741 pub provider_wait_incident_logged: bool,
1742 /// Ghost-text follow-up suggestion shown in the composer when empty.
1743 /// Generated asynchronously after each completed turn; cleared on new input.
1744 pub prompt_suggestion: Option<String>,
1745 /// Read-only view of the current Config, refreshed by its notification delta owner.
1746 pub notification_settings: codewhale_config::notifications::NotificationsConfig,
1747 /// Monotonic turn counter for stale-suggestion protection. Incremented on
1748 /// each TurnStarted; background suggestion tasks capture the token and
1749 /// discard their result if the token no longer matches.
1750 pub prompt_suggestion_gen: std::sync::atomic::AtomicU64,
1751 /// Queue new submissions while browsing offline or recovering provider setup.
1752 pub offline_mode: bool,
1753 /// Whether an `EngineEvent::Error` has already been posted for the
1754 /// current turn. Suppresses the redundant "Turn failed:" status line
1755 /// that `TurnComplete { error: .. }` would otherwise emit on top of
1756 /// the in-transcript error cell.
1757 pub turn_error_posted: bool,
1758 /// Text of the error cell posted for the current turn, when
1759 /// `turn_error_posted`. A turn that then ends `Failed` persists exactly
1760 /// this text, so resume shows what the live transcript showed.
1761 pub(crate) turn_error_notice: Option<String>,
1762 pub(crate) turn_error_cause: Option<codewhale_engine::llm_error_envelope::ProviderFailureCause>,
1763 /// Recent status toasts (ephemeral, newest at back).
1764 pub status_toasts: VecDeque<StatusToast>,
1765 /// Metrics-line label (e.g. `↑ v0.9.5`) set once by the fire-and-forget
1766 /// startup version check when a newer stable release exists. Drives the
1767 /// persistent update notice so the affordance survives
1768 /// the transient toast without nagging (FINISH-0.9.4 #14).
1769 pub update_available: Option<String>,
1770 /// Sticky status toast used for important warnings/errors.
1771 pub sticky_status: Option<StatusToast>,
1772 /// Prevents the same pressure condition from immediately re-arming after
1773 /// the operator explicitly dismisses its sticky warning. Reset when the
1774 /// pressure falls below the warning threshold or compaction starts.
1775 pub context_pressure_warning_dismissed:
1776 Option<codewhale_runtime::context_budget::PressureLevel>,
1777 /// Last on-disk plugin catalog stamp we already nudged `/plugin reload` for.
1778 pub plugin_reload_nudge_stamp: Option<codewhale_plugins::PluginCatalogStamp>,
1779 /// Last idle catalog fingerprint poll, so disk changes can surface between turns.
1780 pub last_plugin_catalog_poll: Option<Instant>,
1781 pub mcp_config_watch: Option<crate::tui::plugin_suggestions::McpConfigWatch>,
1782 /// Live composer plugin CTA (debounce + one match, never auto-install).
1783 pub plugin_cta: crate::tui::plugin_suggestions::PluginCtaState,
1784 pub model: String,
1785 /// Persisted model selections by provider name. Loaded from settings so
1786 /// `/model` and the picker can surface saved provider-specific choices.
1787 pub provider_models: HashMap<String, String>,
1788 /// Which routes this person actually used recently (#6533): built from
1789 /// saved sessions off the UI thread at startup, bumped on route switches.
1790 /// The `/model` picker's default view ranks by it.
1791 pub route_usage: codewhale_engine::model_relevance::SharedRouteUsage,
1792 /// Non-secret declarations from the loaded config snapshot. Completion
1793 /// reads this snapshot without reloading credentials on each keystroke.
1794 pub configured_models: Vec<codewhale_config::catalog::configured::ConfiguredModel>,
1795 /// Exact provider/model pins loaded from settings, in user order.
1796 pub pinned_models: Vec<codewhale_runtime::settings::PinnedModel>,
1797 /// When true, the model is auto-selected rather than using a fixed
1798 /// model. The `/model auto` command sets this. The flash classifier
1799 /// picks the per-turn model when available; otherwise the configured
1800 /// default model is used (no request-content signal).
1801 pub auto_model: bool,
1802 /// Last concrete model chosen while `auto_model` is active.
1803 pub last_effective_model: Option<String>,
1804 pub(crate) last_effective_budget: Option<AutoRouteBudget>,
1805 /// Provider that actually served the latest auto-routed turn.
1806 pub last_effective_provider: Option<ProviderKind>,
1807 /// Exact non-secret identity for the provider that served the latest Auto
1808 /// turn. This matters for named custom providers, which all share the
1809 /// `ProviderKind::Custom` enum variant.
1810 pub(crate) last_effective_provider_identity: Option<String>,
1811 /// Auto decision metadata for the most recently resolved Auto turn.
1812 pub(crate) last_auto_route_receipt: Option<codewhale_engine::model_routing::AutoRouteReceipt>,
1813 /// Route selected for the next turn, retained for in-flight UI details
1814 /// until the engine confirms the authoritative `TurnStarted` route.
1815 pub pending_turn_route: Option<(ProviderKind, String, bool)>,
1816 /// Auto decision metadata waiting to be paired with `pending_turn_route`.
1817 pub(crate) pending_auto_route_receipt:
1818 Option<codewhale_engine::model_routing::AutoRouteReceipt>,
1819 /// Authoritative lifecycle metadata attached to the most recent
1820 /// `TurnStarted`. Kept separate from `pending_turn_route` so a preceding
1821 /// compaction completion cannot consume the next model turn's route.
1822 pub active_turn: Option<ActiveTurnMetadata>,
1823 /// Current API provider (mirrors `Config::api_provider`).
1824 /// Updated by `/provider` switches so the UI/commands can read the
1825 /// active backend without re-deriving it from the live config.
1826 pub api_provider: ProviderKind,
1827 /// The resolved startup config named a provider or model. Capture this
1828 /// before runtime synchronization writes even the built-in route to Config;
1829 /// missing credentials must not make that choice eligible for discovery.
1830 pub(crate) startup_route_configured: bool,
1831 /// Exact configured provider key for persistence and route restoration.
1832 /// Built-ins use their canonical slug; named custom providers retain the
1833 /// user-owned key instead of collapsing to `custom`.
1834 pub(crate) provider_identity: Option<codewhale_runtime::config::ProviderIdentity>,
1835 /// Primary provider plus configured fallback providers for this session.
1836 pub provider_chain: Option<ProviderChain>,
1837 /// Per-provider auth/local readiness snapshot for the fallback chain (#2574).
1838 ///
1839 /// Captured at startup alongside `provider_chain` (where the live `Config` is
1840 /// in scope). `advance_fallback` consults it to skip chain entries that
1841 /// cannot serve a turn — hosted providers missing a key — while local
1842 /// providers (Ollama/vLLM/SGLang) are always ready. Stored as `(provider,
1843 /// ready)` pairs; lookups fall back to "ready" for providers not present so
1844 /// an unknown entry is tried rather than silently skipped.
1845 provider_readiness: Vec<(codewhale_runtime::config::ProviderIdentity, bool)>,
1846 /// Session-local evidence from real provider requests and verification
1847 /// probes. Unlike `provider_readiness` above, this never treats a saved key
1848 /// as proof that the endpoint is healthy.
1849 pub(crate) provider_health: codewhale_engine::provider_readiness::ProviderReadinessSnapshot,
1850 /// Human-readable description of the last provider fallback event.
1851 pub last_fallback_reason: Option<String>,
1852 /// True when the active provider/base URL accepts arbitrary model IDs
1853 /// verbatim rather than DeepSeek-only aliases.
1854 pub model_ids_passthrough: bool,
1855 /// Resolved provider/model route limits for the active runtime route.
1856 pub active_route_limits: Option<RouteLimits>,
1857 /// Exact resolved endpoint for the active runtime route. This stays
1858 /// separate from persisted config so endpoint-sensitive compatibility
1859 /// (notably Kimi Code's bare `k3`) is never inferred from a provider name
1860 /// alone.
1861 pub active_route_base_url: String,
1862 /// Provenance for `active_route_limits`' effective context window. This
1863 /// is an operator-facing receipt, not a claim about provider billing.
1864 pub active_context_window_source: codewhale_engine::route_runtime::ContextWindowSource,
1865 pub(crate) active_context_window:
1866 Option<codewhale_engine::route_runtime::ContextWindowResolution>,
1867 /// User-configured provider context-window override for the active route.
1868 pub active_context_window_override: Option<u32>,
1869 /// `[providers.<id>.model_context_windows]` for the active provider
1870 /// identity, keyed by exact wire model id (#6108). A hit wins over
1871 /// `active_context_window_override` for that model only.
1872 pub active_model_context_windows: Option<std::collections::BTreeMap<String, u32>>,
1873 /// Pending provider transition for transactional rollback when the next
1874 /// auth failure indicates the new provider cannot be used.
1875 pub pending_provider_switch: Option<PendingProviderSwitch>,
1876 /// Current live reasoning-effort selection. Route changes may normalize
1877 /// this value; the raw user choice remains in
1878 /// [`Self::reasoning_effort_preference`].
1879 pub reasoning_effort: ReasoningEffort,
1880 /// Raw explicit user preference, before any fixed provider/model route
1881 /// normalizes it. `None` means the current live tier is an implicit route
1882 /// default or compatibility inference and must not constrain Auto routing.
1883 pub(crate) reasoning_effort_preference: Option<ReasoningEffort>,
1884 /// Last effective thinking receipt for the most recently accepted route.
1885 pub(crate) last_effective_reasoning_effort: Option<EffectiveReasoningEffort>,
1886 pub workspace: PathBuf,
1887 /// Effective `[workflow]` table for this session (`/workflow settings`).
1888 pub workflow_config: codewhale_config::WorkflowConfigToml,
1889 /// Effective `[goal] max_continuations` backstop; `0` means unlimited.
1890 pub goal_max_continuations: u32,
1891 /// Effective `[goal] enforce_token_budget`; `true` makes a goal's token
1892 /// budget a hard stop instead of advisory telemetry (#6013).
1893 pub goal_enforce_token_budget: bool,
1894 /// Typed engine lifecycle state for the cancellable between-turn wait.
1895 pub goal_continuation_waiting: bool,
1896 /// Effective explicit/managed filesystem scope captured at startup. The
1897 /// named permission posture supplies the default when this is `None`.
1898 pub configured_sandbox_mode: Option<String>,
1899 /// Configured `sandbox_network_access`. `None`/`Some(false)` keep the
1900 /// workspace-write sandbox network-restricted.
1901 pub configured_sandbox_network: Option<bool>,
1902 /// The sandbox backend this platform+config can actually enforce with,
1903 /// resolved once at startup. `None` means there is NO enforcement
1904 /// available (Linux with `prefer_bwrap = false` or no working bwrap, and
1905 /// all Windows), so surfaces must not claim the session is sandboxed
1906 /// (2026-08-04 audit).
1907 pub sandbox_backend: Option<codewhale_sandbox::SandboxType>,
1908 /// Off-event-loop worker for durable Lane control writes. `/lane interrupt`
1909 /// submits here instead of tearing down a Runtime on the composer thread
1910 /// (#4022).
1911 pub lane_control: codewhale_runtime::lane_control::LaneControlQueue,
1912 /// Immutable plugin catalogue scoped to this App's effective workspace.
1913 pub plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>,
1914 pub config_path: Option<PathBuf>,
1915 pub config_profile: Option<String>,
1916 /// Legacy executable plugin-tool directory resolved from the already
1917 /// loaded configuration. Slash-command inventory must not reload the full
1918 /// config (and thereby re-read credential-bearing fields) merely to find
1919 /// this path.
1920 pub legacy_plugin_tools_dir: Option<PathBuf>,
1921 pub mcp_config_path: PathBuf,
1922 pub skills_dir: PathBuf,
1923 pub skills_config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>,
1924 /// Whether the optional project context pack was enabled when this
1925 /// session loaded its configuration. Context diagnostics consult this
1926 /// source of truth even before the first system prompt is assembled.
1927 pub project_context_pack_enabled: bool,
1928 /// Path to the user-memory file (#489). Always populated; only
1929 /// consulted when `use_memory` is `true`.
1930 pub memory_path: PathBuf,
1931 /// Whether the user-memory feature is enabled (#489). Mirrors
1932 /// `Config::memory_enabled()` at app boot. Used by the `# foo`
1933 /// composer interception,
1934 /// the `/memory` slash command, and tool registration for
1935 /// `remember`.
1936 pub use_memory: bool,
1937 pub use_mouse_capture: bool,
1938 /// When true, plain Up/Down on an empty composer scroll the transcript
1939 /// instead of navigating input history. Defaults to `true` when mouse
1940 /// capture is off: terminals that convert mouse-wheel events to arrow-key
1941 /// sequences (e.g. Windows CMD without `WT_SESSION`) get page-scrolling
1942 /// without any explicit config (#1443).
1943 pub composer_arrows_scroll: bool,
1944 /// Data-side cap for the `@`-mention popup. The renderer still limits the
1945 /// visible rows to available terminal height.
1946 pub mention_menu_limit: usize,
1947 /// Maximum workspace depth for `@`-mention completion walks. `0` means
1948 /// unlimited depth.
1949 pub mention_walk_depth: usize,
1950 /// `@`-mention completion behavior: fuzzy workspace search or deterministic
1951 /// directory browser.
1952 pub mention_menu_behavior: String,
1953 /// Follow symbolic links during workspace file discovery walks.
1954 /// When `true`, symlinked directories are traversed, enabling
1955 /// multi-project workspaces.
1956 pub workspace_follow_symlinks: bool,
1957 pub use_bracketed_paste: bool,
1958 pub use_paste_burst_detection: bool,
1959 /// Set to `true` the first time a real `Event::Paste` arrives during a
1960 /// session. Once set, `handle_paste_burst_key` short-circuits — there's
1961 /// no point running the rapid-keypress heuristic on a terminal that
1962 /// already delivers paste-as-event correctly. Avoids paste-burst false
1963 /// positives on Ghostty / iTerm2 / WezTerm / Windows Terminal where
1964 /// fast typing or IME commits could otherwise be mis-classified as a
1965 /// paste burst (#1322 follow-up).
1966 pub bracketed_paste_seen: bool,
1967 /// A non-Windows terminal on the verified `Event::Paste` allowlist may
1968 /// skip the rapid-keystroke heuristic from the first keystroke. Windows
1969 /// input requires `bracketed_paste_seen`: a terminal name or WT_SESSION
1970 /// does not prove that the input backend delivers paste events (#6427).
1971 /// Resolved once at startup, so tests and headless runs stay hermetic.
1972 pub bracketed_paste_trusted: bool,
1973 pub system_prompt: Option<SystemPrompt>,
1974 pub instruction_assembly:
1975 Option<std::sync::Arc<codewhale_engine::project_context::InstructionAssembly>>,
1976 pub auto_compact: bool,
1977 pub auto_compact_user_configured: bool,
1978 pub auto_compact_threshold_percent: f64,
1979 /// `[compaction] summary_instructions` resolved at startup (#5956): the
1980 /// standing operator suffix appended to every summarizer prompt, manual
1981 /// and automatic.
1982 pub compaction_summary_instructions: Option<String>,
1983 /// `[compaction] retained_user_message_tokens` resolved and clamped at
1984 /// startup (#5956).
1985 pub compaction_retained_user_message_tokens: usize,
1986 pub stopped_turn: bool,
1987 pub calm_mode: bool,
1988 pub low_motion: bool,
1989 pub constrained_frame_rate: bool,
1990 /// The ambient animation clock, in clamped milliseconds. Creature and
1991 /// water positions are pure functions of this value; advancing it by at
1992 /// most [`App::AMBIENT_MAX_STEP_MS`] per sampled frame keeps motion
1993 /// continuous when draws arrive in bursts (fast token streams previously
1994 /// sampled raw wall-clock time at irregular gaps, so fish "teleported"
1995 /// between frames — captains-log #16).
1996 pub ambient_clock_ms: u128,
1997 /// When the ambient clock last advanced; `None` until the first sample.
1998 pub ambient_clock_sampled_at: Option<Instant>,
1999 /// When the shell last became fully idle (no turn, no live sub-agents,
2000 /// no active durable tasks, completion exhale finished). After a short
2001 /// grace of gentle motion the aquarium settles to a genuinely still
2002 /// scene instead of repainting an idle screen forever.
2003 pub ambient_idle_since: Option<Instant>,
2004 pub ambient_life_held_ms: Option<u128>,
2005 /// Start of the underwater shell's one-shot successful-turn exhale.
2006 /// Kept separate from the ambient ocean clock so completion can settle
2007 /// once without restarting or repainting the transcript field.
2008 pub ocean_completion_started_at: Option<Instant>,
2009 /// History length at the current turn boundary. Successful completion
2010 /// uses this stable index to settle only the receipts produced by that
2011 /// turn, never old transcript rows.
2012 pub ocean_turn_history_start: usize,
2013 /// First committed history cell participating in the current one-shot
2014 /// receipt-settle cascade.
2015 pub ocean_receipt_settle_start: Option<usize>,
2016 /// Enables the authored underwater phase and ambient motion system.
2017 pub fancy_animations: bool,
2018 /// Typed appearance treatment; appearance is independent from motion
2019 /// settings, and every underwater treatment keeps ambient life.
2020 /// Focus-context texture prototype mode (#4823), parsed once from the
2021 /// `focus_texture` setting. `Off` by default; while off the modal render
2022 /// path is byte-identical to the pre-prototype path.
2023 pub focus_texture: crate::tui::focus_texture::FocusTextureMode,
2024 /// Distinct pre-session menu. Once dismissed, the normal idle ocean owns
2025 /// the empty session and this state stays hidden.
2026 pub launch: LaunchState,
2027 /// Mouse-selected launch action, consumed by the async UI loop.
2028 pub pending_launch_action: Option<crate::tui::underwater::LaunchAction>,
2029 /// Mouse click on the live composer's `[↵]` send target. The async UI loop
2030 /// consumes it through the same submit dispatcher as Enter.
2031 pub pending_composer_submit: Option<ComposerSubmitChord>,
2032 /// Mouse-selected hotbar slot, consumed by the async UI loop.
2033 pub pending_hotbar_slot: Option<u8>,
2034 /// Whether the renderer should wrap each frame in DEC mode 2026
2035 /// synchronized output. Resolved from `Settings::synchronized_output`
2036 /// at construction; `auto`/`on` → `true`, `off` → `false`. The Ptyxis
2037 /// auto-detect path in `Settings::apply_env_overrides` flips `auto`
2038 /// to `off` before App is built, so by the time we read this flag in
2039 /// the draw loop the decision is already made. See the
2040 /// `Settings::synchronized_output` doc for the user-facing knob.
2041 pub synchronized_output_enabled: bool,
2042 /// Header status-indicator chip mode. `"cw"` is the static default;
2043 /// `"whale"` and `"dots"` preserve the animated legacy choices, while
2044 /// `"off"` hides the chip. Loaded from settings and changed via
2045 /// `/config status_indicator <cw|whale|dots|off>`.
2046 pub status_indicator: String,
2047 pub show_thinking: bool,
2048 pub thinking_highlight: bool,
2049 pub thinking_default_expanded: bool,
2050 pub thinking_preview_lines: usize,
2051 pub help_expand_groups: bool,
2052 pub pin_last_prompt: bool,
2053 pub verbose_transcript: bool,
2054 pub show_tool_details: bool,
2055 /// Inline presentation mode for successful structured File mutations.
2056 /// Exact evidence remains attached to each mutation receipt in all modes.
2057 pub inline_diff_mode: InlineDiffMode,
2058 pub ui_locale: Locale,
2059 pub constitution_reviewed_digest: Option<String>,
2060 pub cost_currency: CostCurrency,
2061 /// Route payment truth. Model pricing alone cannot distinguish metered
2062 /// API calls from OAuth or token-plan quota.
2063 pub billing_presentation: codewhale_engine::route_billing::BillingPresentation,
2064 pub composer_density: ComposerDensity,
2065 pub composer_border: bool,
2066 pub composer_multiline_mode: bool,
2067 /// Voice input state — toggled by `/voice` and the voice hotbar action.
2068 pub voice_enabled: bool,
2069 /// Auto-send after transcription when the transcript ends with an
2070 /// explicit send instruction ("send it" / "发送"). Toggled by `/voice-send`.
2071 pub voice_send_enabled: bool,
2072 /// AI-assisted dictation that sees the current composer text.
2073 /// Toggled by `/voice-control`.
2074 pub voice_control_enabled: bool,
2075 pub transcript_spacing: TranscriptSpacing,
2076 /// Prose wrap cap from `[transcript] prose_measure` (#5436). `None`
2077 /// means prose uses the full content width, like tool/status cells.
2078 pub(crate) prose_measure: Option<u16>,
2079 /// Sidebar hover state for mouse tooltip support.
2080 pub sidebar_hover: SidebarHoverState,
2081 /// Current hover tooltip text, if any.
2082 pub sidebar_hover_tooltip: Option<String>,
2083 /// Last successfully rendered Work panel summary. Transient mutex misses
2084 /// Browsing context from the last dismissed `/model` picker, so reopening
2085 /// restores the view mode and highlighted row instead of resetting to the
2086 /// top (#4109 picker memory). Session-scoped, never persisted.
2087 pub model_picker_memory: Option<ModelPickerMemory>,
2088 pub external_agents: Vec<codewhale_app_server::runtime_api::ExternalAgentDiscoveryRow>,
2089 pub external_agents_rx: Option<
2090 tokio::sync::oneshot::Receiver<
2091 Vec<codewhale_app_server::runtime_api::ExternalAgentDiscoveryRow>,
2092 >,
2093 >,
2094 pub external_agent: Option<crate::tui::external_agent::ExternalAgentSession>,
2095 /// Browsing context from the last dismissed `/provider` picker.
2096 pub provider_picker_memory: Option<ProviderPickerMemory>,
2097 /// Last known mouse position for tooltip placement.
2098 pub last_mouse_pos: Option<(u16, u16)>,
2099 /// Whether the session-context panel is enabled (#504).
2100 pub context_panel: bool,
2101 /// Whether the persistent Sessions rail is enabled (#2934). Opt-in.
2102 pub sessions_rail: bool,
2103 /// Minimum number of consecutive safe tool cells needed for auto-collapse.
2104 ///
2105 /// Fixed at 3 for v0.9.x (#3256 decision): not a user setting. Rollups need
2106 /// enough cells to be readable; exposing a knob without UX for partial
2107 /// runs would just recreate the pre-collapse noise floor.
2108 pub tool_collapse_threshold: usize,
2109 /// Tool runs the user explicitly expanded. Stores original history indices.
2110 pub expanded_tool_runs: HashSet<usize>,
2111 pub turn_work_durations: HashMap<usize, Duration>,
2112 pub turn_durations_revision: u64,
2113 pub active_turn_user_index: Option<usize>,
2114 /// Current dense tool-run collapse behavior.
2115 pub tool_collapse_mode: ToolCollapseMode,
2116 /// File-tree pane state. `None` when hidden; `Some` when visible.
2117 pub file_tree: Option<crate::tui::file_tree::FileTreeState>,
2118 /// Whether the file-tree pane was actually rendered in the last frame.
2119 /// Set false when the terminal is too narrow to show the tree.
2120 pub file_tree_visible: bool,
2121 pub compact_threshold: usize,
2122 pub max_input_history: usize,
2123 pub allow_shell: bool,
2124 pub verbosity: Option<String>,
2125 pub max_subagents: usize,
2126 /// Per-SSE-chunk idle timeout for streamed turns, in seconds.
2127 pub stream_chunk_timeout_secs: u64,
2128 /// Cached sub-agent snapshots for UI views.
2129 pub subagent_cache: Vec<SubAgentResult>,
2130 /// First time this TUI observed each terminal sub-agent card.
2131 pub subagent_terminal_seen_at: HashMap<String, Instant>,
2132 /// Last known per-agent progress text for running sub-agents.
2133 pub agent_progress: HashMap<String, String>,
2134 /// Parent/depth metadata for live progress-only sub-agent rows.
2135 pub agent_progress_meta: HashMap<String, AgentProgressMeta>,
2136 pub delegated_writes:
2137 std::collections::BTreeMap<(String, u64), std::collections::BTreeSet<String>>,
2138 /// In-transcript sub-agent card index by `agent_id` (issue #128).
2139 /// Maps each live sub-agent to the `HistoryCell::SubAgent` it renders
2140 /// into, so successive mailbox envelopes mutate the same cell rather
2141 /// than spawning duplicates.
2142 pub subagent_card_index: HashMap<String, usize>,
2143 /// History index of the most recent FanoutCard. Sibling sub-agents
2144 /// spawned by the same `rlm` invocation route into this card; reset
2145 /// when a fresh fanout-family tool call starts.
2146 pub last_fanout_card_index: Option<usize>,
2147 /// Most recently observed sub-agent dispatch tool name (set on
2148 /// `ToolCallStarted` for `agent` / `rlm` / etc., cleared
2149 /// after the first `Started` mailbox envelope routes through it).
2150 pub pending_subagent_dispatch: Option<String>,
2151 /// Animation anchor for status-strip active sub-agent spinner.
2152 pub agent_activity_started_at: Option<Instant>,
2153 /// Monotonic counter for stable agent labels (#3030).
2154 /// Incremented each time a sub-agent is spawned; used to generate
2155 /// "Agent 1", "Agent 2", etc.
2156 pub agent_counter: u64,
2157 /// Maps raw agent_id to a stable user-facing label (#3030).
2158 /// Populated when `AgentSpawned` fires; read by sidebar rendering.
2159 pub agent_label_map: HashMap<String, String>,
2160 /// Background work (agents, shells, durable tasks) that finished since
2161 /// the last notice, named the way every surface names it. Drained by one
2162 /// batched notice (#6565).
2163 pub background_finished: Vec<crate::tui::background_finished::FinishedWork>,
2164 /// Background shells by owning session, oldest first, capped per session
2165 /// at [`crate::tui::background_finished::MAX_FINISHED_SHELLS`]. They stay listed, muted, so
2166 /// a person can see what ran and how it ended (#6565).
2167 pub finished_shell_ids: HashMap<String, VecDeque<String>>,
2168 /// Completion deduplication is independent of visible rows and their cap.
2169 /// IDs are manager-unique; these sets live only for this TUI process.
2170 pub notified_shell_ids: HashSet<String>,
2171 pub notified_task_ids: HashSet<String>,
2172 /// When the latest `AgentList` snapshot arrived, so a running agent's
2173 /// engine idle clock keeps counting between snapshots.
2174 pub subagent_cache_received_at: Option<Instant>,
2175 /// The child whose full transcript currently owns the main conversation
2176 /// area and whose fork the composer addresses (`None` = main session).
2177 pub agent_focus: Option<crate::tui::agent_focus::AgentFocus>,
2178 /// Follow-ups a running child has not yet taken at its next round
2179 /// boundary (`agent_id` → count), from the latest `AgentList` refresh.
2180 pub agent_queued_follow_ups: HashMap<String, usize>,
2181 /// Receipts-only roster of every agent that ran this session (#5479).
2182 /// Updated incrementally from session-scoped agent lifecycle events and
2183 /// reconciled by `AgentList`; shared by `/agents`, the Agents register
2184 /// and the Price view.
2185 pub agent_roster: Vec<codewhale_engine::agent_roster::AgentRosterRow>,
2186 /// Original conversation owner of the retained snapshot. A process boot
2187 /// marker or a worker's parent run is not a conversation identity.
2188 pub agent_roster_session_id: Option<String>,
2189 /// `/agents list` asked for a one-shot transcript listing. Cleared by the
2190 /// `AgentList` handler that prints it.
2191 pub agent_roster_print_requested: bool,
2192 /// Last time a sub-agent progress event triggered a redraw.
2193 /// Used to throttle redraws under high sub-agent concurrency (#3033).
2194 pub last_agent_progress_redraw: Option<Instant>,
2195 pub ui_theme: UiTheme,
2196 /// Parsed `background_color` setting, kept separately from `ui_theme` so
2197 /// an explicit override remains distinguishable even when it happens to
2198 /// equal the current named theme's default surface and can still carry
2199 /// into previews of other themes.
2200 pub background_color_override: Option<Color>,
2201 /// Active named theme. Drives the cell-level color remap in
2202 /// `tui::color_compat::ColorCompatBackend` so community presets
2203 /// (Catppuccin, Tokyo Night, Dracula, Gruvbox) propagate to every
2204 /// render site, not just the handful that read `app.ui_theme`.
2205 pub theme_id: palette::ThemeId,
2206 /// Normalized persisted selector, including `custom:<name>` overlays.
2207 /// `theme_id` remains the resolved base theme for behavior such as the
2208 /// underwater surface and color-compatibility backend.
2209 pub theme_name: String,
2210 // Onboarding
2211 pub onboarding: OnboardingState,
2212 /// True while the startup gate for `[redaction] model_bound = "disabled"`
2213 /// owns the screen. The gate renders above every other surface and must
2214 /// be answered (confirm / keep / quit) before any session starts; see
2215 /// `tui::redaction_gate`.
2216 pub redaction_gate: bool,
2217 /// True while the gate shows its second, final-confirmation stage: the
2218 /// user already pressed 1/Y on the first stage and must confirm once more
2219 /// before the opt-out actually takes effect.
2220 pub redaction_gate_confirming: bool,
2221 /// Viewport position for the consent text; clamped by the gate renderer.
2222 pub redaction_gate_scroll: std::cell::Cell<usize>,
2223 pub onboarding_needs_api_key: bool,
2224 pub onboarding_provider: ProviderKind,
2225 pub onboarding_workspace_trust_gate: bool,
2226 /// True when onboarding opened only because a returning user's configured
2227 /// provider is missing its key. Esc then exits to the offline composer
2228 /// instead of walking back through first-run steps.
2229 pub onboarding_missing_key_recovery: bool,
2230 /// Why provider setup reopened after the provider refused the active
2231 /// key. The setup screen covers the transcript, so it shows this until
2232 /// the user leaves or completes setup.
2233 pub(crate) onboarding_key_rejected: Option<String>,
2234 /// True when the user explicitly chose "Explore offline" during onboarding
2235 /// (#3927). No provider was selected, no route was activated, and no secret
2236 /// was saved: the session browses with queued input until a route is
2237 /// activated later (`/provider`), which is the only thing that clears it.
2238 pub onboarding_explore_offline: bool,
2239 /// First-run route receipts: which required decisions this run contains.
2240 /// The surface title counts only these ("1 of 2"), never a fixed spine.
2241 pub onboarding_had_language_step: bool,
2242 pub onboarding_had_provider_step: bool,
2243 pub onboarding_had_trust_step: bool,
2244 pub local_runtime_detected: bool,
2245 pub(crate) local_ollama_probe: Option<LocalOllamaProbe>,
2246 /// True when the active credential was discovered only through an
2247 /// environment variable. Missing-key recovery and route rollback use this
2248 /// provenance to decide whether a durable provider slot still exists;
2249 /// credential drafts live exclusively inside `ProviderPickerView`.
2250 pub api_key_env_only: bool,
2251 // Hooks system
2252 pub hooks: HookExecutor,
2253 /// Lifecycle event outbox (`[lifecycle_outbox]` config). Disabled
2254 /// (all emits no-ops) when no path is configured.
2255 pub lifecycle_outbox: codewhale_hooks::LifecycleOutbox,
2256 pub yolo: bool,
2257 /// One-shot YOLO→Act+Bypass migration notice for this session (#0.8.68 M6).
2258 yolo_compat_notified: bool,
2259 permission_receipt_deferred: bool,
2260 /// One-shot notice for a settings file that still names the retired
2261 /// Operate mode, so the mode change is explained instead of silent.
2262 operate_retired_notified: bool,
2263 /// The single serialized owner of `settings.toml` startup-default writes
2264 /// (mode, thinking, model). Keeping one owner per `App` is what stops two
2265 /// rapid selections from interleaving their load/modify/save transactions
2266 /// and losing the newer one. Failures are drained by the event loop into a
2267 /// warning toast, so a settings write that did not land is never silently
2268 /// reverted on the next launch.
2269 pub startup_defaults: crate::tui::startup_defaults::StartupDefaultsWriter,
2270 /// One-shot Shift+Tab/Ctrl+T rebinding notice for this session (#0.8.68 M3).
2271 keybinding_migration_notified: bool,
2272 /// Durable Agent-era permission baseline that Plan/YOLO derive from and
2273 /// restore to (#3386). Refreshed from the live fields whenever the user
2274 /// leaves Agent mode; see [`base_policy_for_mode`] and `set_mode`.
2275 mode_prefs: ModeSessionPrefs,
2276 /// True when config/requirements supplied an approval policy. In that
2277 /// case the TUI-only Shift+Tab preference must not loosen it.
2278 approval_policy_locked: bool,
2279 /// True only when the controlling policy is the user's editable root
2280 /// config.toml key. An explicit Shift+Tab may migrate that key to the
2281 /// durable TUI posture; higher-precedence sources remain immutable.
2282 approval_policy_root_editable: bool,
2283 /// True only when an organization requirements file owns approval policy.
2284 /// Unlike a user-owned config key, this source cannot be edited in-app.
2285 approval_policy_requirements_managed: bool,
2286 pub auto_review_disabled: bool,
2287 pub auto_review_reviewer_model: Option<String>,
2288 pub exec_policy_engine: codewhale_execpolicy::ExecPolicyEngine,
2289 pub auto_review_broad_allow_warnings: Vec<String>,
2290 // Clipboard handler
2291 pub clipboard: ClipboardHandler,
2292 // Tool approval session allowlist
2293 pub approval_session_approved: HashSet<String>,
2294 /// Approval keys (or tool names) the user has denied or aborted in
2295 /// this session. Subsequent re-requests for the same approval key
2296 /// auto-deny without re-prompting (#360) — the model can retry a
2297 /// dangerous command after being told no, but the user shouldn't
2298 /// have to keep dismissing the same dialog.
2299 pub approval_session_denied: HashSet<String>,
2300 pub approval_mode: ApprovalMode,
2301 // Modal view stack (approval/help/etc.)
2302 pub view_stack: ViewStack,
2303 /// Last `request_user_input` prompt, retained so a failed modal submit can reopen (#1198).
2304 pub pending_user_input_prompt: Option<(
2305 String,
2306 codewhale_engine::tools::user_input::UserInputRequest,
2307 )>,
2308 /// Child-agent approval requests shown to the person and not yet
2309 /// answered, keyed by approval id (approvals C1). The footer row, the
2310 /// `/agents` re-open, and retiring answered cards all read this store.
2311 pub pending_child_requests:
2312 std::collections::BTreeMap<String, crate::tui::pending_requests::PendingChildRequest>,
2313 /// Which conversation owns each child agent this host has seen, from the
2314 /// agent lifecycle events. A request from another conversation's child
2315 /// is answered `unavailable` instead of shown here.
2316 pub child_agent_sessions: std::collections::HashMap<String, String>,
2317 /// Esc-Esc backtrack state machine (#133). `Inactive` by default; first
2318 /// Esc primes, second Esc opens the live-transcript overlay scoped to
2319 /// previous user messages so the user can rewind a turn.
2320 pub backtrack: crate::tui::backtrack::BacktrackState,
2321 pub undo_selection: bool,
2322 /// Current session ID for auto-save updates
2323 pub current_session_id: Option<String>,
2324 pub(crate) conversation_mode: Option<String>,
2325 pub(crate) conversation_mode_unavailable: Option<String>,
2326 pub(crate) session_write_receipt:
2327 Option<codewhale_engine::session_manager::SessionWriteReceipt>,
2328 pub(crate) session_write_owner: Option<codewhale_engine::session_manager::SessionWriteOwner>,
2329 /// Exclusive editor ownership, shared with outstanding queue writes.
2330 pub(crate) offline_queue_lease:
2331 Option<std::sync::Arc<codewhale_engine::session_manager::OfflineQueueLease>>,
2332 /// Last non-contended Work snapshot captured in this App. The outer
2333 /// option distinguishes "never captured" from a captured empty state.
2334 pub(crate) last_known_work_state: Option<Option<SessionWorkState>>,
2335 /// Latest bounded runtime goal projection. Persistence stores this beside
2336 /// the owning saved session so a resumed process rebuilds the same goal
2337 /// control state instead of inferring it from transcript prose.
2338 pub(crate) last_known_goal_state: Option<codewhale_engine::session_manager::SessionGoalState>,
2339 /// FIFO of accepted typed controls not yet reconciled by GoalUpdated.
2340 /// The durable desired state lives in `last_known_goal_state`; this queue
2341 /// preserves in-process ordering and mailbox retry state only.
2342 pub(crate) pending_goal_controls: VecDeque<PendingGoalControl>,
2343 pub(crate) pending_fresh_session: Option<crate::tui::ui::PendingFreshSession>,
2344 /// Metadata for the active session, cached in memory so automatic
2345 /// checkpoints never synchronously reload and parse a growing JSON file on
2346 /// the UI thread.
2347 pub(crate) current_session_metadata: Option<SessionMetadata>,
2348 /// Metadata-only registry of large tool outputs produced in this session.
2349 pub session_artifacts: Vec<ArtifactRecord>,
2350 /// Turns in this session that ended `Failed`, persisted with the session
2351 /// so the reason survives the TUI closing.
2352 pub(crate) session_turn_outcomes: Vec<codewhale_engine::session_manager::SavedTurnOutcome>,
2353 /// Trust mode - allow access outside workspace
2354 pub trust_mode: bool,
2355 /// Translation mode — when enabled, the model is instructed to respond in
2356 /// the current locale and a post-hoc translation layer replaces any
2357 /// remaining English output before it reaches the user.
2358 pub translation_enabled: bool,
2359 /// Mini-window (pinned always-on-top) layout preferences, sourced from
2360 /// `[mini_window]` in config.toml at startup and mutated live by
2361 /// `/config mini_window.keep_*`. The renderer reads this instead of the
2362 /// parsed Config so runtime changes apply without a restart.
2363 pub(crate) mini_window: codewhale_runtime::config::MiniWindowConfig,
2364 /// What the bottom chrome shows. Sourced from `tui.status_items` in
2365 /// `~/.deepseek/config.toml` at startup; mutated live by `/statusline`.
2366 ///
2367 /// Read by [`crate::tui::ui::frame::info_segments`] for every segment of
2368 /// the metrics line, by `tideline_footer_from_app` for the posture bar's
2369 /// mode chip, and by `should_fetch_provider_balance` for the balance
2370 /// fetch. Every variant in the list paints exactly one of those; the
2371 /// items that painted nothing were retired in #5950 rather than left as
2372 /// toggles that lie.
2373 pub status_items: Vec<codewhale_runtime::config::StatusItem>,
2374 /// How much of the posture bar to paint (`tui.posture_bar`, #5950):
2375 /// full, compact, or hidden. Sourced from `config.toml` at startup and
2376 /// mutated live by `/config posture_bar`. `hidden` gives the row to the
2377 /// transcript; `compact` starts the bar's shed ladder past the clocks,
2378 /// counts and hints. `status_items` composes the row; this sizes it.
2379 pub posture_bar: codewhale_runtime::config::ChromeRowPreset,
2380 /// The same setting for the metrics line (`tui.metrics_line`, #5950).
2381 /// `compact` keeps the route, context, cost and balance and drops the
2382 /// telemetry and the help hint.
2383 pub metrics_line: codewhale_runtime::config::ChromeRowPreset,
2384 /// Plan state for tracking tasks
2385 pub plan_state: SharedPlanState,
2386 /// Todo list for the canonical `work_update` progress surface.
2387 pub todos: SharedTodoList,
2388 /// Durable runtime services exposed to model-visible task/automation tools.
2389 pub runtime_services: RuntimeToolServices,
2390 /// Latest bounded coordination receipt delivered by the engine. This is
2391 /// the same typed projection returned to headless inspection; the TUI does
2392 /// not parse tool text to reconstruct it.
2393 pub coordination_detail:
2394 Option<codewhale_engine::tools::subagent::CoordinationDetailProjection>,
2395 /// Last MCP manager/discovery snapshot shown in the UI.
2396 pub mcp_snapshot: Option<codewhale_engine::mcp::McpManagerSnapshot>,
2397 /// True while the engine-owned MCP boot connection pass is in flight.
2398 /// Configured rows render as connecting until its snapshot lands.
2399 pub mcp_initializing: bool,
2400 /// When that prediction was made. `None` while no prediction is live; a
2401 /// prediction older than
2402 /// [`MCP_BOOT_PREDICTION_HORIZON`](crate::tui::session_boot::MCP_BOOT_PREDICTION_HORIZON)
2403 /// is retired because the missing receipt is the answer (#7035).
2404 pub mcp_boot_predicted_at: Option<Instant>,
2405 /// Latest engine-owned MCP event generation applied to the UI.
2406 pub mcp_snapshot_generation: u64,
2407 /// The direct snapshot from a successful `/mcp` action supersedes any
2408 /// queued event at `mcp_snapshot_generation`, but not a later generation.
2409 pub mcp_snapshot_generation_invalidated: bool,
2410 /// Enabled servers that have not settled in the current boot pass.
2411 pub mcp_connecting: Vec<String>,
2412 pub mcp_announced_problems:
2413 std::collections::BTreeMap<String, crate::tui::session_boot::McpServerBootState>,
2414 /// Number of MCP servers declared in the user's config at app boot.
2415 /// Used by the footer chip (#502) so a count is visible even before
2416 /// the user runs `/mcp` for the first time. `0` hides the chip.
2417 pub mcp_configured_count: usize,
2418 /// Set after in-TUI MCP config edits because the engine caches its MCP pool.
2419 pub mcp_reload_required: bool,
2420 /// True between an accepted `/mcp` reload (or mutation that rebuilds the
2421 /// live pool) and the background pass's finished receipt, so completion
2422 /// can post exactly one summary.
2423 pub mcp_reload_in_flight: bool,
2424 /// Tool execution log
2425 pub tool_log: Vec<String>,
2426 /// Active skill to apply to next user message
2427 pub active_skill: Option<String>,
2428 /// Content-bound plugin authority carried with `active_skill`, when the
2429 /// selected skill came from a reviewed plugin bundle.
2430 pub active_skill_provenance: Option<codewhale_skills::SkillProvenance>,
2431 /// Cached (name, description) pairs from the skill registry.
2432 /// Populated once at startup and refreshed on install/uninstall so
2433 /// the slash menu can show skills without filesystem I/O on every keystroke.
2434 pub cached_skills: Vec<(String, String)>,
2435 /// Tool call cells by tool id (for cells already finalized in `history`).
2436 /// While a tool call is in flight inside `active_cell`, it is tracked by
2437 /// `active_tool_entries` instead and migrated here at flush time.
2438 pub tool_cells: HashMap<String, usize>,
2439 /// Full tool input/output keyed by history cell index.
2440 pub tool_details_by_cell: HashMap<usize, ToolDetailRecord>,
2441 /// Linked context references keyed by the visible user history cell that
2442 /// introduced them.
2443 pub context_references_by_cell: HashMap<usize, Vec<SessionContextReference>>,
2444 /// Session-wide context references persisted with saved sessions.
2445 pub session_context_references: Vec<SessionContextReference>,
2446 /// In-flight tool/exec group for the current turn. Mutated in place as
2447 /// parallel tool calls start and complete; flushed into `history` on
2448 /// `TurnComplete`.
2449 pub active_cell: Option<ActiveCell>,
2450 /// Revision counter for `active_cell`. Combined with `active_cell.revision`
2451 /// when feeding the transcript cache so cached lines for the synthetic
2452 /// active-cell row are invalidated on every mutation.
2453 pub active_cell_revision: u64,
2454 /// Pending tool details for entries that live inside `active_cell`.
2455 /// Keyed by tool id rather than cell index because the active cell's
2456 /// virtual index can shift (orphan completions push real cells in
2457 /// between). Migrated into `tool_details_by_cell` on flush.
2458 pub active_tool_details: HashMap<String, ToolDetailRecord>,
2459 /// Completion timestamps for entries still living inside `active_cell`.
2460 /// The transcript keeps completed entries until turn flush, but the
2461 /// sidebar can use these timestamps to let settled live rows expire.
2462 pub active_tool_entry_completed_at: HashMap<usize, Instant>,
2463 /// Mapping of exploring tool ids to `(entry index in active_cell, entry
2464 /// within ExploringCell)`. Used to update individual exploring entries
2465 /// when their tools complete.
2466 pub exploring_entries: HashMap<String, (usize, usize)>,
2467 /// Tool calls that should be ignored by the UI
2468 pub ignored_tool_calls: HashMap<String, serde_json::Value>,
2469 /// Last exec wait command shown (for duplicate suppression)
2470 pub last_exec_wait_command: Option<String>,
2471 /// Current streaming assistant cell
2472 pub streaming_message_index: Option<usize>,
2473 /// Provenance for append-only changes to the current streaming cell.
2474 /// Revisions are raw `history_revisions`; the widget maps them through its
2475 /// cache-key transform before handing the receipt to the transcript cache.
2476 pub(crate) streaming_source_receipt: Option<crate::tui::transcript::StreamingSourceReceipt>,
2477 /// True after a local cancel key has been handled and before the engine's
2478 /// authoritative TurnComplete arrives. Stream events already queued for
2479 /// the cancelled turn are ignored so text does not keep appearing after
2480 /// Ctrl+C/Esc returns focus to the composer.
2481 pub suppress_stream_events_until_turn_complete: bool,
2482 /// Index into `active_cell.entries` of the thinking entry currently being
2483 /// streamed. `None` when no thinking block is in flight. P2.3 routes
2484 /// thinking into the active cell so it groups visually with tool calls
2485 /// until the next assistant prose chunk flushes the group into history.
2486 pub streaming_thinking_active_entry: Option<usize>,
2487 pub(crate) pending_thinking_translation_cells: HashMap<u64, usize>,
2488 /// Instant of the last throttled active-cell revision bump for the
2489 /// in-flight thinking stream (#1620). Reasoning chunks arrive faster than
2490 /// the eye can read, and each bump invalidates the active cell's wrap
2491 /// cache, forcing a full re-wrap. We debounce intermediate bumps to a
2492 /// time window so high-frequency thinking deltas no longer trigger a
2493 /// re-render per character. `None` means "no bump since the last
2494 /// finalize" so the first chunk of a block always renders immediately.
2495 pub thinking_revision_last_bump_at: Option<Instant>,
2496 pub(super) thinking_read_window: super::thinking_checkpoint::ThinkingReadWindow,
2497 pub(crate) thinking_revision_owed: bool,
2498 /// Newline-gated streaming collector state.
2499 pub streaming_state: StreamingState,
2500 /// Live approximate output tokens for the current assistant stream.
2501 pub streaming_output_token_estimate: u64,
2502 /// Provider-billed prompt tokens from the most recent parent model call
2503 /// (per-step `TurnUsage`). The context meter takes the max of this and
2504 /// the local estimate — the same rule the auto-compaction trigger uses —
2505 /// so the two can never disagree about pressure (#5577). Cleared when
2506 /// compaction rewrites history, since the receipt describes the
2507 /// pre-compaction context.
2508 pub last_billed_input_tokens: Option<u32>,
2509 /// Last successful compaction, so `/context` and the inspector can name
2510 /// the path and the last-round floor instead of looking empty.
2511 pub last_compaction: Option<codewhale_engine::compaction::LastCompactionSnapshot>,
2512 /// Accumulated reasoning text
2513 pub reasoning_buffer: String,
2514 /// Live reasoning header extracted from bold text
2515 pub reasoning_header: Option<String>,
2516 /// Last completed reasoning block
2517 pub last_reasoning: Option<String>,
2518 /// Tool calls captured for the pending assistant message
2519 pub pending_tool_uses: Vec<ContentBlock>,
2520 /// One-line permission receipts (`tool_id`, text) for decisions nobody
2521 /// was prompted for, held until that tool's card completes so the note
2522 /// lands directly under the card instead of splitting a running tool run.
2523 pub pending_gate_receipts: Vec<(String, String)>,
2524 /// Permission receipts for child (sub-agent) tool calls, keyed by agent
2525 /// id then `(tool_id, text)`, rendered under the matching tool card when
2526 /// that child is focused. Session-resident only.
2527 pub child_gate_receipts: std::collections::HashMap<String, Vec<(String, String)>>,
2528 pub auto_review_blocked_receipts:
2529 Vec<codewhale_engine::core::authority::auto_review::AutoReviewBlockedAction>,
2530 /// User messages queued while a turn is running
2531 pub queued_messages: VecDeque<QueuedMessage>,
2532 pub held_restored_queue: usize,
2533 /// Draft queued message being edited
2534 pub queued_draft: Option<QueuedMessage>,
2535 pub queued_draft_was_held: bool,
2536 /// Steers accepted by the steer channel but not yet seen in the engine's
2537 /// record. Rendered through the "sending into turn" preview bucket;
2538 /// promoted to a transcript cell by
2539 /// `apply_engine_session_projection`, or queued as a follow-up by
2540 /// `TurnComplete` when the turn ended without them (#6190, #6297).
2541 pub inflight_steers: VecDeque<InflightSteer>,
2542 /// Start time for current turn
2543 pub turn_started_at: Option<Instant>,
2544 /// Most recent engine event observed for the current turn. This is
2545 /// separate from `turn_started_at` because the latter drives elapsed-time
2546 /// UI and must not be reset during long but healthy turns.
2547 pub turn_last_activity_at: Option<Instant>,
2548 /// Sum of completed turn durations for this `App` instance (#448
2549 /// follow-up). Drives the footer's `worked Nh Mm` chip so the
2550 /// label reflects actual model work, not wall-clock since launch.
2551 /// Incremented on `TurnComplete` from the elapsed time of the
2552 /// just-finished turn. Resets per launch.
2553 pub cumulative_turn_duration: std::time::Duration,
2554 /// Session metrics strip accumulators (model-call/tool timings, TTFT,
2555 /// throughput). Sourced only from engine events; see
2556 /// [`crate::tui::session_metrics`].
2557 pub session_metrics: crate::tui::session_metrics::SessionMetrics,
2558 /// DeepSeek account balance, refreshed once per turn completion.
2559 /// Shared cell updated by background fetch tasks; read lock in the UI thread.
2560 pub balance_cell:
2561 std::sync::Arc<std::sync::Mutex<Option<codewhale_engine::pricing::BalanceInfo>>>,
2562 /// The route `balance_cell` belongs to (provider, endpoint, key
2563 /// fingerprint). A route change swaps in a fresh cell; see
2564 /// `provider_routes::balance_cell_for_route`.
2565 pub balance_route: Option<String>,
2566 /// Shared cell for async fleet-profile model-draft delivery. A background
2567 /// task fills it (model label + drafted profile or a failure reason) so
2568 /// the drafting network call never parks the event loop (#3757 review).
2569 #[allow(clippy::type_complexity)]
2570 /// Monotonic generation for model-draft requests. Bumped on each draft
2571 /// request and each setup/fleet wizard open, so a draft that lands after
2572 /// a superseding request or a wizard reopen is dropped rather than
2573 /// installed into the wrong (or a stale) wizard instance.
2574 pub draft_gen: std::sync::Arc<std::sync::atomic::AtomicU64>,
2575 #[allow(clippy::type_complexity)]
2576 pub fleet_draft_cell: std::sync::Arc<
2577 std::sync::Mutex<
2578 Option<(
2579 u64,
2580 String,
2581 // The `(provider, model)` route the operator picked when they
2582 // pressed `m` (#4093). Carried alongside the async draft so the
2583 // ratified profile keeps the picked cross-provider route even if
2584 // the model draft (which is always `provider: None`) omitted or
2585 // changed it. `None` for an `inherit` pick.
2586 Option<(String, String)>,
2587 // The reasoning tier selected when the operator pressed `m`
2588 // (#4137). `None` means inherit.
2589 Option<String>,
2590 Result<Box<codewhale_engine::fleet::profile::FleetProfileDraft>, String>,
2591 )>,
2592 >,
2593 >,
2594 /// Shared cell for async constitution model-draft delivery (same pattern
2595 /// as `fleet_draft_cell`, so the drafting network call never parks the
2596 /// event loop).
2597 #[allow(clippy::type_complexity)]
2598 pub constitution_draft_cell: std::sync::Arc<
2599 std::sync::Mutex<
2600 Option<(
2601 u64,
2602 String,
2603 codewhale_localization::Locale,
2604 Result<Box<codewhale_config::UserConstitution>, String>,
2605 )>,
2606 >,
2607 >,
2608 /// Discovery, registration and the browser callback all run in the
2609 /// background. Esc or dropping the app cancels the entire operation.
2610 pub(crate) mcp_login: Option<PendingMcpLogin>,
2611 /// `/mcp retry` requests still waiting on the engine, one per server.
2612 pub(crate) mcp_retries: Vec<PendingMcpRetry>,
2613 /// Server whose OAuth login just stored credentials; the event loop
2614 /// retries that one server instead of asking for a full reload.
2615 pub(crate) mcp_login_reconnect: Option<String>,
2616 /// Shared cell for async prompt suggestion delivery from background task.
2617 pub prompt_suggestion_cell: std::sync::Arc<std::sync::Mutex<Option<(u64, String)>>>,
2618 /// Tracks whether the initial balance fetch has been attempted for this session.
2619 pub balance_initiated: bool,
2620 /// Timestamp of the last balance fetch, used to debounce rapid requests.
2621 pub last_balance_fetch: Option<std::time::Instant>,
2622 /// Current runtime turn id (if known).
2623 pub runtime_turn_id: Option<String>,
2624 /// Current runtime turn status (if known).
2625 pub runtime_turn_status: Option<String>,
2626 /// Monotonic turn counter for stable user-facing labels (#3030).
2627 /// Incremented each time a new turn starts; displayed as "Turn N".
2628 pub turn_counter: u64,
2629 /// When the UI accepted a user message but has not observed `TurnStarted` yet.
2630 pub dispatch_started_at: Option<Instant>,
2631
2632 /// Cached git context snapshot for the footer.
2633 pub workspace_context: Option<String>,
2634 /// Cached linked-worktree identity, refreshed with the branch off the draw path.
2635 pub workspace_is_linked_worktree: bool,
2636 /// Shared cell for async git context updates (#399 S1).
2637 pub workspace_context_cell: std::sync::Arc<
2638 std::sync::Mutex<Option<crate::tui::workspace_context::WorkspaceContextSnapshot>>,
2639 >,
2640 /// Timestamp for cached workspace context.
2641 pub workspace_context_refreshed_at: Option<Instant>,
2642 /// Cached size of the memory file, formatted for the Session sidebar.
2643 ///
2644 /// Rendered every frame the Session/Context panel is visible, so the
2645 /// `stat` behind it is refreshed on the workspace-context TTL tick
2646 /// instead of inside the draw closure (#3908) — tens of ms per frame on
2647 /// NFS/SSHFS/cloud-synced homes otherwise.
2648 pub memory_size_hint: Option<String>,
2649 /// The workspace notes (`/note`), refreshed with the workspace context
2650 /// off the render path; the dock's NOTES view lists them (#6565).
2651 pub workspace_notes: Vec<String>,
2652 /// Cached background tasks for sidebar rendering.
2653 pub task_panel: Vec<TaskPanelEntry>,
2654 pub task_panel_session_id: Option<String>,
2655 pub task_panel_unavailable: bool,
2656 /// Live scheduled-work projection for the activity band
2657 /// (AUTOMATION-VISIBILITY-SPEC §2.1), refreshed on the task-panel cadence
2658 /// by `refresh_automation_panel`. The band reads it;
2659 /// `background_indicator` never learns about automations.
2660 pub automation_panel: crate::tui::automation_panel::AutomationPanelState,
2661 /// The automation store scan in flight for `automation_panel`, if any.
2662 /// The scan reads every definition and run file, so it runs on a
2663 /// blocking thread and the tick folds it once it has finished — the
2664 /// async UI loop never parks behind the automation store's disk.
2665 pub automation_scan:
2666 Option<tokio::task::JoinHandle<crate::tui::automation_panel::AutomationScan>>,
2667 /// Session-local quieting and command detectors for event-driven tips.
2668 pub behavioral_tips: crate::tui::behavioral_tips::BehavioralTipState,
2669 /// Footer-hint use counts, hydrated from `Settings` at startup and
2670 /// bumped by `App::note_footer_hint_used`. The posture bar reads this
2671 /// every frame, so the counts live here rather than behind a
2672 /// settings-file read.
2673 pub footer_hint_uses: std::collections::BTreeMap<String, u8>,
2674 /// Every workflow run this session is showing, in start order, one state
2675 /// per run id (#4121). The workbar under the composer paints one row per
2676 /// run; the transcript gets only each run's start and finish lines.
2677 /// Settled runs stay until a later turn starts with nothing still running.
2678 pub workflow_runs: Vec<crate::tui::widgets::workflow_panel::WorkflowPanel>,
2679 /// Wall-clock time when this TUI session started. Used by the Work
2680 /// sidebar projection to hide completed durable tasks that finished
2681 /// before the current session (bug #1913).
2682 pub session_started_at: chrono::DateTime<chrono::Utc>,
2683 /// Whether the UI needs to be redrawn.
2684 pub needs_redraw: bool,
2685 /// A fleet mutation (`/fleet add|remove`, ⇧F, auto-enroll) landed on
2686 /// disk since the engine last received its roster. The event loop
2687 /// flushes it through `Op::SetFleetRoster` (`sync_fleet_roster`).
2688 pub fleet_roster_stale: bool,
2689 /// When true, the next draw will be a full repaint (terminal clear +
2690 /// all cells redrawn) instead of a ratatui incremental diff. Used by
2691 /// theme switches where the diff engine may miss color-only changes
2692 /// in sidebar cells that were previously rendered with palette constants.
2693 pub force_next_full_repaint: bool,
2694 /// When the current thinking block started (for duration tracking).
2695 pub thinking_started_at: Option<Instant>,
2696 /// Whether context compaction is currently in progress.
2697 pub is_compacting: bool,
2698 /// Typed identity retained from CompactionStarted until its matching
2699 /// CompactionCompleted/CompactionFailed event.
2700 pub(crate) active_compaction: Option<ActiveCompaction>,
2701 /// A manual compaction op accepted by the UI but waiting for the engine to
2702 /// finish the active turn and emit CompactionStarted.
2703 pub(crate) manual_compaction_queued: bool,
2704 /// Stable identity allocated before the manual request enters the engine
2705 /// mailbox, retained so Ctrl+C/Esc can cancel that exact queued pass.
2706 pub(crate) manual_compaction_id: Option<String>,
2707 /// A manual compaction request that found the bounded engine mailbox full.
2708 /// The event loop retries the send once a slot frees; any compaction that
2709 /// starts or settles in the meantime supersedes it. Inner value is the
2710 /// requested focus.
2711 pub(crate) deferred_manual_compaction: Option<Option<String>>,
2712 /// Whether context purge is currently in progress.
2713 pub is_purging: bool,
2714 /// Set when the user scrolls up/down during a streaming turn so subsequent
2715 /// streamed chunks don't yank the view back to the live tail. Cleared
2716 /// when the user explicitly returns to bottom or the turn completes.
2717 pub user_scrolled_during_stream: bool,
2718 /// Timestamp of the last user message send (for brief visual feedback).
2719 pub last_send_at: Option<Instant>,
2720 /// Most recent user prompt accepted for an active engine turn. Ctrl+C can
2721 /// restore this into an empty composer after cancelling that turn.
2722 pub last_submitted_prompt: Option<String>,
2723 /// The dispatched message of the turn in flight, until that turn ends.
2724 /// A credential rejection the engine marks unsent hands it back (#6566).
2725 pub unanswered_submission: Option<UnansweredSubmission>,
2726 /// Startup prompt should be submitted automatically after the engine is ready.
2727 pub auto_submit_initial_input: bool,
2728 /// Two-tap quit confirmation. When set, a prior Ctrl+C in idle state has
2729 /// armed the quit shortcut; a second Ctrl+C before this `Instant` exits
2730 /// the app, while expiry silently re-arms the prompt for next time.
2731 /// Stays `None` while a turn is in flight or a modal/picker is open so
2732 /// Ctrl+C keeps its current "interrupt this turn" semantics in those
2733 /// states. See [`App::arm_quit`] / [`App::quit_is_armed`].
2734 pub quit_armed_until: Option<Instant>,
2735
2736 // === Prefix-Cache Stability Tracking ===
2737 /// Number of times the prefix (system prompt + tool specs) has changed.
2738 pub prefix_change_count: u64,
2739 /// Total number of prefix stability checks performed.
2740 pub prefix_checks_total: u64,
2741 /// Current prefix stability percentage, if known.
2742 pub prefix_stability_pct: Option<u32>,
2743 /// Description of the last prefix change, if any.
2744 pub last_prefix_change_desc: Option<String>,
2745 /// Current pinned prefix combined hash (SHA-256, 64 hex chars).
2746 /// Updated per-turn via PrefixCacheChange events; surfaced by
2747 /// `/cache stats` for cache-hit debugging.
2748 pub last_pinned_prefix_hash: Option<String>,
2749 /// Why the current KV-cache prefix pin exists (`initial`/`resume`/`change:*`).
2750 pub prefix_pin_reason: Option<String>,
2751 /// Explanation of the most recent expected cache miss.
2752 pub prefix_last_miss_reason: Option<String>,
2753 /// Undeclared prefix drifts this session (should stay 0 after the fix).
2754 pub prefix_drift_count: u64,
2755 /// `<context_update>` snapshots appended this session.
2756 pub prefix_context_updates: u64,
2757
2758 // === Transcript filtering (#397) ===
2759 /// Transcript cells the user has collapsed (hidden from view).
2760 /// Stores **original** virtual cell indices (pre-filtering).
2761 pub collapsed_cells: HashSet<usize>,
2762 /// Explicit expand/collapse intents for transcript cells, keyed by
2763 /// **original** virtual cell index. Space preserves a visible preview;
2764 /// context-menu Hide uses `collapsed_cells` instead.
2765 ///
2766 /// An absent index means the user has not touched that cell, so the
2767 /// thinking display preferences decide it; other cells start expanded.
2768 /// A present index is absolute, so
2769 /// changing `verbose` or `thinking_default_expanded` afterwards leaves
2770 /// the user's own choice alone (#5847).
2771 pub cell_folds: HashMap<usize, TranscriptFold>,
2772 /// Mapping from filtered cell index → original virtual index.
2773 /// Populated during `ChatWidget::new` by filtering out collapsed cells.
2774 /// Used by `build_context_menu_entries` to convert line-meta indices
2775 /// back to original indices for the `HideCell` / `ShowCell` actions.
2776 pub collapsed_cell_map: Vec<usize>,
2777
2778 /// Whether `/edit` has loaded the last user message into the composer and
2779 /// the next submit should replace (not append to) the last exchange.
2780 pub edit_in_progress: bool,
2781
2782 /// Whether the config has an enabled `[lsp]` table.
2783 pub lsp_enabled: bool,
2784 pub lsp_config: Option<codewhale_lsp::LspConfig>,
2785 /// Current-turn LSP repair-loop summary for Ctrl-O Turn Inspector (#4107).
2786 pub lsp_repair: LspRepairState,
2787 /// Derived title for the current session shown in the composer border.
2788 /// Updated when `EngineEvent::SessionUpdated` fires or a saved session is loaded.
2789 pub session_title: Option<String>,
2790
2791 /// User-configured tab/window title for the current session, shown as
2792 /// `[title] …` in front of the terminal window title. Set with the
2793 /// `/title` command and persisted on the saved session; distinct from
2794 /// [`session_title`](Self::session_title), which is the session *name*
2795 /// shown in the composer border and session picker.
2796 pub window_title: Option<String>,
2797 pub composer_color: Option<String>,
2798 /// Default tab/window title from the `title` config key (or a profile
2799 /// overlay). Used when the current session has no explicit
2800 /// [`window_title`](Self::window_title).
2801 pub title_default: Option<String>,
2802
2803 /// Post-turn receipt rendered as transient composer chrome.
2804 /// Set when a turn completes; cleared when a new turn starts or after expiry.
2805 pub receipt_text: Option<String>,
2806 pub receipt_started_at: Option<Instant>,
2807 /// Tool evidence collected during the current turn for the receipt.
2808 pub tool_evidence: Vec<ToolEvidence>,
2809 }
2810
2811 pub(crate) struct ToolRunCache {
2812 /// Bumped each time the projection below is rebuilt, so anything derived
2813 /// from it (the collapsed-row mapping) can tell it is stale without
2814 /// re-deriving the key.
2815 pub(crate) generation: u64,
2816 pub(crate) filtered: FilteredProjection,
2817 pub(crate) history_version: u64,
2818 pub(crate) active_cell_revision: u64,
2819 pub(crate) active_len: usize,
2820 pub(crate) threshold: usize,
2821 pub(crate) mode: ToolCollapseMode,
2822 pub(crate) calm_mode: bool,
2823 pub(crate) locale: Locale,
2824 #[cfg(test)]
2825 pub(crate) projection_builds: usize,
2826 pub(crate) history_len: usize,
2827 pub(crate) expanded_runs: HashSet<usize>,
2828 pub(crate) open_tail: bool,
2829 pub(crate) open_turn_user_index: Option<usize>,
2830 pub(crate) echoed_queued_users: usize,
2831 pub(crate) turn_durations_revision: u64,
2832 pub(crate) summaries: HashMap<usize, (HistoryCell, u64)>,
2833 pub(crate) hidden_indices: HashSet<usize>,
2834 pub(crate) superseded_todos: HashSet<usize>,
2835 }
2836
2837 /// The collapsed transcript path's rendered-row -> original-index mapping.
2838 ///
2839 /// Which rows survive filtering depends only on the tool-run projection and
2840 /// the user's hidden cells, never on cell revisions, so it is computed once
2841 /// per change of either instead of once per frame with a hash lookup per
2842 /// history cell (#6652). Revisions are still read fresh every frame.
2843 #[derive(Default)]
2844 pub(crate) struct FilteredProjection {
2845 /// `ToolRunCache::generation` this mapping was built for.
2846 built_for: Option<u64>,
2847 collapsed_cells: HashSet<usize>,
2848 /// Rendered position -> original virtual index.
2849 pub(crate) original: Vec<usize>,
2850 /// Rendered positions that show a collapsed-run summary instead of the
2851 /// cell at their original index.
2852 pub(crate) summary_slots: Vec<usize>,
2853 }
2854
2855 impl ToolRunCache {
2856 /// Refresh [`FilteredProjection`] unless it already matches the current
2857 /// projection and `collapsed_cells`. `rows` is committed plus active.
2858 pub(crate) fn refresh_filtered(&mut self, rows: usize, collapsed_cells: &HashSet<usize>) {
2859 if self.filtered.built_for == Some(self.generation)
2860 && self.filtered.collapsed_cells == *collapsed_cells
2861 {
2862 return;
2863 }
2864 self.filtered.original.clear();
2865 self.filtered.summary_slots.clear();
2866 for index in 0..rows {
2867 if self.superseded_todos.contains(&index)
2868 || collapsed_cells.contains(&index)
2869 || self.hidden_indices.contains(&index)
2870 {
2871 continue;
2872 }
2873 if self.summaries.contains_key(&index) {
2874 self.filtered
2875 .summary_slots
2876 .push(self.filtered.original.len());
2877 }
2878 self.filtered.original.push(index);
2879 }
2880 self.filtered.collapsed_cells.clone_from(collapsed_cells);
2881 self.filtered.built_for = Some(self.generation);
2882 }
2883 }
2884
2885 impl Default for ToolRunCache {
2886 fn default() -> Self {
2887 Self {
2888 generation: 0,
2889 filtered: FilteredProjection::default(),
2890 history_version: u64::MAX,
2891 active_cell_revision: u64::MAX,
2892 active_len: usize::MAX,
2893 threshold: usize::MAX,
2894 mode: ToolCollapseMode::Expanded,
2895 calm_mode: false,
2896 locale: Locale::En,
2897 #[cfg(test)]
2898 projection_builds: 0,
2899 history_len: usize::MAX,
2900 expanded_runs: HashSet::new(),
2901 open_tail: false,
2902 open_turn_user_index: None,
2903 echoed_queued_users: 0,
2904 turn_durations_revision: u64::MAX,
2905 summaries: HashMap::new(),
2906 hidden_indices: HashSet::new(),
2907 superseded_todos: HashSet::new(),
2908 }
2909 }
2910 }
2911
2912 // === Deref to ComposerState for backward compat ===
2913
2914 impl std::ops::Deref for App {
2915 type Target = ComposerState;
2916 fn deref(&self) -> &Self::Target {
2917 &self.composer
2918 }
2919 }
2920
2921 impl std::ops::DerefMut for App {
2922 fn deref_mut(&mut self) -> &mut Self::Target {
2923 &mut self.composer
2924 }
2925 }
2926
2927 // === App State ===
2928
2929 pub(crate) fn default_composer_arrows_scroll(use_mouse_capture: bool) -> bool {
2930 default_composer_arrows_scroll_for_platform(use_mouse_capture, cfg!(windows))
2931 }
2932
2933 fn default_composer_arrows_scroll_for_platform(use_mouse_capture: bool, _is_windows: bool) -> bool {
2934 !use_mouse_capture
2935 }
2936
2937 impl App {
2938 /// The durable task manager this host currently owns.
2939 ///
2940 /// This is the one slot every consumer reads. A session switch can adopt
2941 /// another Runtime store, which replaces the manager; a handle captured at
2942 /// launch would then describe a store this host no longer holds, and its
2943 /// admission is closed. `None` means this host is between managers — after
2944 /// a failed adoption, before exit — and callers must treat that as "no task
2945 /// work is available right now" rather than as an error.
2946 #[must_use]
2947 pub fn task_manager(&self) -> Option<crate::task_manager::SharedTaskManager> {
2948 self.runtime_services.task_manager.clone()
2949 }
2950
2951 /// Start or end an MCP boot prediction, stamping when it starts.
2952 ///
2953 /// Every writer of [`App::mcp_initializing`] goes through here so a
2954 /// prediction always carries its own age; a bare flag could outlive the
2955 /// pass it describes (#7035).
2956 pub fn set_mcp_boot_initializing(&mut self, initializing: bool) {
2957 self.mcp_initializing = initializing;
2958 // Progress events re-assert the prediction on every batch; only a
2959 // genuine stop→start restarts its clock, or a talkative pass that
2960 // never finishes would keep the guess alive forever.
2961 self.mcp_boot_predicted_at = match (initializing, self.mcp_boot_predicted_at) {
2962 (true, Some(stamp)) => Some(stamp),
2963 (true, None) => Some(Instant::now()),
2964 (false, _) => None,
2965 };
2966 }
2967
2968 /// True while the boot prediction is still worth painting.
2969 #[must_use]
2970 pub fn mcp_boot_initializing(&self) -> bool {
2971 self.mcp_boot_initializing_at(Instant::now())
2972 }
2973
2974 #[must_use]
2975 pub(crate) fn mcp_boot_initializing_at(&self, now: Instant) -> bool {
2976 self.mcp_initializing
2977 && self.mcp_boot_predicted_at.is_some_and(|predicted_at| {
2978 now.saturating_duration_since(predicted_at)
2979 < crate::tui::session_boot::MCP_BOOT_PREDICTION_HORIZON
2980 })
2981 }
2982
2983 /// Time until a live boot prediction reaches its horizon, so the event loop
2984 /// wakes to retire it rather than waiting for unrelated input (#7035).
2985 #[must_use]
2986 pub fn mcp_boot_prediction_due_in(&self, now: Instant) -> Option<Duration> {
2987 let predicted_at = self.mcp_boot_predicted_at?;
2988 self.mcp_initializing.then(|| {
2989 crate::tui::session_boot::MCP_BOOT_PREDICTION_HORIZON
2990 .saturating_sub(now.saturating_duration_since(predicted_at))
2991 })
2992 }
2993
2994 /// Retire a prediction whose receipt never arrived, and repaint once so the
2995 /// stale rows leave the screen instead of waiting for the next event.
2996 pub fn settle_stale_mcp_boot_prediction(&mut self) {
2997 self.settle_stale_mcp_boot_prediction_at(Instant::now());
2998 }
2999
3000 pub(crate) fn settle_stale_mcp_boot_prediction_at(&mut self, now: Instant) {
3001 if !self.mcp_initializing || self.mcp_boot_initializing_at(now) {
3002 return;
3003 }
3004 self.mcp_initializing = false;
3005 self.mcp_boot_predicted_at = None;
3006 self.mcp_connecting.clear();
3007 self.needs_redraw = true;
3008 }
3009
3010 pub(crate) fn start_local_ollama_probe(&mut self, config: &Config, requested: bool) -> bool {
3011 if !self.should_adopt_live_local_ollama() {
3012 return false;
3013 }
3014 if let Some(probe) = self.local_ollama_probe.as_mut()
3015 && !probe.task.is_finished()
3016 {
3017 probe.requested |= requested;
3018 return true;
3019 }
3020 self.local_ollama_probe =
3021 codewhale_engine::local_ollama::spawn_local_ollama_adoption_probe(config, true)
3022 .map(|task| LocalOllamaProbe { task, requested });
3023 self.local_ollama_probe.is_some()
3024 }
3025
3026 pub(crate) fn should_adopt_live_local_ollama(&mut self) -> bool {
3027 let picker_interacted = self.view_stack.provider_picker_interacted();
3028 if self.api_provider == ProviderKind::Ollama {
3029 return self.provider_identity_for_persistence() == "ollama"
3030 && codewhale_runtime::config::is_unresolved_local_ollama_model(&self.model)
3031 && !self.is_loading
3032 && !picker_interacted
3033 && self.view_stack.top_kind() != Some(ModalKind::ModelPicker);
3034 }
3035 codewhale_engine::local_ollama::should_adopt_live_local_ollama(
3036 self.startup_route_configured,
3037 self.api_provider,
3038 picker_interacted,
3039 self.onboarding_needs_api_key || self.onboarding_missing_key_recovery,
3040 )
3041 }
3042
3043 /// A retained roster remains readable only in its owning conversation.
3044 pub(crate) fn current_agent_roster(&self) -> &[codewhale_engine::agent_roster::AgentRosterRow] {
3045 if self
3046 .current_session_id
3047 .as_deref()
3048 .is_some_and(|session_id| {
3049 !session_id.is_empty()
3050 && self.agent_roster_session_id.as_deref() == Some(session_id)
3051 })
3052 {
3053 &self.agent_roster
3054 } else {
3055 &[]
3056 }
3057 }
3058
3059 /// Who owns the keyboard right now.
3060 ///
3061 /// The single derivation of [`Focus`], mirroring the order in which the
3062 /// event loop actually offers a key to each surface. Shell bindings ask
3063 /// this; only genuine composer *editing* keys may ask whether the
3064 /// composer has text.
3065 #[must_use]
3066 pub fn focus(&self) -> Focus {
3067 if self.redaction_gate && self.onboarding == OnboardingState::None {
3068 return Focus::RedactionGate;
3069 }
3070 if let Some(kind) = self.view_stack.top_kind() {
3071 return Focus::Modal(kind);
3072 }
3073 if self.onboarding != OnboardingState::None {
3074 return Focus::Onboarding;
3075 }
3076 if self.launch.visible {
3077 return Focus::Launch;
3078 }
3079 if self.work_surface.focused {
3080 if self.work_surface.panel == crate::tui::work_surface::RailPanel::Terminal {
3081 return Focus::TerminalPanel;
3082 }
3083 return Focus::Panel;
3084 }
3085 Focus::Composer
3086 }
3087
3088 /// Persist the pending session route as the explicit choice (`/fleet save`,
3089 /// `/fleet save-as`, `/model save-default`). Returns the receipt
3090 /// message naming the exact file written — or an error message when the
3091 /// write failed. Nothing is ever written without this explicit call.
3092 pub fn apply_route_save_choice(
3093 &mut self,
3094 choice: crate::tui::views::route_save_prompt::RouteSaveChoice,
3095 ) -> String {
3096 use crate::tui::views::route_save_prompt::RouteSaveChoice;
3097 use codewhale_engine::fleet::store::{FleetFile, FleetOperator, save_fleet, set_selected};
3098 let locale = self.ui_locale;
3099 let Some(pending) = self.pending_route_save.take() else {
3100 return tr(locale, MessageId::RouteSaveNothingPending).into_owned();
3101 };
3102 let route = format!("{}/{}", pending.provider_identity, pending.model);
3103 match choice {
3104 RouteSaveChoice::UpdateFleet => {
3105 let Some((name, scope)) = pending.fleet.clone() else {
3106 return tr(locale, MessageId::RouteSaveNoTeamSelected).into_owned();
3107 };
3108 match codewhale_engine::fleet::store::load_fleet_in_scope(
3109 &name,
3110 scope,
3111 &self.workspace,
3112 ) {
3113 Ok((mut fleet, _source_path)) => {
3114 fleet.operator = Some(FleetOperator {
3115 provider: pending.provider_identity.clone(),
3116 model: pending.model.clone(),
3117 reasoning: fleet.operator.as_ref().and_then(|op| op.reasoning.clone()),
3118 });
3119 match save_fleet(&fleet, scope, &self.workspace) {
3120 Ok(path) => tr(locale, MessageId::RouteSaveTeamUpdated)
3121 .replace("{name}", &fleet.name)
3122 .replace("{route}", &route)
3123 .replace("{path}", &path.display().to_string()),
3124 Err(err) => tr(locale, MessageId::RouteSaveTeamUpdateFailed)
3125 .replace("{error}", &err.to_string()),
3126 }
3127 }
3128 Err(err) => tr(locale, MessageId::RouteSaveTeamUpdateFailedMoved)
3129 .replace("{error}", &err.to_string()),
3130 }
3131 }
3132 RouteSaveChoice::SaveAsNewFleet => {
3133 let display = format!(
3134 "{} {}",
3135 codewhale_config::ProviderKind::parse(&pending.provider_identity)
3136 .map(|p| p.provider().display_name().to_string())
3137 .unwrap_or_else(|| pending.provider_identity.clone()),
3138 pending.model
3139 );
3140 let Ok(mut fleet) = FleetFile::new(
3141 display.clone(),
3142 Some("Saved from a session route choice.".to_string()),
3143 ) else {
3144 return tr(locale, MessageId::RouteSaveTeamCreateFailed).into_owned();
3145 };
3146 fleet.operator = Some(FleetOperator {
3147 provider: pending.provider_identity.clone(),
3148 model: pending.model.clone(),
3149 reasoning: None,
3150 });
3151 match save_fleet(
3152 &fleet,
3153 codewhale_engine::fleet::store::FleetScope::Personal,
3154 &self.workspace,
3155 ) {
3156 Ok(path) => {
3157 let selected_note = match set_selected(
3158 &display,
3159 codewhale_engine::fleet::store::FleetScope::Personal,
3160 &self.workspace,
3161 ) {
3162 Ok(sel_path) => tr(locale, MessageId::RouteSaveSelectedNote)
3163 .replace("{path}", &sel_path.display().to_string()),
3164 Err(err) => tr(locale, MessageId::RouteSaveSelectionFailedNote)
3165 .replace("{error}", &err.to_string()),
3166 };
3167 tr(locale, MessageId::RouteSaveSavedAsNewTeam)
3168 .replace("{route}", &route)
3169 .replace("{name}", &display)
3170 .replace("{path}", &path.display().to_string())
3171 .replace("{note}", &selected_note)
3172 }
3173 Err(err) => {
3174 tr(locale, MessageId::RouteSaveFailed).replace("{error}", &err.to_string())
3175 }
3176 }
3177 }
3178 RouteSaveChoice::SaveAsDefault => {
3179 let active_model = if self.auto_model { "auto" } else { &self.model };
3180 if (pending.provider_identity != self.provider_identity_for_persistence()
3181 && Some(pending.provider_identity.as_str())
3182 != self.provider_id_for_persistence())
3183 || pending.model != active_model
3184 {
3185 return tr(locale, MessageId::RouteSaveRouteNoLongerActive).into_owned();
3186 }
3187 let identity = match self.admitted_provider_identity() {
3188 Ok(identity) => identity,
3189 Err(error) => {
3190 return tr(locale, MessageId::RouteSaveFailed)
3191 .replace("{error}", &error.to_string());
3192 }
3193 };
3194 persist_route_as_startup_default(locale, identity, &pending.model)
3195 }
3196 }
3197 }
3198
3199 /// Persist the live route with a typed failure for onboarding, whose next
3200 /// transition depends on knowing that the restart route actually landed.
3201 pub(crate) fn try_save_live_route_as_startup_default(&mut self) -> anyhow::Result<String> {
3202 let provider_identity = self.provider_identity_for_persistence().to_string();
3203 let model = if self.auto_model {
3204 "auto".to_string()
3205 } else {
3206 self.model.clone()
3207 };
3208 try_persist_route_as_startup_default(
3209 self.admitted_provider_identity()
3210 .map_err(anyhow::Error::msg)?,
3211 &model,
3212 )?;
3213 // Resolve the prompt only after the write lands. If persistence fails,
3214 // keep the retry available instead of discarding the operator's route.
3215 self.pending_route_save = None;
3216 Ok(self
3217 .tr(MessageId::RouteSaveRememberedDefault)
3218 .replace("{route}", &format!("{provider_identity}/{model}")))
3219 }
3220
3221 /// Record that the live session route changed to `provider_identity` /
3222 /// `model`. The change is temporary until the user explicitly chooses how
3223 /// to save it; nothing is written here.
3224 pub fn note_session_route_change(&mut self, provider_identity: &str, model: &str) {
3225 let fleet = codewhale_engine::fleet::store::selected_fleet(&self.workspace)
3226 .map(|sel| (sel.name, sel.scope));
3227 self.pending_route_save = Some(PendingRouteSave {
3228 provider_identity: provider_identity.to_string(),
3229 model: model.to_string(),
3230 fleet,
3231 });
3232 }
3233
3234 /// One truthful chip for cumulative session cost surfaces.
3235 ///
3236 /// Session history wins over the *current* route: switching to an OAuth or
3237 /// local route must not hide spend already accrued on a metered route, and
3238 /// an unpriced turn turns a displayed amount into a subtotal rather than a
3239 /// complete total.
3240 #[must_use]
3241 pub fn cumulative_usage_chip(&self) -> codewhale_engine::route_billing::UsageChip {
3242 use codewhale_engine::pricing::UnpricedReason;
3243 let displayed = self.displayed_session_cost_for_currency(self.cost_currency);
3244 let (priced, unpriced) = match self.cost_display_currency(self.cost_currency) {
3245 CostCurrency::Usd => (
3246 self.session.cost_priced_turns,
3247 self.session.cost_unpriced_turns,
3248 ),
3249 CostCurrency::Cny => (
3250 self.session.cost_cny_priced_turns,
3251 self.session.cost_cny_unpriced_turns,
3252 ),
3253 };
3254 let saved_reasons = match self.cost_display_currency(self.cost_currency) {
3255 CostCurrency::Usd => &self.session.cost_unpriced_reasons,
3256 CostCurrency::Cny => &self.session.cost_cny_unpriced_reasons,
3257 };
3258 let mut reasons: Vec<_> = saved_reasons
3259 .iter()
3260 .map(|reason| UnpricedReason::from_label(reason))
3261 .collect();
3262 if (self.session.cost_coverage_unknown_legacy || reasons.is_empty())
3263 && !reasons.contains(&UnpricedReason::UnrecordedCoverage)
3264 {
3265 reasons.push(UnpricedReason::UnrecordedCoverage);
3266 }
3267 if self.session.cost_coverage_unknown_legacy {
3268 return if displayed.is_finite() && displayed > 0.0 {
3269 codewhale_engine::route_billing::UsageChip::PricedSubtotal {
3270 amount: self.format_cost_amount(displayed),
3271 legacy: true,
3272 reasons,
3273 }
3274 } else {
3275 codewhale_engine::route_billing::UsageChip::Unknown(reasons)
3276 };
3277 }
3278 if unpriced > 0 {
3279 return if displayed.is_finite() && displayed > 0.0 {
3280 codewhale_engine::route_billing::UsageChip::PricedSubtotal {
3281 amount: self.format_cost_amount(displayed),
3282 legacy: false,
3283 reasons,
3284 }
3285 } else {
3286 codewhale_engine::route_billing::UsageChip::Unknown(reasons)
3287 };
3288 }
3289 if priced > 0 {
3290 return if displayed.is_finite() && displayed > 0.0 {
3291 codewhale_engine::route_billing::UsageChip::Money(
3292 self.format_cost_amount(displayed),
3293 )
3294 } else {
3295 codewhale_engine::route_billing::UsageChip::Hidden
3296 };
3297 }
3298 codewhale_engine::route_billing::usage_chip(
3299 self.billing_presentation,
3300 self.api_provider,
3301 &self.model,
3302 displayed,
3303 self.cost_display_currency(self.cost_currency),
3304 None,
3305 )
3306 }
3307
3308 /// Record that the session is now using `provider` / `model`, so the
3309 /// picker's recent section reflects it before any session is saved.
3310 pub fn note_route_used(&mut self, provider: &str, model: &str) {
3311 if let Ok(mut usage) = self.route_usage.write() {
3312 usage.record(provider, model, chrono::Utc::now());
3313 }
3314 }
3315
3316 /// Advance and return the model-draft generation. Call when a draft is
3317 /// requested or a setup/fleet wizard opens; a spawned draft that captured
3318 /// an older generation is dropped on delivery.
3319 pub fn next_draft_gen(&self) -> u64 {
3320 self.draft_gen
3321 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
3322 + 1
3323 }
3324
3325 /// The current model-draft generation (delivery compares against this).
3326 #[must_use]
3327 pub fn current_draft_gen(&self) -> u64 {
3328 self.draft_gen.load(std::sync::atomic::Ordering::SeqCst)
3329 }
3330
3331 /// Cap on the session turn-cache history. Holds enough turns to debug a long
3332 /// session without being so large the on-screen `/cache` table wraps.
3333 pub const TURN_CACHE_HISTORY_CAP: usize = 50;
3334
3335 /// Append a per-turn cache-telemetry record, trimming the oldest entry once
3336 /// the ring exceeds [`Self::TURN_CACHE_HISTORY_CAP`].
3337 pub fn push_turn_cache_record(&mut self, record: TurnCacheRecord) {
3338 self.session.turn_cache_history.push_back(record);
3339 while self.session.turn_cache_history.len() > Self::TURN_CACHE_HISTORY_CAP {
3340 self.session.turn_cache_history.pop_front();
3341 }
3342 }
3343
3344 pub(crate) fn clear_model_scoped_telemetry(&mut self) {
3345 self.session.last_prompt_tokens = None;
3346 self.last_billed_input_tokens = None;
3347 self.clear_context_pressure_sticky_status();
3348 self.session.last_completion_tokens = None;
3349 self.session.last_prompt_cache_hit_tokens = None;
3350 self.session.last_prompt_cache_miss_tokens = None;
3351 self.session.last_reasoning_replay_tokens = None;
3352 self.session.turn_cache_history.clear();
3353 self.pending_turn_route = None;
3354 self.pending_auto_route_receipt = None;
3355 self.active_turn = None;
3356 self.last_effective_model = None;
3357 self.last_effective_budget = None;
3358 self.last_effective_provider = None;
3359 self.last_effective_provider_identity = None;
3360 self.last_auto_route_receipt = None;
3361 self.last_pinned_prefix_hash = None;
3362 self.prefix_pin_reason = None;
3363 self.prefix_last_miss_reason = None;
3364 self.prefix_drift_count = 0;
3365 self.prefix_context_updates = 0;
3366 }
3367
3368 /// Invalidate facts that were accepted under the previous reasoning
3369 /// request.
3370 ///
3371 /// A fixed model keeps the same concrete route when its reasoning tier
3372 /// changes, so only its effective-reasoning receipt becomes stale. Under
3373 /// Auto, reasoning is one of the classifier inputs; the previous concrete
3374 /// provider/model route therefore cannot be replayed or displayed as the
3375 /// route for the new request.
3376 pub(crate) fn invalidate_route_receipts_for_reasoning_change(&mut self) {
3377 self.last_effective_reasoning_effort = None;
3378 if self.auto_model {
3379 self.last_effective_model = None;
3380 self.last_effective_budget = None;
3381 self.last_effective_provider = None;
3382 self.last_effective_provider_identity = None;
3383 self.last_auto_route_receipt = None;
3384 }
3385 }
3386
3387 pub fn tr(&self, id: MessageId) -> Cow<'static, str> {
3388 tr(self.ui_locale, id)
3389 }
3390
3391 pub(crate) fn discover_cached_skills(
3392 workspace: &std::path::Path,
3393 skills_dir: &std::path::Path,
3394 config: &codewhale_runtime::config::SkillsConfig,
3395 plugins: &codewhale_plugins::PluginRegistry,
3396 ) -> Vec<(String, String)> {
3397 codewhale_skills::discover_for_workspace(workspace, Some(skills_dir), config, Some(plugins))
3398 .into_enabled()
3399 .list()
3400 .iter()
3401 .filter(|s| s.invocation.user_invocable())
3402 .map(|s| (s.name.clone(), s.user_menu_description()))
3403 .collect()
3404 }
3405
3406 pub(crate) fn extension_plugin_view(
3407 &self,
3408 ) -> std::sync::Arc<codewhale_plugins::PluginRegistry> {
3409 codewhale_engine::extension_host::caller_view(
3410 &self.workspace,
3411 self.current_session_id.as_deref(),
3412 self.agent_focus
3413 .as_ref()
3414 .map(|focus| focus.agent_id.as_str()),
3415 )
3416 .unwrap_or_else(|| std::sync::Arc::clone(&self.plugin_registry))
3417 }
3418
3419 pub fn refresh_skill_cache(&mut self) {
3420 codewhale_skills::clear_skill_discovery_cache();
3421 let skills_dir = self.skills_dir.clone();
3422 let cached_skills = Self::discover_cached_skills(
3423 &self.workspace,
3424 &skills_dir,
3425 &self.skills_config,
3426 self.extension_plugin_view().as_ref(),
3427 );
3428 self.install_skill_cache(cached_skills);
3429 }
3430
3431 pub(crate) fn skill_cache_scope(&self, epoch: u64) -> SkillCacheScope {
3432 SkillCacheScope {
3433 epoch,
3434 workspace: self.workspace.clone(),
3435 skills_dir: self.skills_dir.clone(),
3436 config: self.skills_config.clone(),
3437 plugins: self.extension_plugin_view(),
3438 }
3439 }
3440
3441 pub(crate) fn install_skill_cache_if_current(
3442 &mut self,
3443 scope: &SkillCacheScope,
3444 epoch: u64,
3445 cached_skills: Vec<(String, String)>,
3446 ) -> bool {
3447 if scope.epoch != epoch
3448 || scope.workspace != self.workspace
3449 || scope.skills_dir != self.skills_dir
3450 || !std::sync::Arc::ptr_eq(&scope.config, &self.skills_config)
3451 || !std::sync::Arc::ptr_eq(&scope.plugins, &self.extension_plugin_view())
3452 {
3453 return false;
3454 }
3455 self.install_skill_cache(cached_skills);
3456 self.needs_redraw = true;
3457 true
3458 }
3459
3460 pub(crate) fn install_skill_cache(&mut self, cached_skills: Vec<(String, String)>) {
3461 self.hotbar_actions.replace_skills(&cached_skills);
3462 self.cached_skills = cached_skills;
3463 }
3464
3465 /// Whether the onboarding provider picker should focus the saved route.
3466 /// A fresh home can already name a route in config. Only an unconfigured
3467 /// new user has the built-in default rather than a route to recover.
3468 pub(crate) fn onboarding_recovers_configured_route(&self) -> bool {
3469 self.onboarding_missing_key_recovery
3470 && (self.startup_route_configured || !self.onboarding_had_provider_step)
3471 }
3472
3473 pub fn finish_onboarding_without_feature_intro(&mut self) {
3474 if let Err(err) = crate::tui::onboarding::mark_onboarded() {
3475 tracing::warn!(error = %err, "onboarding marker write failed");
3476 let message = self
3477 .tr(MessageId::OnboardingMarkFailed)
3478 .replace("{error}", &err.to_string());
3479 self.add_message(HistoryCell::Error {
3480 message: message.clone(),
3481 severity: codewhale_error_taxonomy::ErrorSeverity::Error,
3482 code: None,
3483 });
3484 self.push_status_toast(message, StatusToastLevel::Error, None);
3485 self.needs_redraw = true;
3486 return;
3487 }
3488 self.onboarding = OnboardingState::None;
3489 self.needs_redraw = true;
3490 }
3491
3492 /// Show the one-time Fleet intro as a status line, the first time the
3493 /// user opens `/fleet` — never as a first-run push.
3494 /// It inserts no transcript message: a synthetic history cell would hide
3495 /// the empty launch surface before the user sends anything.
3496 pub fn maybe_show_feature_intro(&mut self) {
3497 if self.onboarding != OnboardingState::None {
3498 return;
3499 }
3500 // Never claim "setup is ready" when auth is still missing — e.g.
3501 // `--skip-onboarding` with no API key (#3985). Leave the flag unset so
3502 // the tip can appear after the user finishes provider setup.
3503 if self.onboarding_needs_api_key {
3504 return;
3505 }
3506 // One transaction: the "already shown?" read and the flag write must not
3507 // straddle another writer's whole-file save.
3508 let write = Settings::transact_opt(|settings| {
3509 if settings.feature_intro_shown {
3510 return Ok(None);
3511 }
3512 settings.feature_intro_shown = true;
3513 Ok(Some(()))
3514 });
3515 match write {
3516 Ok(None) => return,
3517 Ok(Some(())) => {}
3518 Err(err) => {
3519 tracing::warn!(error = %err, "feature intro flag write failed");
3520 let message = self
3521 .tr(MessageId::FeatureIntroFlagSaveFailed)
3522 .replace("{error}", &err.to_string());
3523 self.show_command_result(message, StatusToastLevel::Error);
3524 return;
3525 }
3526 }
3527 self.show_command_result(
3528 self.tr(MessageId::FleetReadyNotice).into_owned(),
3529 StatusToastLevel::Success,
3530 );
3531 self.needs_redraw = true;
3532 }
3533
3534 /// Apply a locale tag selected from the onboarding language picker (#566).
3535 /// Persists the value to settings.toml and immediately
3536 /// re-resolves `ui_locale` so the rest of onboarding renders in the new
3537 /// language. `App` doesn't keep `Settings` resident — it loads on entry
3538 /// and rewrites on exit, mirroring the pattern used by the `/config`
3539 /// surface.
3540 pub fn set_locale_from_onboarding(&mut self, tag: &str) -> anyhow::Result<()> {
3541 let locale = Settings::transact(|settings| {
3542 settings.set("locale", tag)?;
3543 Ok(settings.locale.clone())
3544 })?;
3545 self.ui_locale = codewhale_localization::resolve_locale(&locale);
3546 self.needs_redraw = true;
3547 Ok(())
3548 }
3549
3550 /// Locale tag currently persisted in settings.toml (or
3551 /// `"auto"` when no settings file exists). Used by the onboarding
3552 /// language picker to highlight the current selection without `App`
3553 /// having to keep `Settings` resident.
3554 pub fn current_locale_tag(&self) -> String {
3555 Settings::load()
3556 .map(|s| s.locale)
3557 .unwrap_or_else(|_| "auto".to_string())
3558 }
3559
3560 pub fn set_mode(&mut self, mode: AppMode) -> bool {
3561 let previous_mode = self.mode;
3562 if previous_mode == mode && !self.yolo {
3563 return false;
3564 }
3565 let permission_before = self.permission_receipt_label();
3566
3567 self.mode = mode;
3568 // Mode chip lives in the header — skip redundant status/toast copy.
3569
3570 // Mode cycling is untangled from permission policy (#3386). The user
3571 // only edits the durable permission surface while in Agent mode, so
3572 // refresh the baseline from the live mirrors whenever we leave Agent —
3573 // before any transient Plan/YOLO policy overwrites them. This subsumes
3574 // the old per-mode `YoloRestoreState`/`PlanRestoreState` snapshots:
3575 // cross-mode hops (Plan -> YOLO, YOLO -> Plan) do not touch the baseline,
3576 // so YOLO's elevated authority never bleeds into the restored Agent
3577 // surface (#3279).
3578 if previous_mode.uses_agent_baseline() && !self.yolo {
3579 self.mode_prefs = ModeSessionPrefs {
3580 agent_allow_shell: self.allow_shell,
3581 agent_trust_mode: self.trust_mode,
3582 agent_approval_mode: self.approval_mode,
3583 };
3584 }
3585
3586 let policy = base_policy_for_mode(mode, &self.mode_prefs);
3587 self.allow_shell = policy.allow_shell;
3588 self.trust_mode = policy.trust_mode;
3589 self.approval_mode = policy.approval_mode;
3590 self.yolo = matches!(policy.approval_mode, ApprovalMode::Bypass);
3591
3592 self.finish_mode_change(previous_mode, &permission_before);
3593 true
3594 }
3595
3596 /// Shared tail of every mode transition: ModeChange hooks plus redraw.
3597 /// Built from `base_hook_context` so this event carries the same session
3598 /// id, workspace, model, and token total as every other event — it used
3599 /// to omit `DEEPSEEK_SESSION_ID` entirely, which made mode transitions
3600 /// uncorrelatable with the session they belonged to.
3601 fn finish_mode_change(&mut self, previous_mode: AppMode, permission_before: &str) {
3602 let context = self
3603 .base_hook_context()
3604 .with_mode(self.mode.hook_label())
3605 .with_previous_mode(previous_mode.hook_label());
3606 if let Err(error) = self.submit_hooks(HookEvent::ModeChange, context) {
3607 self.surface_observer_hook_submission_failure(error);
3608 }
3609 self.record_permission_change(permission_before);
3610 self.needs_redraw = true;
3611 }
3612
3613 /// Apply a *user-facing* mode selection: change the live session mode and
3614 /// persist it as the startup default.
3615 ///
3616 /// This is the difference between [`Self::set_mode`] and this method.
3617 /// `set_mode` is the session-only primitive — session restore and preset
3618 /// application use it because they are re-installing a mode the user
3619 /// already chose elsewhere, and re-persisting there would let a restored
3620 /// session silently rewrite the startup default. Every interactive
3621 /// selector (the Shift+Tab permission dial, the Alt+A/P shortcuts, the
3622 /// hotbar mode actions) goes through here instead, so "I switched to Plan"
3623 /// survives a restart (reported by Hunter against v0.9.1).
3624 ///
3625 /// The write is queued, not performed here: it is ordered behind every
3626 /// earlier selection by [`StartupDefaultsWriter`], and a failure surfaces
3627 /// through [`Self::drain_startup_default_failures`] rather than being
3628 /// dropped.
3629 ///
3630 /// What is persisted is `self.mode` — the mode `set_mode` actually
3631 /// installed — not the requested enum.
3632 ///
3633 /// The outcome is typed, not a bool, so callers can tell a live change
3634 /// from a selection that only saved the startup default:
3635 ///
3636 /// - [`SettingSelection::Changed`] — live mode moved *and* the startup
3637 /// default was queued.
3638 /// - [`SettingSelection::PersistedSame`] — live mode was already the
3639 /// requested one, but the startup default was still queued. This is a
3640 /// real, reportable action: after a session restore the live mode and the
3641 /// startup default routinely disagree.
3642 ///
3643 /// Mode is not turn-locked: a change during a running turn is sent to the
3644 /// engine, which applies it at its next step boundary in that turn.
3645 ///
3646 /// [`StartupDefaultsWriter`]: crate::tui::startup_defaults::StartupDefaultsWriter
3647 pub fn select_mode(&mut self, mode: AppMode) -> SettingSelection {
3648 let changed = self.set_mode(mode);
3649 // Persist an explicit selection even when it matches the live mode.
3650 // A restored session can be Plan while the startup default remains
3651 // Work; choosing Plan again is a request to make the visible state
3652 // durable, not a no-op.
3653 self.startup_defaults
3654 .spawn(crate::tui::startup_defaults::StartupDefaults::mode(
3655 self.mode,
3656 ));
3657 if changed {
3658 SettingSelection::Changed
3659 } else {
3660 SettingSelection::PersistedSame
3661 }
3662 }
3663
3664 /// The receipt for an accepted selection that did not move live state.
3665 ///
3666 /// Without it a same-live selection is indistinguishable from a refusal on
3667 /// screen, even though it wrote the file the user was trying to change.
3668 #[must_use]
3669 pub fn mode_startup_default_receipt(&self, mode: AppMode) -> String {
3670 self.tr(MessageId::ModeAlreadyActiveSavedAsDefault)
3671 .replace("{mode}", &mode.display_name_localized(self.ui_locale))
3672 }
3673
3674 /// Surface any startup-default write that failed since the last drain.
3675 /// Called once per event-loop iteration.
3676 pub fn drain_startup_default_failures(&mut self) {
3677 for failure in self.startup_defaults.drain_failures() {
3678 let message = self.startup_default_failure_message(&failure);
3679 self.push_status_toast(message, StatusToastLevel::Warning, Some(8_000));
3680 }
3681 }
3682
3683 /// Translate a typed startup-default failure at the locale boundary.
3684 ///
3685 /// The writer runs on a blocking pool and knows nothing about the user's
3686 /// locale, so it reports `StartupDefaultSubject` values and a path-free
3687 /// detail. Turning those into a sentence is this side's job.
3688 #[must_use]
3689 pub fn startup_default_failure_message(
3690 &self,
3691 failure: &crate::tui::startup_defaults::StartupDefaultFailure,
3692 ) -> String {
3693 use crate::tui::startup_defaults::StartupDefaultSubject;
3694
3695 let subject = if failure.subjects.is_empty() {
3696 self.tr(MessageId::StartupDefaultSubjectAll).into_owned()
3697 } else {
3698 failure
3699 .subjects
3700 .iter()
3701 .map(|subject| {
3702 self.tr(match subject {
3703 StartupDefaultSubject::Mode => MessageId::StartupDefaultSubjectMode,
3704 StartupDefaultSubject::Thinking => MessageId::StartupDefaultSubjectThinking,
3705 StartupDefaultSubject::PetMode => MessageId::ConfigLabelPetMode,
3706 StartupDefaultSubject::WhaleName => MessageId::ConfigLabelWhaleName,
3707 StartupDefaultSubject::WhaleColor => MessageId::ConfigLabelWhaleColor,
3708 })
3709 .into_owned()
3710 })
3711 .collect::<Vec<_>>()
3712 // A separator, not a word: composed in code per the crate's
3713 // localization rules.
3714 .join(" + ")
3715 };
3716 self.tr(MessageId::StartupDefaultNotSaved)
3717 .replace("{setting}", &subject)
3718 .replace("{error}", &failure.detail)
3719 }
3720
3721 fn notify_yolo_compat_once(&mut self) {
3722 if self.yolo_compat_notified {
3723 return;
3724 }
3725 self.yolo_compat_notified = true;
3726 // Per-install suppression: check the persisted flag so the toast
3727 // appears exactly once across sessions, not every launch.
3728 if let Ok(settings) = codewhale_runtime::settings::Settings::load()
3729 && settings.yolo_deprecation_shown
3730 {
3731 return;
3732 }
3733 // Persist the flag best-effort; toast still fires even if the write
3734 // fails (retries on the next attempt).
3735 let _ = codewhale_runtime::settings::Settings::transact(|settings| {
3736 settings.yolo_deprecation_shown = true;
3737 Ok(())
3738 });
3739 self.push_status_toast(
3740 "Legacy full-access mode is deprecated — use Work + Full Access (Shift+Tab)"
3741 .to_string(),
3742 StatusToastLevel::Warning,
3743 Some(8_000),
3744 );
3745 }
3746
3747 fn notify_operate_retired_once(&mut self) {
3748 if self.operate_retired_notified {
3749 return;
3750 }
3751 self.operate_retired_notified = true;
3752 if let Ok(settings) = codewhale_runtime::settings::Settings::load()
3753 && settings.operate_deprecation_shown
3754 {
3755 return;
3756 }
3757 let _ = codewhale_runtime::settings::Settings::transact(|settings| {
3758 settings.operate_deprecation_shown = true;
3759 Ok(())
3760 });
3761 self.push_status_toast(
3762 "Operate mode was retired — this session starts in Work; /fleet runs parallel agents"
3763 .to_string(),
3764 StatusToastLevel::Info,
3765 Some(10_000),
3766 );
3767 }
3768
3769 pub(crate) fn notify_account_preferences_not_loaded(&mut self) {
3770 let sign_in = account_sign_in_marker(self.config_profile.as_deref());
3771 self.notify_account_preferences_not_loaded_for(&sign_in);
3772 }
3773
3774 fn notify_account_preferences_not_loaded_for(&mut self, sign_in: &str) {
3775 let first_for_sign_in = Settings::transact_opt(|settings| {
3776 if settings.account_preferences_notice_shown.as_deref() == Some(sign_in) {
3777 return Ok(None);
3778 }
3779 settings.account_preferences_notice_shown = Some(sign_in.to_string());
3780 Ok(Some(()))
3781 });
3782 if matches!(first_for_sign_in, Ok(None)) {
3783 return;
3784 }
3785 let text = self
3786 .tr(MessageId::AccountPreferencesNotLoaded)
3787 .replace("{command}", "codewhale login");
3788 self.push_status_toast_record(StatusToast::standing(
3789 text,
3790 StatusToastLevel::Warning,
3791 ACCOUNT_PREFERENCES_NOTICE,
3792 ));
3793 }
3794
3795 pub(crate) fn dismiss_account_preferences_notice(&mut self) -> bool {
3796 let before = self.status_toasts.len();
3797 self.retire_event_notices(ACCOUNT_PREFERENCES_NOTICE);
3798 self.status_toasts.len() != before
3799 }
3800
3801 pub(crate) fn refresh_agent_approved_plugins_notice(&mut self) {
3802 self.retire_event_notices(AGENT_APPROVED_PLUGINS_NOTICE);
3803 let names = active_agent_approved_plugin_names(&self.plugin_registry);
3804 if names.is_empty() {
3805 return;
3806 }
3807 let text = self
3808 .tr(MessageId::CmdPluginAuditSessionNotice)
3809 .replace("{names}", &names.join(", "));
3810 self.push_status_toast_record(StatusToast::standing(
3811 text,
3812 StatusToastLevel::Warning,
3813 AGENT_APPROVED_PLUGINS_NOTICE,
3814 ));
3815 }
3816
3817 /// One-release migration notice for the Shift+Tab/Ctrl+T rebinding: users
3818 /// pressing Shift+Tab expecting the old thinking cycle land here first.
3819 fn notify_keybinding_migration_once(&mut self) {
3820 if self.keybinding_migration_notified {
3821 return;
3822 }
3823 self.keybinding_migration_notified = true;
3824 self.push_status_toast(
3825 "Shift+Tab now cycles permissions — reasoning effort moved to Ctrl+T".to_string(),
3826 StatusToastLevel::Info,
3827 Some(8_000),
3828 );
3829 }
3830
3831 /// Whether a route setting is locked because a turn is in flight.
3832 ///
3833 /// While `is_loading`, the model, provider and thinking the engine is
3834 /// acting on must not shift underneath it, so those changes are refused
3835 /// (#2982). Mode and permissions are not locked: the engine applies them
3836 /// at its next step boundary in the same turn. Returns true (and posts a concise status message) if
3837 /// the change should be rejected — the caller leaves the selection unchanged
3838 /// so the chip "twitches" back instead of moving.
3839 ///
3840 /// `subject` is a `MessageId`, not a `&str`, so the refusal is translated
3841 /// as one sentence in the user's locale instead of splicing an English noun
3842 /// into a translated template.
3843 pub(crate) fn reject_setting_change_while_busy(&mut self, subject: MessageId) -> bool {
3844 if self.is_loading {
3845 let message = self.setting_locked_message(subject);
3846 self.show_command_result(message, StatusToastLevel::Warning);
3847 self.needs_redraw = true;
3848 true
3849 } else {
3850 false
3851 }
3852 }
3853
3854 /// The localized "locked while a turn is running" sentence for `subject`.
3855 #[must_use]
3856 pub(crate) fn setting_locked_message(&self, subject: MessageId) -> String {
3857 self.tr(MessageId::SettingLockedDuringTurn)
3858 .replace("{setting}", self.tr(subject).as_ref())
3859 }
3860
3861 /// Show the startup-default receipt for a selection that did not move live
3862 /// mode. `Changed` and `Refused` already have their own messaging (the mode
3863 /// chip, and `reject_setting_change_while_busy` respectively).
3864 pub(crate) fn report_mode_selection(&mut self, mode: AppMode, outcome: SettingSelection) {
3865 if outcome == SettingSelection::PersistedSame {
3866 let receipt = self.mode_startup_default_receipt(mode);
3867 self.show_command_result(receipt, StatusToastLevel::Success);
3868 self.needs_redraw = true;
3869 }
3870 }
3871
3872 /// Cycle reasoning-effort through the active route's distinct tiers.
3873 ///
3874 /// Typed for the same reason as [`Self::select_mode`]: a bool could not tell
3875 /// the hotbar whether the turn lock refused the action or the provider
3876 /// simply exposes a single tier.
3877 pub fn cycle_effort(&mut self) -> SettingSelection {
3878 self.cycle_effort_checked()
3879 .unwrap_or(SettingSelection::Refused)
3880 }
3881
3882 pub(crate) fn cycle_effort_checked(&mut self) -> Result<SettingSelection, String> {
3883 if self.reject_setting_change_while_busy(MessageId::SettingSubjectThinking) {
3884 return Ok(SettingSelection::Refused);
3885 }
3886 let previous = self.reasoning_effort;
3887 self.apply_reasoning_effort_cycle()?;
3888 if self.reasoning_effort == previous {
3889 Ok(SettingSelection::PersistedSame)
3890 } else {
3891 Ok(SettingSelection::Changed)
3892 }
3893 }
3894
3895 /// Advance reasoning effort to the next tier for the active route and
3896 /// surface the change: set a status message and refresh the compaction
3897 /// budget. Auto routing and concrete models alike walk the same ladder as
3898 /// `/model` and `/effort`. Shared by the Ctrl+T shortcut (`cycle_effort`) and the
3899 /// hotbar `reasoning.cycle` action so the two paths cannot drift.
3900 pub(crate) fn apply_reasoning_effort_cycle(&mut self) -> Result<(), String> {
3901 let requested = self.next_reasoning_effort_for_active_route();
3902 self.commit_reasoning_effort_checked(requested)
3903 }
3904
3905 fn next_reasoning_effort_for_active_route(&self) -> ReasoningEffort {
3906 let (provider, base_url, model) = match self.active_reasoning_route_truth() {
3907 Some((provider, _, endpoint, model)) => (provider, endpoint, model),
3908 None => (
3909 self.api_provider,
3910 self.active_route_base_url.as_str(),
3911 self.model.as_str(),
3912 ),
3913 };
3914 // The exact ladder the `/model` picker shows for this route, Auto
3915 // routing included (#6650). On a concrete route every rung is a
3916 // distinct effective tier; under Auto routing the tier is decided at
3917 // dispatch, so neighbouring preferences may still resolve to one tier.
3918 let efforts = crate::tui::model_picker::picker_efforts_for_route(
3919 provider,
3920 base_url,
3921 model,
3922 self.auto_model,
3923 );
3924 // A persisted value the ladder dropped as an alias (DeepSeek `medium`)
3925 // enters at the rung it already resolves to, so the first press moves
3926 // past it instead of re-selecting the same effective tier.
3927 let current = self.reasoning_effort;
3928 let anchor = if self.auto_model || efforts.contains(&current) {
3929 current
3930 } else {
3931 let tier = crate::tui::model_picker::effective_tier_for_route(
3932 current, provider, base_url, model,
3933 );
3934 if efforts.contains(&tier) {
3935 tier
3936 } else {
3937 current
3938 }
3939 };
3940 anchor.cycle_next_in(&efforts)
3941 }
3942
3943 pub(crate) fn commit_reasoning_effort(&mut self, requested: ReasoningEffort) {
3944 let _ = self.commit_reasoning_effort_checked(requested);
3945 }
3946
3947 pub(crate) fn commit_reasoning_effort_checked(
3948 &mut self,
3949 requested: ReasoningEffort,
3950 ) -> Result<(), String> {
3951 let effective = self.effective_reasoning_effort_for_active_route(requested);
3952 let route_truth = self.active_reasoning_route_truth();
3953 let provider_kind = route_truth.map_or(self.api_provider, |(provider, _, _, _)| provider);
3954 let provider = route_truth.map_or_else(
3955 || self.provider_identity_for_persistence().to_string(),
3956 |(_, provider_identity, _, _)| provider_identity.to_string(),
3957 );
3958 let endpoint_identity = route_truth.map(|(_, _, endpoint, _)| {
3959 codewhale_engine::route_receipt::endpoint_identity(endpoint)
3960 });
3961 let model = route_truth.map(|(_, _, _, model)| model.to_string());
3962 if let Some(work) = self.runtime_services.work.clone()
3963 && let Err(err) = work.record_reasoning_effort_change(
3964 self.current_session_id.as_deref(),
3965 requested.into(),
3966 effective.into(),
3967 provider_kind,
3968 &provider,
3969 endpoint_identity.as_deref(),
3970 model.as_deref(),
3971 )
3972 {
3973 let msg = format!("Reasoning effort unchanged: Work receipt failed ({err})");
3974 self.show_command_result(msg.clone(), StatusToastLevel::Error);
3975 self.needs_redraw = true;
3976 return Err(msg);
3977 }
3978 self.reasoning_effort = requested;
3979 self.reasoning_effort_preference = Some(requested);
3980 self.invalidate_route_receipts_for_reasoning_change();
3981 // Same persistence owner as the model/effort pickers, so Ctrl+T and the
3982 // hotbar `reasoning.cycle` action restore on restart exactly like a
3983 // picker selection does. Only the *requested* tier is persisted — the
3984 // effective tier is a per-turn route fact, not a user preference.
3985 self.startup_defaults.spawn(
3986 crate::tui::startup_defaults::StartupDefaults::reasoning_effort(requested.as_setting()),
3987 );
3988 self.update_model_compaction_budget();
3989 self.show_command_result(
3990 format!(
3991 "Reasoning effort: {}",
3992 Self::reasoning_effort_resolution_label(requested, effective, self.api_provider)
3993 ),
3994 StatusToastLevel::Info,
3995 );
3996 self.needs_redraw = true;
3997 Ok(())
3998 }
3999
4000 #[must_use]
4001 pub fn permission_dial_next(&self) -> (AppMode, ApprovalMode) {
4002 if self.mode == AppMode::Plan {
4003 return (
4004 AppMode::Agent,
4005 if self.auto_review_disabled {
4006 ApprovalMode::Bypass
4007 } else {
4008 ApprovalMode::Auto
4009 },
4010 );
4011 }
4012 match self.approval_mode {
4013 ApprovalMode::AcceptEdits => (AppMode::Plan, ApprovalMode::AcceptEdits),
4014 current => (
4015 AppMode::Agent,
4016 current.cycle_permission_next_with_auto_review(self.auto_review_disabled),
4017 ),
4018 }
4019 }
4020
4021 pub fn step_permission_dial(&mut self, root_control: bool) -> DialStep {
4022 let (mode, posture) = self.permission_dial_next();
4023 let current_posture = if self.mode == AppMode::Plan {
4024 self.mode_prefs.agent_approval_mode
4025 } else {
4026 self.approval_mode
4027 };
4028 let was_auto = self.mode_prefs.agent_approval_mode == ApprovalMode::Auto
4029 || self.approval_mode == ApprovalMode::Auto;
4030 let permission_before = self.permission_receipt_label();
4031 self.permission_receipt_deferred = true;
4032 let mut step = DialStep::default();
4033 if mode != self.mode {
4034 step.mode_changed = self.select_mode(mode) == SettingSelection::Changed;
4035 }
4036 if posture != current_posture {
4037 step.posture_changed = if root_control {
4038 self.select_root_approval_posture(posture)
4039 } else {
4040 self.select_approval_posture(posture)
4041 };
4042 let posture_locked = if root_control {
4043 !self.approval_policy_root_editable
4044 } else {
4045 self.approval_policy_locked()
4046 };
4047 if !step.posture_changed && !step.mode_changed && posture_locked {
4048 step.mode_changed = self.select_mode(AppMode::Plan) == SettingSelection::Changed;
4049 }
4050 }
4051 self.permission_receipt_deferred = false;
4052 self.record_permission_change(&permission_before);
4053 if !was_auto
4054 && (self.approval_mode == ApprovalMode::Auto
4055 || self.mode_prefs.agent_approval_mode == ApprovalMode::Auto)
4056 && self.has_suspended_broad_allows()
4057 {
4058 self.emit_auto_review_broad_allows_paused_note();
4059 }
4060 step
4061 }
4062
4063 /// Set the durable Agent permission posture.
4064 pub fn select_approval_posture(&mut self, next: ApprovalMode) -> bool {
4065 if next == ApprovalMode::Auto && self.auto_review_disabled {
4066 self.push_status_toast(
4067 "Auto-Review is disabled by managed configuration (`auto_review.disabled = true`)"
4068 .to_string(),
4069 StatusToastLevel::Warning,
4070 Some(6_000),
4071 );
4072 self.needs_redraw = true;
4073 return false;
4074 }
4075 if self.approval_policy_locked() {
4076 self.push_status_toast(
4077 "Permissions are controlled by config or managed requirements".to_string(),
4078 StatusToastLevel::Warning,
4079 Some(6_000),
4080 );
4081 self.needs_redraw = true;
4082 return false;
4083 }
4084 if let Err(err) = Self::persist_permission_posture(next) {
4085 self.push_status_toast(
4086 format!("Permissions were not changed: could not save TUI posture ({err})"),
4087 StatusToastLevel::Warning,
4088 Some(8_000),
4089 );
4090 self.needs_redraw = true;
4091 return false;
4092 }
4093 self.finish_approval_posture_change(next);
4094 true
4095 }
4096
4097 /// Set permissions when the only controlling source is the user's
4098 /// editable root `config.toml` key. Shift+Tab is an explicit request to
4099 /// adopt the TUI posture, so persist the next setting first, then remove
4100 /// the shadowing root key. Roll back the setting if that removal fails.
4101 pub fn select_root_approval_posture(&mut self, next: ApprovalMode) -> bool {
4102 if next == ApprovalMode::Auto && self.auto_review_disabled {
4103 self.push_status_toast(
4104 "Auto-Review is disabled by managed configuration (`auto_review.disabled = true`)"
4105 .to_string(),
4106 StatusToastLevel::Warning,
4107 Some(6_000),
4108 );
4109 self.needs_redraw = true;
4110 return false;
4111 }
4112 if !self.approval_policy_root_editable {
4113 self.push_status_toast(
4114 "Permissions are controlled by a non-editable policy source".to_string(),
4115 StatusToastLevel::Warning,
4116 Some(6_000),
4117 );
4118 self.needs_redraw = true;
4119 return false;
4120 }
4121
4122 if let Err(reason) = self.adopt_root_approval_posture(next) {
4123 self.push_status_toast(
4124 format!("Permissions were not changed: {reason}"),
4125 StatusToastLevel::Warning,
4126 Some(8_000),
4127 );
4128 self.needs_redraw = true;
4129 return false;
4130 }
4131
4132 true
4133 }
4134
4135 /// Save a real TUI permission posture and release the user-owned root
4136 /// `approval_policy` that would otherwise shadow it. This is shared by
4137 /// Shift+Tab and the config choice editor so both surfaces make the same
4138 /// atomic transition from raw policy tokens to the three product postures.
4139 pub(crate) fn adopt_root_approval_posture(&mut self, next: ApprovalMode) -> Result<(), String> {
4140 if !self.approval_policy_root_editable {
4141 return Err("the root approval policy is not editable".to_string());
4142 }
4143
4144 let active_config_path =
4145 codewhale_runtime::config::resolve_load_config_path(self.config_path.clone())
4146 .map_err(|error| error.to_string())?;
4147 // The posture commit, the root-key release, and the rollback are one
4148 // critical section. Two `Settings::transact` calls would expose the
4149 // uncommitted middle state — a concurrent writer (a queued startup-default
4150 // drain, say) could load the new posture, and the rollback save would then
4151 // also revert whatever that writer had committed in between.
4152 /// Why the critical section ended, carried out so every toast is
4153 /// pushed after the settings lock is released.
4154 enum RootPostureOutcome {
4155 Committed,
4156 Failed(String),
4157 }
4158
4159 let posture = Self::approval_posture_setting(next).to_string();
4160 let outcome = codewhale_runtime::settings::with_settings_transaction(|transaction| {
4161 let mut settings = match transaction.load() {
4162 Ok(settings) => settings,
4163 Err(err) => {
4164 return Ok(RootPostureOutcome::Failed(format!(
4165 "could not load TUI settings ({err})"
4166 )));
4167 }
4168 };
4169 let previous = settings.permission_posture.clone();
4170 settings.permission_posture = Some(posture);
4171 if let Err(err) = transaction.save(&settings) {
4172 return Ok(RootPostureOutcome::Failed(format!(
4173 "could not save TUI posture ({err})"
4174 )));
4175 }
4176
4177 if let Err(err) = codewhale_runtime::config_persistence::persist_unset_root_key(
4178 active_config_path.as_deref(),
4179 "approval_policy",
4180 ) {
4181 settings.permission_posture = previous;
4182 let rollback_note = transaction
4183 .save(&settings)
4184 .err()
4185 .map(|rollback| format!("; settings rollback also failed: {rollback}"))
4186 .unwrap_or_default();
4187 return Ok(RootPostureOutcome::Failed(format!(
4188 "could not release root config policy ({err}){rollback_note}"
4189 )));
4190 }
4191 Ok(RootPostureOutcome::Committed)
4192 })
4193 .unwrap_or_else(|err| {
4194 RootPostureOutcome::Failed(format!("could not lock TUI settings ({err})"))
4195 });
4196 if let RootPostureOutcome::Failed(reason) = outcome {
4197 return Err(reason);
4198 }
4199
4200 self.clear_saved_approval_policy_lock();
4201 self.finish_approval_posture_change(next);
4202 Ok(())
4203 }
4204
4205 fn approval_posture_setting(mode: ApprovalMode) -> &'static str {
4206 match mode {
4207 ApprovalMode::Suggest => "ask",
4208 ApprovalMode::AcceptEdits => "accept-edits",
4209 ApprovalMode::Auto => "auto-review",
4210 ApprovalMode::Bypass => "full-access",
4211 ApprovalMode::Never => "never",
4212 }
4213 }
4214
4215 /// Persist the Shift+Tab permission posture.
4216 ///
4217 /// Synchronous on purpose: `select_approval_posture` only moves the live
4218 /// posture if this succeeded, so the keystroke already required the write.
4219 /// It runs inside [`Settings::transact`] so it cannot interleave with a
4220 /// queued mode/thinking write — the two used to load the same bytes and the
4221 /// later save reverted the other's field.
4222 fn persist_permission_posture(next: ApprovalMode) -> anyhow::Result<()> {
4223 Settings::transact(|settings| {
4224 settings.permission_posture = Some(Self::approval_posture_setting(next).to_string());
4225 Ok(())
4226 })
4227 }
4228
4229 fn finish_approval_posture_change(&mut self, next: ApprovalMode) {
4230 let was_auto = self.mode_prefs.agent_approval_mode == ApprovalMode::Auto;
4231 self.set_agent_approval_posture(next);
4232 self.needs_redraw = true;
4233 // In Plan the new posture is real but dormant, and the footer chip
4234 // alone would imply it is live. Say when it starts applying instead of
4235 // refusing the change.
4236 if self.mode == AppMode::Plan {
4237 self.push_status_toast(
4238 format!(
4239 "Permissions set to {}. Plan stays Read Only; this applies in Work.",
4240 next.permission_chip_label()
4241 ),
4242 StatusToastLevel::Info,
4243 Some(5_000),
4244 );
4245 }
4246 if !self.permission_receipt_deferred
4247 && !was_auto
4248 && next == ApprovalMode::Auto
4249 && self.has_suspended_broad_allows()
4250 {
4251 self.emit_auto_review_broad_allows_paused_note();
4252 }
4253 // Footer permission chip is canonical — no status toast for the new
4254 // value, only the one-shot rebinding notice.
4255 self.notify_keybinding_migration_once();
4256 }
4257
4258 /// Replace the complete durable Act baseline and project it onto the live
4259 /// runtime when the current mode uses that baseline. Keeping these three
4260 /// fields together prevents setup presets from updating a live mirror while
4261 /// leaving the next Plan → Act transition stale.
4262 pub fn set_agent_runtime_baseline(
4263 &mut self,
4264 allow_shell: bool,
4265 trust_mode: bool,
4266 approval_mode: ApprovalMode,
4267 ) {
4268 self.mode_prefs = ModeSessionPrefs {
4269 agent_allow_shell: allow_shell,
4270 agent_trust_mode: trust_mode,
4271 agent_approval_mode: approval_mode,
4272 };
4273 if self.mode.uses_agent_baseline() {
4274 let policy = base_policy_for_mode(self.mode, &self.mode_prefs);
4275 self.allow_shell = policy.allow_shell;
4276 self.trust_mode = policy.trust_mode;
4277 self.approval_mode = policy.approval_mode;
4278 self.yolo = matches!(policy.approval_mode, ApprovalMode::Bypass);
4279 }
4280 }
4281
4282 #[must_use]
4283 pub(crate) fn agent_trust_baseline(&self) -> bool {
4284 self.mode_prefs.agent_trust_mode
4285 }
4286
4287 /// Update the durable Act shell choice without disturbing trust or
4288 /// approval. The live mirror changes only while Act owns the runtime.
4289 pub fn set_agent_shell_access(&mut self, allow_shell: bool) {
4290 self.set_agent_runtime_baseline(
4291 allow_shell,
4292 self.mode_prefs.agent_trust_mode,
4293 self.mode_prefs.agent_approval_mode,
4294 );
4295 }
4296
4297 #[must_use]
4298 pub fn has_suspended_broad_allows(&self) -> bool {
4299 !self
4300 .exec_policy_engine
4301 .suspended_broad_allow_descriptions()
4302 .is_empty()
4303 || !self.auto_review_broad_allow_warnings.is_empty()
4304 }
4305
4306 fn emit_auto_review_broad_allows_paused_note(&mut self) {
4307 let content = self
4308 .tr(MessageId::AutoReceiptBroadAllowsPaused)
4309 .into_owned();
4310 self.add_message(HistoryCell::System { content });
4311 self.needs_redraw = true;
4312 }
4313
4314 /// Host path for `/auto`: persist Auto-Review as the TUI permission
4315 /// posture without inventing a second runtime.
4316 pub fn apply_auto_review_posture(&mut self) -> Result<(), String> {
4317 self.apply_agent_posture_with_note(ApprovalMode::Auto, false)
4318 }
4319
4320 pub fn apply_cli_permission_mode(
4321 &mut self,
4322 permission_mode: Option<codewhale_engine::runtime_options::PermissionMode>,
4323 ) {
4324 let Some(permission_mode) = permission_mode else {
4325 return;
4326 };
4327 match permission_mode {
4328 codewhale_engine::runtime_options::PermissionMode::Plan => {
4329 self.set_mode(AppMode::Plan);
4330 }
4331 other => {
4332 if let Some(approval) = other.approval_mode() {
4333 if approval == ApprovalMode::Auto && self.auto_review_disabled {
4334 return;
4335 }
4336 if !self.approval_policy_requirements_managed
4337 && (!self.approval_policy_locked() || self.approval_policy_root_editable)
4338 {
4339 let was_auto = self.approval_mode == ApprovalMode::Auto;
4340 self.mode = AppMode::Agent;
4341 self.set_agent_approval_posture(approval);
4342 if !was_auto
4343 && self.approval_mode == ApprovalMode::Auto
4344 && self.has_suspended_broad_allows()
4345 {
4346 self.emit_auto_review_broad_allows_paused_note();
4347 }
4348 }
4349 }
4350 }
4351 }
4352 }
4353
4354 /// Persist `next` as the TUI permission posture. Same write as Shift+Tab
4355 /// landing on it; Plan stays read-only and only the Act baseline moves.
4356 /// Shared by `/auto` and the Plan hand-off.
4357 pub fn apply_agent_posture(&mut self, next: ApprovalMode) -> Result<(), String> {
4358 self.apply_agent_posture_with_note(next, true)
4359 }
4360
4361 fn apply_agent_posture_with_note(
4362 &mut self,
4363 next: ApprovalMode,
4364 emit_broad_allow_note: bool,
4365 ) -> Result<(), String> {
4366 if next == ApprovalMode::Auto && self.auto_review_disabled {
4367 return Err(
4368 "Auto-Review is disabled by managed configuration (`auto_review.disabled = true`)"
4369 .to_string(),
4370 );
4371 }
4372 if self.approval_policy_locked() {
4373 return Err("Permissions are controlled by config or managed requirements".to_string());
4374 }
4375 let was_auto = self.agent_approval_baseline() == ApprovalMode::Auto;
4376 Self::persist_permission_posture(next)
4377 .map_err(|err| format!("could not save TUI posture ({err})"))?;
4378 self.set_agent_approval_posture(next);
4379 if emit_broad_allow_note
4380 && !was_auto
4381 && next == ApprovalMode::Auto
4382 && self.has_suspended_broad_allows()
4383 {
4384 self.emit_auto_review_broad_allows_paused_note();
4385 }
4386 self.needs_redraw = true;
4387 Ok(())
4388 }
4389
4390 /// The durable Act permission posture, whichever mode is live.
4391 #[must_use]
4392 pub(crate) fn agent_approval_baseline(&self) -> ApprovalMode {
4393 self.mode_prefs.agent_approval_mode
4394 }
4395
4396 /// Update the durable Act approval choice. Entering Full Access enables
4397 /// trust mode; leaving it removes that implicit elevation while preserving
4398 /// an independently enabled trust baseline in other posture transitions.
4399 /// Plan remains read-only.
4400 pub fn set_agent_approval_posture(&mut self, next: ApprovalMode) {
4401 let permission_before = self.permission_receipt_label();
4402 let trust_mode = if next == ApprovalMode::Bypass {
4403 true
4404 } else if self.mode_prefs.agent_approval_mode == ApprovalMode::Bypass {
4405 false
4406 } else {
4407 self.mode_prefs.agent_trust_mode
4408 };
4409 self.set_agent_runtime_baseline(self.mode_prefs.agent_allow_shell, trust_mode, next);
4410 self.record_permission_change(&permission_before);
4411 }
4412
4413 pub fn sync_auto_review_paused_posture(&mut self, next: ApprovalMode) {
4414 let trust_mode = if next == ApprovalMode::Bypass {
4415 true
4416 } else if self.mode_prefs.agent_approval_mode == ApprovalMode::Bypass {
4417 false
4418 } else {
4419 self.mode_prefs.agent_trust_mode
4420 };
4421 self.revoke_approvable_auto_review_receipts();
4422 self.set_agent_runtime_baseline(self.mode_prefs.agent_allow_shell, trust_mode, next);
4423 if !self.approval_policy_locked()
4424 && let Err(err) = Self::persist_permission_posture(next)
4425 {
4426 tracing::warn!(%err, "failed to persist auto-review paused permission posture");
4427 let warning = format!(
4428 "Auto-Review paused for this session only: could not save TUI posture ({err}); previous posture will reload on restart"
4429 );
4430 self.add_message(HistoryCell::System {
4431 content: warning.clone(),
4432 });
4433 self.push_status_toast(warning, StatusToastLevel::Warning, Some(10_000));
4434 }
4435 self.needs_redraw = true;
4436 }
4437
4438 pub fn revoke_approvable_auto_review_receipts(&mut self) {
4439 for entry in &mut self.auto_review_blocked_receipts {
4440 if !entry.approved {
4441 entry.approvable = false;
4442 }
4443 }
4444 }
4445
4446 #[allow(clippy::too_many_arguments)]
4447 pub fn record_auto_review_blocked_receipt(
4448 &mut self,
4449 receipt_id: Option<String>,
4450 tool_id: String,
4451 tool_name: String,
4452 gate: String,
4453 verdict: String,
4454 rule: Option<String>,
4455 reason: String,
4456 call_digest: Option<String>,
4457 action_summary: String,
4458 ) {
4459 self.record_auto_review_blocked_receipt_for_agent(
4460 None,
4461 receipt_id,
4462 tool_id,
4463 tool_name,
4464 gate,
4465 verdict,
4466 rule,
4467 reason,
4468 call_digest,
4469 action_summary,
4470 );
4471 }
4472
4473 #[allow(clippy::too_many_arguments)]
4474 pub fn record_auto_review_blocked_receipt_for_agent(
4475 &mut self,
4476 agent_id: Option<String>,
4477 receipt_id: Option<String>,
4478 tool_id: String,
4479 tool_name: String,
4480 gate: String,
4481 verdict: String,
4482 rule: Option<String>,
4483 reason: String,
4484 call_digest: Option<String>,
4485 action_summary: String,
4486 ) {
4487 let approvable = agent_id.is_none()
4488 && receipt_id.as_deref().is_some_and(|id| !id.is_empty())
4489 && call_digest
4490 .as_deref()
4491 .is_some_and(|digest| !digest.is_empty());
4492 if let Some(ref id) = receipt_id
4493 && !id.is_empty()
4494 && self
4495 .auto_review_blocked_receipts
4496 .iter()
4497 .any(|entry| entry.receipt_id == *id)
4498 {
4499 return;
4500 }
4501 if self.auto_review_blocked_receipts.len() >= 100 {
4502 self.auto_review_blocked_receipts.remove(0);
4503 }
4504 self.auto_review_blocked_receipts.push(
4505 codewhale_engine::core::authority::auto_review::AutoReviewBlockedAction {
4506 receipt_id: receipt_id.unwrap_or_default(),
4507 call_digest: call_digest.unwrap_or_default(),
4508 tool_id,
4509 tool_name,
4510 action_summary,
4511 rule,
4512 reason,
4513 gate,
4514 verdict,
4515 approved: false,
4516 approvable,
4517 agent_id,
4518 },
4519 );
4520 }
4521
4522 pub fn mark_auto_review_receipt_approved(&mut self, target: &str) {
4523 if target.is_empty() {
4524 return;
4525 }
4526 for entry in &mut self.auto_review_blocked_receipts {
4527 if entry.receipt_id == target || entry.call_digest == target {
4528 entry.approved = true;
4529 }
4530 }
4531 }
4532
4533 #[must_use]
4534 pub(crate) fn effective_permission_label(&self) -> String {
4535 crate::tui::underwater::permission_label(self).into_owned()
4536 }
4537
4538 fn permission_receipt_label(&self) -> String {
4539 crate::tui::underwater::dial_chip_for(self.ui_locale, self.mode, self.approval_mode)
4540 .0
4541 .into_owned()
4542 }
4543
4544 fn record_permission_change(&mut self, before: &str) {
4545 if self.permission_receipt_deferred {
4546 return;
4547 }
4548 let after = self.permission_receipt_label();
4549 if after == before {
4550 return;
4551 }
4552 let content = self
4553 .tr(MessageId::PermissionsChangedReceipt)
4554 .replace("{label}", &after);
4555 self.add_message(HistoryCell::System { content });
4556 self.needs_redraw = true;
4557 }
4558
4559 #[must_use]
4560 pub fn approval_policy_locked(&self) -> bool {
4561 self.approval_policy_locked
4562 }
4563
4564 #[cfg(test)]
4565 #[must_use]
4566 pub fn approval_policy_requirements_managed(&self) -> bool {
4567 self.approval_policy_requirements_managed
4568 }
4569
4570 /// Session transitions must never detach live runtime producers. Late
4571 /// engine, compaction, purge, or background-task events could otherwise
4572 /// contaminate the replacement session after clear/load/new.
4573 #[must_use]
4574 pub fn session_transition_blocked(&self) -> bool {
4575 !self.session_transition_blockers().is_empty()
4576 }
4577
4578 /// Why a session transition is blocked, in operator terms. Empty means the
4579 /// transition is allowed; [`Self::session_transition_blocked`] derives from
4580 /// this same list so the gate and its explanation cannot drift.
4581 ///
4582 /// A dispatch still resolving its route, and a locally cancelled turn
4583 /// whose terminal event has not landed, both belong to this session:
4584 /// switching now would hand the next session a stale suppression that
4585 /// cancels its first turn, or a dispatch bound to the old one (U02-10).
4586 #[must_use]
4587 pub fn session_transition_blockers(&self) -> Vec<String> {
4588 let mut blockers = Vec::new();
4589 if self.pending_fresh_session.is_some() {
4590 blockers.push("a new session is awaiting Engine confirmation".to_string());
4591 }
4592
4593 let mut tasks: Vec<&TaskPanelEntry> = self
4594 .task_panel
4595 .iter()
4596 .filter(|task| matches!(task.status.as_str(), "queued" | "running"))
4597 .collect();
4598 let hidden = tasks.len().saturating_sub(MAX_TRANSITION_BLOCKER_TASKS);
4599 tasks.truncate(MAX_TRANSITION_BLOCKER_TASKS);
4600 blockers.extend(Self::transition_blocker_task_lines(&tasks));
4601 if hidden > 0 {
4602 blockers.push(format!("…and {hidden} more"));
4603 }
4604
4605 if self.is_loading {
4606 blockers.push("the session is still busy with the current turn".to_string());
4607 }
4608 if self.dispatch_in_flight {
4609 blockers.push("an earlier message is still resolving its route".to_string());
4610 }
4611 if self.suppress_stream_events_until_turn_complete {
4612 blockers.push("a cancelled turn is still settling".to_string());
4613 }
4614 if self.runtime_turn_status.as_deref() == Some("in_progress") {
4615 blockers.push("the runtime reports a turn in progress".to_string());
4616 }
4617 if self.is_compacting {
4618 blockers.push("context compaction is running".to_string());
4619 }
4620 if self.manual_compaction_queued {
4621 blockers.push("a manual compaction is queued".to_string());
4622 }
4623 if self.is_purging {
4624 blockers.push("session cleanup is running".to_string());
4625 }
4626 blockers
4627 }
4628
4629 /// One aligned row per blocking task, bounded to the transcript's content
4630 /// width. Every column but the summary is ASCII, so padding by character
4631 /// count matches the rendered width there; the summary is truncated by
4632 /// display width so CJK text cannot silently double the row.
4633 fn transition_blocker_task_lines(tasks: &[&TaskPanelEntry]) -> Vec<String> {
4634 let rows: Vec<(String, String, String, String)> = tasks
4635 .iter()
4636 .map(|task| {
4637 // `-` keeps the column present for rows without a duration,
4638 // the placeholder `format_task_list` already uses.
4639 let duration = task
4640 .duration_ms
4641 .map(codewhale_engine::agent_roster::format_duration)
4642 .unwrap_or_else(|| "-".to_string());
4643 // Panel summaries carry the `shell: ` prefix the Work rows
4644 // strip; a blocker row names the command, not its source kind.
4645 let command = task
4646 .prompt_summary
4647 .strip_prefix("shell: ")
4648 .unwrap_or(task.prompt_summary.as_str())
4649 .replace(['\n', '\r'], " ");
4650 // An owned shell names its owner: an unclaimed background
4651 // command is the case an operator most needs to identify.
4652 let summary = match task.owner_agent_name.as_deref() {
4653 Some(owner) if !owner.trim().is_empty() => {
4654 format!("(by {}) {}", owner.trim(), command.trim())
4655 }
4656 _ => command.trim().to_string(),
4657 };
4658 (task.id.clone(), task.status.clone(), duration, summary)
4659 })
4660 .collect();
4661 let id_width = rows
4662 .iter()
4663 .map(|row| row.0.chars().count())
4664 .max()
4665 .unwrap_or(0);
4666 let status_width = rows
4667 .iter()
4668 .map(|row| row.1.chars().count())
4669 .max()
4670 .unwrap_or(0);
4671 let duration_width = rows
4672 .iter()
4673 .map(|row| row.2.chars().count())
4674 .max()
4675 .unwrap_or(0);
4676 let fixed_width = id_width + 2 + status_width + 2 + duration_width + 2;
4677 let summary_width = TRANSITION_BLOCKER_LINE_WIDTH
4678 .saturating_sub(fixed_width)
4679 .max(MIN_TRANSITION_BLOCKER_SUMMARY_WIDTH);
4680 rows.iter()
4681 .map(|(id, status, duration, summary)| {
4682 let summary =
4683 codewhale_tui_kit::ui_text::truncate_line_to_width(summary, summary_width);
4684 format!(
4685 "{id:<id_width$} {status:<status_width$} {duration:<duration_width$} {summary}"
4686 )
4687 })
4688 .collect()
4689 }
4690
4691 /// Abandon a dispatch still resolving its route or waiting on engine
4692 /// admission (#6800). Its completion closure then arrives promptly, retires
4693 /// `dispatch_in_flight` and restores the unsent message through the normal
4694 /// dispatch-error path. A no-op when no dispatch is outstanding.
4695 pub fn cancel_in_flight_dispatch(&mut self) {
4696 crate::tui::ui::restore_preparing_steers(self);
4697 if let Some(cancel) = self.dispatch_cancel.take() {
4698 cancel.cancel();
4699 }
4700 }
4701
4702 /// Whether the interface is asking the user to make a decision. Ambient
4703 /// motion yields across the whole frame while this is true; freezing one
4704 /// task marker still leaves distracting movement in peripheral vision.
4705 #[must_use]
4706 pub fn attention_hold_active(&self) -> bool {
4707 !self.view_stack.is_empty()
4708 || self.pending_user_input_prompt.is_some()
4709 || self
4710 .task_panel
4711 .iter()
4712 .any(|task| matches!(task.status.as_str(), "waiting" | "needs_user"))
4713 }
4714
4715 pub fn mark_approval_policy_locked(&mut self) {
4716 self.approval_policy_locked = true;
4717 self.approval_policy_root_editable = true;
4718 }
4719
4720 pub fn clear_saved_approval_policy_lock(&mut self) {
4721 if !self.approval_policy_requirements_managed {
4722 self.approval_policy_locked = false;
4723 self.approval_policy_root_editable = false;
4724 }
4725 }
4726
4727 /// Submit observer hooks off the terminal event loop. Foreground in hook
4728 /// configuration still means ordered/awaited within the worker; it no
4729 /// longer means the UI waits on the child process.
4730 pub fn submit_hooks(&self, event: HookEvent, context: HookContext) -> Result<(), String> {
4731 self.hooks.submit_observer(event, context)
4732 }
4733
4734 /// Preserve a lost observer event independently of the ordinary status
4735 /// line. Agent lifecycle handlers immediately post a separate notice
4736 /// with their normal progress text, so a submission failure belongs in
4737 /// the toast queue instead of that transient slot.
4738 pub fn surface_observer_hook_submission_failure(&mut self, error: String) {
4739 tracing::warn!(target: "hooks", %error, "observer hook was not submitted");
4740 self.push_status_toast(error, StatusToastLevel::Error, Some(12_000));
4741 self.needs_redraw = true;
4742 }
4743
4744 /// Create a hook context with common fields pre-populated
4745 pub fn base_hook_context(&self) -> HookContext {
4746 HookContext::new()
4747 .with_caller(codewhale_engine::hooks::HookCaller {
4748 workspace: self.workspace.clone(),
4749 plugins: Some(self.extension_plugin_view()),
4750 session_id: self.current_session_id.clone(),
4751 agent_id: self
4752 .agent_focus
4753 .as_ref()
4754 .map(|focus| focus.agent_id.clone()),
4755 origin_turn_id: self.runtime_turn_id.clone(),
4756 origin_call_id: None,
4757 })
4758 .with_mode(self.mode.hook_label())
4759 .with_workspace(self.workspace.clone())
4760 .with_model(&self.model)
4761 .with_session_id(self.hooks.session_id())
4762 .with_tokens(self.session.total_tokens)
4763 }
4764
4765 /// Soft cap on [`Self::history`] length. When history exceeds this count,
4766 /// the oldest cells are folded into a single placeholder to bound memory
4767 /// and render cost (#399 S2). The cap is generous — 5000 cells is more
4768 /// than enough to keep the visible transcript intact across sessions.
4769 pub const HISTORY_SOFT_CAP: usize = 5_000;
4770
4771 /// Number of oldest cells to fold when the soft cap fires. Folding in
4772 /// batches amortizes the cost instead of triggering on every push.
4773 const HISTORY_FOLD_BATCH: usize = 1_000;
4774
4775 pub fn add_message(&mut self, msg: HistoryCell) {
4776 // An in-flight tool is bound to a *virtual* index, `history.len() +
4777 // entry_index`, resolved against `history.len()` at completion time.
4778 // Growing history here without re-basing those bindings makes each of
4779 // them silently mean a different cell, so the completion lands on the
4780 // wrong one and the real row spins forever (#5478 — reproduced by
4781 // `/rename` mid-turn, but every command that reports a message hits it).
4782 self.rebase_active_cell_bindings(1);
4783 let rev = self.fresh_history_revision();
4784 self.history.push(msg);
4785 self.history_revisions.push(rev);
4786 self.history_version = self.history_version.wrapping_add(1);
4787
4788 // Bound history length: when the soft cap fires, fold the oldest
4789 // batch into a single ArchivedContext placeholder.
4790 self.maybe_fold_history();
4791 let selection_has_range = self
4792 .viewport
4793 .transcript_selection
4794 .ordered_endpoints()
4795 .is_some_and(|(start, end)| start != end);
4796 if self.viewport.transcript_scroll.is_at_tail()
4797 && !self.viewport.transcript_selection.dragging
4798 && !selection_has_range
4799 && !self.user_scrolled_during_stream
4800 // While a worker's transcript owns the conversation area, its
4801 // pin governs the visible viewport: main-conversation activity
4802 // must not yank the user's read position in the focused
4803 // transcript (same stick-to-bottom rule as the main pane).
4804 && self
4805 .agent_focus
4806 .as_ref()
4807 .is_none_or(|focus| focus.scroll_top.is_none())
4808 {
4809 self.scroll_to_bottom();
4810 }
4811 }
4812
4813 /// Add `delta` to the parent-turn session cost and bump the displayed
4814 /// high-water mark so the footer total never reverses (#244).
4815 #[cfg(test)]
4816 pub fn accrue_session_cost(&mut self, delta: f64) {
4817 self.accrue_session_cost_estimate(CostEstimate::usd_only(delta));
4818 }
4819
4820 /// Record what a turn's pricing attempt actually produced.
4821 ///
4822 /// Called with the same audit that feeds [`Self::accrue_session_cost_estimate`],
4823 /// so the completeness counters can never drift from the running total.
4824 /// Routes that do not meter money at all (OAuth, token plans, local models)
4825 /// are not counted in either bucket — there is no dollar figure to be
4826 /// incomplete about.
4827 pub fn record_turn_cost_audit(&mut self, audit: &codewhale_engine::pricing::TurnCostAudit) {
4828 // Provenance is recorded for every audited turn, priced or not: knowing
4829 // *which* row a total was built from is part of explaining the total.
4830 if let Some(provenance) = audit.provenance.as_ref() {
4831 self.session
4832 .cost_pricing_provenances
4833 .insert(provenance.label().to_string());
4834 }
4835 if let Some(defect) = audit.live_pricing_defect.as_ref() {
4836 if audit.estimate.is_some() {
4837 self.session
4838 .cost_live_pricing_defects
4839 .insert(defect.label().to_string());
4840 } else {
4841 self.session
4842 .cost_live_pricing_unusable_defects
4843 .insert(defect.label().to_string());
4844 }
4845 }
4846 // An exactly non-metered route has no dollar figure to be incomplete
4847 // about, so it joins neither coverage bucket. Everything else does,
4848 // including a route whose billing basis could not be established.
4849 if !audit.counts_toward_money_coverage() {
4850 return;
4851 }
4852 for class in &audit.unpriced_classes {
4853 self.session
4854 .cost_unpriced_classes
4855 .insert(class.label().to_string());
4856 }
4857 if !audit.usd_priced
4858 && let Some(reason) = audit.unpriced_reason
4859 {
4860 self.session
4861 .cost_unpriced_reasons
4862 .insert(reason.label().to_string());
4863 }
4864 if !audit.cny_priced {
4865 self.session.cost_cny_unpriced_reasons.insert(
4866 audit
4867 .unpriced_reason
4868 .map_or("currency_not_published", |reason| reason.label())
4869 .to_string(),
4870 );
4871 }
4872 if audit.usd_priced {
4873 self.session.cost_priced_turns = self.session.cost_priced_turns.saturating_add(1);
4874 } else {
4875 self.session.cost_unpriced_turns = self.session.cost_unpriced_turns.saturating_add(1);
4876 }
4877 if audit.cny_priced {
4878 self.session.cost_cny_priced_turns =
4879 self.session.cost_cny_priced_turns.saturating_add(1);
4880 } else {
4881 self.session.cost_cny_unpriced_turns =
4882 self.session.cost_cny_unpriced_turns.saturating_add(1);
4883 }
4884 }
4885
4886 /// Record the route a turn's cost was resolved against, redacted.
4887 pub fn record_turn_cost_route_receipt(&mut self, receipt: String) {
4888 // Bound the set so a session that rotates routes cannot grow it without
4889 // limit; the first 32 distinct routes are more than enough to explain a
4890 // total, and the cap is reported rather than silently truncating.
4891 const MAX_ROUTE_RECEIPTS: usize = 32;
4892 if self.session.cost_route_receipts.len() < MAX_ROUTE_RECEIPTS {
4893 self.session.cost_route_receipts.insert(receipt);
4894 } else {
4895 self.session
4896 .cost_route_receipts
4897 .insert("…additional routes not recorded (receipt cap reached)".to_string());
4898 }
4899 }
4900
4901 /// Fold a drained background-cost pool's coverage into the session's.
4902 ///
4903 /// The caller has already added `pool.estimate` to the running total; this
4904 /// adds the counters and provenance that qualify it, from the same drained
4905 /// value, so the two can never disagree.
4906 pub fn absorb_background_cost_coverage(
4907 &mut self,
4908 pool: &codewhale_engine::cost_status::PendingBackgroundCost,
4909 ) {
4910 self.session.cost_priced_turns = self
4911 .session
4912 .cost_priced_turns
4913 .saturating_add(pool.priced_turns);
4914 self.session.cost_unpriced_turns = self
4915 .session
4916 .cost_unpriced_turns
4917 .saturating_add(pool.unpriced_turns);
4918 self.session.cost_cny_priced_turns = self
4919 .session
4920 .cost_cny_priced_turns
4921 .saturating_add(pool.cny_priced_turns);
4922 self.session.cost_cny_unpriced_turns = self
4923 .session
4924 .cost_cny_unpriced_turns
4925 .saturating_add(pool.cny_unpriced_turns);
4926 for reason in &pool.unpriced_reasons {
4927 self.session
4928 .cost_unpriced_reasons
4929 .insert((*reason).to_string());
4930 }
4931 for reason in &pool.cny_unpriced_reasons {
4932 self.session
4933 .cost_cny_unpriced_reasons
4934 .insert((*reason).to_string());
4935 }
4936 for class in &pool.unpriced_classes {
4937 self.session
4938 .cost_unpriced_classes
4939 .insert((*class).to_string());
4940 }
4941 for provenance in &pool.pricing_provenances {
4942 self.session
4943 .cost_pricing_provenances
4944 .insert((*provenance).to_string());
4945 }
4946 for defect in &pool.live_pricing_defects {
4947 self.session
4948 .cost_live_pricing_defects
4949 .insert((*defect).to_string());
4950 }
4951 for defect in &pool.live_pricing_unusable_defects {
4952 self.session
4953 .cost_live_pricing_unusable_defects
4954 .insert((*defect).to_string());
4955 }
4956 for receipt in &pool.route_receipts {
4957 self.record_turn_cost_route_receipt(receipt.clone());
4958 }
4959 }
4960
4961 /// Fold one atomic background batch into the live session projection.
4962 /// Returns whether the batch carried runtime-owned response identities and
4963 /// therefore needs a fresh durable snapshot (it may have landed after the
4964 /// ordinary TurnComplete save).
4965 pub fn absorb_pending_background_cost(
4966 &mut self,
4967 pool: &codewhale_engine::cost_status::PendingBackgroundCost,
4968 ) -> bool {
4969 let runtime_usage_arrived = !pool.usage_source_fingerprints.is_empty();
4970 if pool.estimate.is_positive() {
4971 self.accrue_subagent_cost_estimate(pool.estimate);
4972 }
4973 let add = |slot: &mut Option<u64>, tokens: Option<u64>| {
4974 if let Some(tokens) = tokens {
4975 *slot = Some(slot.unwrap_or(0).saturating_add(tokens));
4976 }
4977 };
4978 add(
4979 &mut self.session.subagent_cache_hit_tokens,
4980 pool.cache_hit_tokens,
4981 );
4982 add(
4983 &mut self.session.subagent_cache_miss_tokens,
4984 pool.cache_miss_tokens,
4985 );
4986 add(
4987 &mut self.session.subagent_cache_write_tokens,
4988 pool.cache_write_tokens,
4989 );
4990 self.absorb_background_cost_coverage(pool);
4991 let mut source_arrived = false;
4992 for record in &pool.source_records {
4993 match self.absorb_usage_source(record) {
4994 Ok(changed) => source_arrived |= changed,
4995 Err(error) => {
4996 tracing::warn!(%error, "live usage source projection skipped");
4997 self.mark_usage_uncertain("usage_correction_unverified");
4998 }
4999 }
5000 }
5001 self.session
5002 .pinned_late_usage_sources
5003 .extend(pool.pinned_usage_source_fingerprints.iter().cloned());
5004 self.session
5005 .subagent_usage_sources
5006 .extend(pool.usage_source_fingerprints.iter().cloned());
5007 self.compact_subagent_usage_sources();
5008 codewhale_engine::cost_status::prune_settled_missing_reasons(
5009 &self.session.accounted_usage_sources,
5010 self.session.cost_unpriced_turns,
5011 self.session.cost_cny_unpriced_turns,
5012 &mut self.session.cost_unpriced_reasons,
5013 &mut self.session.cost_cny_unpriced_reasons,
5014 );
5015 runtime_usage_arrived || source_arrived
5016 }
5017
5018 pub(crate) fn compact_subagent_usage_sources(&mut self) {
5019 let accounted = &self.session.accounted_usage_sources;
5020 let pinned = &self.session.pinned_late_usage_sources;
5021 self.session.subagent_usage_sources.compact_keeping_pinned(
5022 codewhale_engine::cost_status::MAX_USAGE_SOURCE_FINGERPRINTS,
5023 |fp| accounted.contains_key(fp) || pinned.contains(fp),
5024 );
5025 }
5026
5027 /// Clear every live cost-coverage counter.
5028 ///
5029 /// Used by `/new` and by the session-load path: loading a session must not
5030 /// leave the previous session's priced/unpriced turns attached to a total
5031 /// that no longer contains them (#4318).
5032 pub fn reset_cost_coverage(&mut self) {
5033 self.session.accounted_usage_sources.clear();
5034 self.session.pinned_late_usage_sources.clear();
5035 self.session.cost_priced_turns = 0;
5036 self.session.cost_unpriced_turns = 0;
5037 self.session.cost_cny_priced_turns = 0;
5038 self.session.cost_cny_unpriced_turns = 0;
5039 self.session.cost_unpriced_reasons.clear();
5040 self.session.cost_cny_unpriced_reasons.clear();
5041 self.session.cost_unpriced_classes.clear();
5042 self.session.cost_pricing_provenances.clear();
5043 self.session.cost_live_pricing_defects.clear();
5044 self.session.cost_live_pricing_unusable_defects.clear();
5045 self.session.cost_route_receipts.clear();
5046 self.session.cost_coverage_unknown_legacy = false;
5047 }
5048
5049 /// Add a dual-currency parent-turn cost estimate.
5050 pub fn accrue_session_cost_estimate(&mut self, estimate: CostEstimate) {
5051 let total = CostEstimate {
5052 usd: self.session.session_cost,
5053 cny: self.session.session_cost_cny,
5054 }
5055 .saturating_add(estimate);
5056 self.session.session_cost = total.usd;
5057 self.session.session_cost_cny = total.cny;
5058 self.refresh_displayed_cost_high_water();
5059 }
5060
5061 /// Fold one in-flight model call's priced receipt into the pending-turn
5062 /// estimate so cost surfaces move during a long agentic turn rather than
5063 /// only when it completes. The turn's authoritative price still lands via
5064 /// `accrue_session_cost_estimate` at `TurnComplete`; callers must
5065 /// `clear_pending_turn_cost` there first so nothing counts twice.
5066 pub fn accrue_pending_turn_cost_estimate(&mut self, estimate: CostEstimate) {
5067 let total = CostEstimate {
5068 usd: self.session.pending_turn_cost,
5069 cny: self.session.pending_turn_cost_cny,
5070 }
5071 .saturating_add(estimate);
5072 self.session.pending_turn_cost = total.usd;
5073 self.session.pending_turn_cost_cny = total.cny;
5074 self.refresh_displayed_cost_high_water();
5075 }
5076
5077 /// Drop the in-flight turn's provisional estimate. Called at
5078 /// `TurnComplete` (any outcome) immediately before the authoritative
5079 /// cumulative price accrues; the display stays monotonic through the
5080 /// swap via the high-water mark (#244).
5081 pub fn clear_pending_turn_cost(&mut self) {
5082 self.session.pending_turn_cost = 0.0;
5083 self.session.pending_turn_cost_cny = 0.0;
5084 }
5085
5086 /// Add `delta` to the running sub-agent cost and bump the displayed
5087 /// high-water mark so the footer total never reverses (#244).
5088 #[cfg(test)]
5089 pub fn accrue_subagent_cost(&mut self, delta: f64) {
5090 self.accrue_subagent_cost_estimate(CostEstimate::usd_only(delta));
5091 }
5092
5093 /// Add a dual-currency sub-agent/background cost estimate.
5094 pub fn accrue_subagent_cost_estimate(&mut self, estimate: CostEstimate) {
5095 let total = CostEstimate {
5096 usd: self.session.subagent_cost,
5097 cny: self.session.subagent_cost_cny,
5098 }
5099 .saturating_add(estimate);
5100 self.session.subagent_cost = total.usd;
5101 self.session.subagent_cost_cny = total.cny;
5102 self.refresh_displayed_cost_high_water();
5103 }
5104
5105 /// Copy current session/subagent cost accumulators into session metadata
5106 /// for persistence.
5107 pub(crate) fn copy_cost_to_snapshot(
5108 &self,
5109 cost: &mut codewhale_engine::session_manager::SessionCostSnapshot,
5110 ) {
5111 cost.session_cost_usd = self.session.session_cost;
5112 cost.session_cost_cny = self.session.session_cost_cny;
5113 cost.subagent_cost_usd = self.session.subagent_cost;
5114 cost.subagent_cost_cny = self.session.subagent_cost_cny;
5115 cost.displayed_cost_high_water_usd = self.session.displayed_cost_high_water;
5116 cost.displayed_cost_high_water_cny = self.session.displayed_cost_high_water_cny;
5117 // Coverage travels with the money it qualifies. A restored total without
5118 // these fields cannot say what it covers, and its serde defaults read as
5119 // a *complete* total covering zero turns — so they are persisted together
5120 // and `coverage_recorded` marks that this writer actually knew (#4318).
5121 cost.priced_turns = self.session.cost_priced_turns;
5122 cost.unpriced_turns = self.session.cost_unpriced_turns;
5123 cost.cny_priced_turns = self.session.cost_cny_priced_turns;
5124 cost.cny_unpriced_turns = self.session.cost_cny_unpriced_turns;
5125 cost.unpriced_reasons = self.session.cost_unpriced_reasons.clone();
5126 cost.cny_unpriced_reasons = self.session.cost_cny_unpriced_reasons.clone();
5127 cost.unpriced_classes = self.session.cost_unpriced_classes.clone();
5128 cost.pricing_provenances = self.session.cost_pricing_provenances.clone();
5129 cost.live_pricing_defects = self.session.cost_live_pricing_defects.clone();
5130 cost.live_pricing_unusable_defects =
5131 self.session.cost_live_pricing_unusable_defects.clone();
5132 cost.route_receipts = self.session.cost_route_receipts.clone();
5133 cost.usage_source_fingerprints = self.session.subagent_usage_sources.clone();
5134 cost.pinned_late_usage_fingerprints = self.session.pinned_late_usage_sources.clone();
5135 // A session restored as legacy-unknown stays unknown when re-saved:
5136 // re-writing it as "recorded" would launder the missing evidence into an
5137 // apparently complete zero.
5138 cost.coverage_recorded = !self.session.cost_coverage_unknown_legacy;
5139 cost.accounted_usage_sources = self.session.accounted_usage_sources.clone();
5140 }
5141
5142 pub(crate) fn restore_cost_snapshot(
5143 &mut self,
5144 cost: &codewhale_engine::session_manager::SessionCostSnapshot,
5145 ) {
5146 let parent = CostEstimate {
5147 usd: cost.session_cost_usd,
5148 cny: cost.session_cost_cny,
5149 }
5150 .sanitized();
5151 let auxiliary = CostEstimate {
5152 usd: cost.subagent_cost_usd,
5153 cny: cost.subagent_cost_cny,
5154 }
5155 .sanitized();
5156 self.session.session_cost = parent.usd;
5157 self.session.session_cost_cny = parent.cny;
5158 self.session.subagent_cost = auxiliary.usd;
5159 self.session.subagent_cost_cny = auxiliary.cny;
5160 self.session.subagent_usage_sources = cost.usage_source_fingerprints.clone();
5161 self.session.pinned_late_usage_sources = cost.pinned_late_usage_fingerprints.clone();
5162 self.session.accounted_usage_sources = cost.accounted_usage_sources.clone();
5163 self.session.cost_priced_turns = cost.priced_turns;
5164 self.session.cost_unpriced_turns = cost.unpriced_turns;
5165 self.session.cost_cny_priced_turns = cost.cny_priced_turns;
5166 self.session.cost_cny_unpriced_turns = cost.cny_unpriced_turns;
5167 self.session.cost_unpriced_reasons = cost.unpriced_reasons.clone();
5168 self.session.cost_cny_unpriced_reasons = cost.cny_unpriced_reasons.clone();
5169 self.session.cost_unpriced_classes = cost.unpriced_classes.clone();
5170 self.session.cost_pricing_provenances = cost.pricing_provenances.clone();
5171 self.session.cost_live_pricing_defects = cost.live_pricing_defects.clone();
5172 self.session.cost_live_pricing_unusable_defects =
5173 cost.live_pricing_unusable_defects.clone();
5174 self.session.cost_route_receipts = cost.route_receipts.clone();
5175 self.session.cost_coverage_unknown_legacy = cost.coverage_is_legacy_unknown();
5176 self.session.displayed_cost_high_water = self
5177 .session
5178 .displayed_cost_high_water
5179 .max(cost.displayed_cost_high_water_usd)
5180 .max(parent.usd + auxiliary.usd);
5181 self.session.displayed_cost_high_water_cny = self
5182 .session
5183 .displayed_cost_high_water_cny
5184 .max(cost.displayed_cost_high_water_cny)
5185 .max(parent.cny + auxiliary.cny);
5186 }
5187
5188 pub(crate) fn mark_usage_uncertain(&mut self, reason: &'static str) {
5189 if self
5190 .session
5191 .cost_unpriced_reasons
5192 .insert(reason.to_string())
5193 {
5194 self.session.cost_unpriced_turns = self.session.cost_unpriced_turns.saturating_add(1);
5195 }
5196 if self
5197 .session
5198 .cost_cny_unpriced_reasons
5199 .insert(reason.to_string())
5200 {
5201 self.session.cost_cny_unpriced_turns =
5202 self.session.cost_cny_unpriced_turns.saturating_add(1);
5203 }
5204 }
5205
5206 pub(crate) fn absorb_usage_source(
5207 &mut self,
5208 record: &codewhale_engine::cost_status::RuntimeUsageRecord,
5209 ) -> Result<bool, String> {
5210 if codewhale_engine::cost_status::is_usage_source_retired(
5211 codewhale_engine::cost_status::scope_token(),
5212 &record.source_id,
5213 ) {
5214 return Ok(false);
5215 }
5216 let key = codewhale_engine::cost_status::usage_source_fingerprint(&record.source_id);
5217 let previous = self.session.accounted_usage_sources.get(&key).cloned();
5218 let mut cost = codewhale_engine::session_manager::SessionCostSnapshot::default();
5219 self.copy_cost_to_snapshot(&mut cost);
5220 if previous
5221 .as_ref()
5222 .is_some_and(|previous| previous.record == *record)
5223 {
5224 return Ok(false);
5225 }
5226 let (old, new) = cost
5227 .project_usage_record(record)
5228 .map_err(|error| error.to_string())?;
5229 if old == 0 && new == 0 && cost.accounted_usage_sources.get(&key) == previous.as_ref() {
5230 return Ok(false);
5231 }
5232 self.restore_cost_snapshot(&cost);
5233 let next_usage = &record.usage.usage;
5234 let old_usage = previous
5235 .as_ref()
5236 .map(|previous| &previous.record.usage.usage);
5237 let replace = |total: &mut u32, old: u32, new: u32| {
5238 *total = total.saturating_sub(old).saturating_add(new);
5239 };
5240 replace(
5241 &mut self.session.total_tokens,
5242 u32::try_from(old).unwrap_or(u32::MAX),
5243 u32::try_from(new).unwrap_or(u32::MAX),
5244 );
5245 replace(
5246 &mut self.session.total_conversation_tokens,
5247 u32::try_from(old).unwrap_or(u32::MAX),
5248 u32::try_from(new).unwrap_or(u32::MAX),
5249 );
5250 let replace_breakdown = |total: &mut u32, old: u32, new: u32| {
5251 *total = if new >= old {
5252 total.saturating_add(new - old)
5253 } else {
5254 total.saturating_sub(old - new)
5255 };
5256 };
5257 replace_breakdown(
5258 &mut self.session.total_input_tokens,
5259 old_usage.map_or(0, |usage| usage.input_tokens),
5260 next_usage.input_tokens,
5261 );
5262 replace_breakdown(
5263 &mut self.session.total_output_tokens,
5264 old_usage.map_or(0, |usage| usage.output_tokens),
5265 next_usage.output_tokens,
5266 );
5267 let before = old_usage.map(codewhale_engine::pricing::token_usage_for_pricing);
5268 let after = codewhale_engine::pricing::token_usage_for_pricing(next_usage);
5269 replace_breakdown(
5270 &mut self.session.total_cache_hit_tokens,
5271 before.as_ref().map_or(0, |usage| {
5272 u32::try_from(usage.cache_read).unwrap_or(u32::MAX)
5273 }),
5274 u32::try_from(after.cache_read).unwrap_or(u32::MAX),
5275 );
5276 replace_breakdown(
5277 &mut self.session.total_cache_miss_tokens,
5278 before
5279 .as_ref()
5280 .map_or(0, |usage| u32::try_from(usage.input).unwrap_or(u32::MAX)),
5281 u32::try_from(after.input).unwrap_or(u32::MAX),
5282 );
5283 replace_breakdown(
5284 &mut self.session.total_cache_write_tokens,
5285 before.as_ref().map_or(0, |usage| {
5286 u32::try_from(usage.cache_write).unwrap_or(u32::MAX)
5287 }),
5288 u32::try_from(after.cache_write).unwrap_or(u32::MAX),
5289 );
5290 self.needs_redraw = true;
5291 Ok(true)
5292 }
5293
5294 pub fn sync_cost_to_metadata(
5295 &self,
5296 metadata: &mut codewhale_engine::session_manager::SessionMetadata,
5297 ) {
5298 self.copy_cost_to_snapshot(&mut metadata.cost);
5299 // Persist cumulative turn duration so the footer "worked" chip
5300 // survives session save/restore (#2038).
5301 metadata.cumulative_turn_secs = self.cumulative_turn_duration.as_secs();
5302 }
5303
5304 /// Recompute the displayed cost high-water mark. Called any time a cost
5305 /// counter is mutated; never decreases.
5306 pub fn refresh_displayed_cost_high_water(&mut self) {
5307 let current = CostEstimate {
5308 usd: self.session.session_cost,
5309 cny: self.session.session_cost_cny,
5310 }
5311 .saturating_add(CostEstimate {
5312 usd: self.session.pending_turn_cost,
5313 cny: self.session.pending_turn_cost_cny,
5314 })
5315 .saturating_add(CostEstimate {
5316 usd: self.session.subagent_cost,
5317 cny: self.session.subagent_cost_cny,
5318 });
5319 if current.usd > self.session.displayed_cost_high_water {
5320 self.session.displayed_cost_high_water = current.usd;
5321 }
5322 if current.cny > self.session.displayed_cost_high_water_cny {
5323 self.session.displayed_cost_high_water_cny = current.cny;
5324 }
5325 }
5326
5327 /// Read the visible session+sub-agent cost. Guaranteed monotonic across
5328 /// reconciliation events (cache adjustments, provisional → final swaps)
5329 /// for the lifetime of one session (#244).
5330 #[cfg(test)]
5331 pub fn displayed_session_cost(&self) -> f64 {
5332 self.displayed_session_cost_for_currency(CostCurrency::Usd)
5333 }
5334
5335 /// Read the visible session+sub-agent cost in the chosen currency.
5336 pub fn displayed_session_cost_for_currency(&self, currency: CostCurrency) -> f64 {
5337 match self.cost_display_currency(currency) {
5338 CostCurrency::Usd => {
5339 let current = CostEstimate {
5340 usd: self.session.session_cost,
5341 cny: 0.0,
5342 }
5343 .saturating_add(CostEstimate {
5344 usd: self.session.pending_turn_cost,
5345 cny: 0.0,
5346 })
5347 .saturating_add(CostEstimate {
5348 usd: self.session.subagent_cost,
5349 cny: 0.0,
5350 })
5351 .usd;
5352 current.max(self.session.displayed_cost_high_water)
5353 }
5354 CostCurrency::Cny => {
5355 let current = CostEstimate {
5356 usd: 0.0,
5357 cny: self.session.session_cost_cny,
5358 }
5359 .saturating_add(CostEstimate {
5360 usd: 0.0,
5361 cny: self.session.pending_turn_cost_cny,
5362 })
5363 .saturating_add(CostEstimate {
5364 usd: 0.0,
5365 cny: self.session.subagent_cost_cny,
5366 })
5367 .cny;
5368 current.max(self.session.displayed_cost_high_water_cny)
5369 }
5370 }
5371 }
5372
5373 /// The session's own display share: settled turns plus the in-flight
5374 /// turn's provisional estimate (the running turn's money is session
5375 /// money, so the sidebar breakdown keeps summing to the displayed total
5376 /// mid-turn).
5377 pub fn session_cost_for_currency(&self, currency: CostCurrency) -> f64 {
5378 match self.cost_display_currency(currency) {
5379 CostCurrency::Usd => self.session.session_cost + self.session.pending_turn_cost,
5380 CostCurrency::Cny => self.session.session_cost_cny + self.session.pending_turn_cost_cny,
5381 }
5382 }
5383
5384 pub fn subagent_cost_for_currency(&self, currency: CostCurrency) -> f64 {
5385 match self.cost_display_currency(currency) {
5386 CostCurrency::Usd => self.session.subagent_cost,
5387 CostCurrency::Cny => self.session.subagent_cost_cny,
5388 }
5389 }
5390
5391 pub fn format_cost_amount(&self, amount: f64) -> String {
5392 codewhale_engine::pricing::format_cost_amount(
5393 amount,
5394 self.cost_display_currency(self.cost_currency),
5395 )
5396 }
5397
5398 /// A [`CostEstimate`] in the session's display currency — the same rule
5399 /// `format_cost_amount` applies, so a turn receipt and the session total
5400 /// never disagree on `$` versus `¥`.
5401 pub fn format_cost_estimate(&self, estimate: CostEstimate) -> String {
5402 codewhale_engine::pricing::format_cost_estimate(
5403 estimate,
5404 self.cost_display_currency(self.cost_currency),
5405 )
5406 }
5407
5408 /// Price is one number, everywhere (design §2.11 item 5): the session
5409 /// cost as the price view and status surface print it — money routes print
5410 /// exact or estimated dollars (or `$0.00` before spending), while
5411 /// subscription, local, and unpriced sessions say `unknown` rather than
5412 /// printing plan names, `"local"`, or an invented zero.
5413 pub(crate) fn status_cost_label(&self) -> Option<String> {
5414 use codewhale_engine::route_billing::UsageChip;
5415 match self.cumulative_usage_chip() {
5416 UsageChip::Money(_) | UsageChip::Hidden => None,
5417 UsageChip::PricedSubtotal { amount, .. } => Some(amount),
5418 UsageChip::Allowance { .. } | UsageChip::Local | UsageChip::Unknown(_) => Some(
5419 codewhale_localization::tr(
5420 self.ui_locale,
5421 codewhale_localization::MessageId::CmdCostUnknownValue,
5422 )
5423 .into_owned(),
5424 ),
5425 }
5426 }
5427
5428 #[must_use]
5429 pub fn session_cost_label(&self) -> String {
5430 self.status_cost_label().unwrap_or_else(|| {
5431 self.format_cost_amount(self.displayed_session_cost_for_currency(self.cost_currency))
5432 })
5433 }
5434
5435 pub(crate) fn cost_display_currency(&self, currency: CostCurrency) -> CostCurrency {
5436 if currency == CostCurrency::Cny
5437 && self.session.cost_cny_priced_turns == 0
5438 && self.session.cost_priced_turns > 0
5439 {
5440 CostCurrency::Usd
5441 } else {
5442 currency
5443 }
5444 }
5445
5446 /// Fold the oldest [`Self::HISTORY_FOLD_BATCH`] cells into a single
5447 /// `ArchivedContext` placeholder when history exceeds the soft cap.
5448 /// Called from [`Self::add_message`]; the caller is responsible for
5449 /// also removing the folded range from any auxiliary per-cell maps.
5450 fn maybe_fold_history(&mut self) {
5451 if self.history.len() <= Self::HISTORY_SOFT_CAP {
5452 return;
5453 }
5454
5455 let fold_count = Self::HISTORY_FOLD_BATCH.min(self.history.len());
5456 // Don't fold into the very last cell(s) — keep a buffer of
5457 // non-folded cells so the visible transcript tail stays intact.
5458 let keep_tail = Self::HISTORY_SOFT_CAP.saturating_sub(Self::HISTORY_FOLD_BATCH);
5459 if self.history.len().saturating_sub(fold_count) < keep_tail {
5460 return;
5461 }
5462
5463 // Gather the range of cell indices we are folding.
5464 let folded: Vec<HistoryCell> = self.history.drain(..fold_count).collect();
5465 let folded_revs: Vec<u64> = self.history_revisions.drain(..fold_count).collect();
5466 let _ = folded_revs; // revisions are discarded with the cells
5467
5468 // Shift all per-cell index maps down by `fold_count`.
5469 self.shift_history_maps_down(fold_count);
5470
5471 // Build a single placeholder cell summarizing the folded range.
5472 let total_folded = folded.len();
5473 let summary = format!(
5474 "{total_folded} older transcript cells folded to bound memory. \
5475 Use /sessions to load a prior session snapshot if needed."
5476 );
5477 let placeholder = HistoryCell::ArchivedContext {
5478 level: 0,
5479 range: format!("cells 0-{}", total_folded.saturating_sub(1)),
5480 tokens: String::new(),
5481 density: String::new(),
5482 model: String::new(),
5483 timestamp: String::new(),
5484 summary,
5485 };
5486
5487 // Insert the placeholder at the front.
5488 let rev = self.fresh_history_revision();
5489 self.history.insert(0, placeholder);
5490 self.history_revisions.insert(0, rev);
5491 self.transcript_identity_epoch = self.transcript_identity_epoch.wrapping_add(1);
5492 self.history_version = self.history_version.wrapping_add(1);
5493 self.needs_redraw = true;
5494 }
5495
5496 /// Remap every per-cell history index after `maybe_fold_history` removes
5497 /// the first `n` cells and inserts one placeholder at index 0: an index
5498 /// `>= n` becomes `index - n + 1`; an index inside the folded range is
5499 /// dropped.
5500 fn shift_history_maps_down(&mut self, n: usize) {
5501 let remap = |idx: usize| idx.checked_sub(n).map(|kept| kept + 1);
5502 self.completed_assistant_outputs
5503 .retain_mut(|receipt| match remap(receipt.history_index) {
5504 Some(idx) => {
5505 receipt.history_index = idx;
5506 true
5507 }
5508 None => false,
5509 });
5510 self.tool_cells.retain(|_, idx| match remap(*idx) {
5511 Some(new) => {
5512 *idx = new;
5513 true
5514 }
5515 None => false,
5516 });
5517 self.pending_thinking_translation_cells
5518 .retain(|_, idx| match remap(*idx) {
5519 Some(new) => {
5520 *idx = new;
5521 true
5522 }
5523 None => false,
5524 });
5525 self.tool_details_by_cell = std::mem::take(&mut self.tool_details_by_cell)
5526 .into_iter()
5527 .filter_map(|(idx, detail)| remap(idx).map(|idx| (idx, detail)))
5528 .collect();
5529 self.context_references_by_cell = std::mem::take(&mut self.context_references_by_cell)
5530 .into_iter()
5531 .filter_map(|(idx, refs)| remap(idx).map(|idx| (idx, refs)))
5532 .collect();
5533 self.rebuild_session_context_references();
5534 self.subagent_card_index.retain(|_, idx| match remap(*idx) {
5535 Some(new) => {
5536 *idx = new;
5537 true
5538 }
5539 None => false,
5540 });
5541 self.last_fanout_card_index = self.last_fanout_card_index.and_then(remap);
5542 self.collapsed_cells = std::mem::take(&mut self.collapsed_cells)
5543 .into_iter()
5544 .filter_map(remap)
5545 .collect();
5546 self.cell_folds.clear();
5547 self.expanded_tool_runs = std::mem::take(&mut self.expanded_tool_runs)
5548 .into_iter()
5549 .filter_map(remap)
5550 .collect();
5551 self.turn_work_durations = std::mem::take(&mut self.turn_work_durations)
5552 .into_iter()
5553 .filter_map(|(idx, duration)| remap(idx).map(|idx| (idx, duration)))
5554 .collect();
5555 self.turn_durations_revision = self.turn_durations_revision.wrapping_add(1);
5556 self.active_turn_user_index = self.active_turn_user_index.and_then(remap);
5557 self.collapsed_cell_map.clear();
5558 self.streaming_message_index = self.streaming_message_index.and_then(remap);
5559 self.streaming_source_receipt = None;
5560 self.ocean_turn_history_start = self.ocean_turn_history_start.saturating_sub(n) + 1;
5561 self.ocean_receipt_settle_start = self
5562 .ocean_receipt_settle_start
5563 .map(|idx| idx.saturating_sub(n) + 1);
5564 }
5565
5566 /// The name a sub-agent was dispatched under, when it has one (#5287).
5567 ///
5568 /// `SubAgentResult::name` carries the session name, which the manager
5569 /// seeds with the agent id and only replaces when the dispatch supplied a
5570 /// name. An id is a lookup handle, never the identity an operator
5571 /// dispatched by, so it is reported as absent here.
5572 fn agent_session_name(&self, agent_id: &str) -> Option<String> {
5573 let agent = self
5574 .subagent_cache
5575 .iter()
5576 .find(|agent| agent.agent_id == agent_id)?;
5577 let name = agent.name.trim();
5578 (!name.is_empty() && name != agent.agent_id).then(|| name.to_string())
5579 }
5580
5581 /// `true` for the `Agent N` counter placeholder assigned before a child's
5582 /// dispatch metadata arrives. Placeholders are the only label that may be
5583 /// upgraded once the child's identity is observed.
5584 pub(crate) fn is_agent_counter_placeholder(label: &str) -> bool {
5585 label
5586 .strip_prefix("Agent ")
5587 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
5588 }
5589
5590 /// The engine's name for an agent (#6565): resolved from the manager
5591 /// snapshot when there is one, else from the name its spawn or completion
5592 /// event carried. `None` only for a progress-only agent whose identity has
5593 /// not arrived yet, so the caller falls back to a counter placeholder.
5594 fn engine_agent_name(&self, agent_id: &str) -> Option<String> {
5595 self.subagent_cache
5596 .iter()
5597 .find(|agent| agent.agent_id == agent_id)
5598 .map(codewhale_engine::tools::subagent::subagent_result_display_name)
5599 .or_else(|| {
5600 self.agent_progress_meta
5601 .get(agent_id)
5602 .and_then(|meta| meta.display_name.clone())
5603 })
5604 .or_else(|| {
5605 self.current_agent_roster()
5606 .iter()
5607 .find(|row| row.worker_id == agent_id)
5608 .map(|row| row.display_name.clone())
5609 })
5610 .map(|name| name.trim().to_string())
5611 .filter(|name| !name.is_empty() && name != agent_id)
5612 }
5613
5614 /// The engine's name, made unique among the labels already shown: two
5615 /// parallel "review" tasks read "review" and "review · 2", the only thing
5616 /// the TUI adds to the engine's name.
5617 fn resolved_identity_label(&mut self, agent_id: &str) -> Option<String> {
5618 let name = self.engine_agent_name(agent_id)?;
5619 let shown_by_another = |candidate: &str| {
5620 self.agent_label_map
5621 .iter()
5622 .any(|(id, shown)| id != agent_id && shown == candidate)
5623 };
5624 let mut unique = name.clone();
5625 let mut sequence = 1u64;
5626 while shown_by_another(&unique) {
5627 sequence += 1;
5628 unique = format!("{name} · {sequence}");
5629 }
5630 Some(unique)
5631 }
5632
5633 fn next_agent_placeholder(&mut self) -> String {
5634 self.agent_counter = self.agent_counter.saturating_add(1);
5635 format!("Agent {}", self.agent_counter)
5636 }
5637
5638 /// The name this agent was *given*: its workflow task label or another
5639 /// explicit nickname, else its dispatch (session) name. `None` for an
5640 /// agent that goes by its role, so a surface can fall back to its own
5641 /// placeholder (a generated whale name on the sidebar).
5642 pub(crate) fn agent_given_name(&self, agent_id: &str) -> Option<String> {
5643 let agent = self
5644 .subagent_cache
5645 .iter()
5646 .find(|agent| agent.agent_id == agent_id)?;
5647 codewhale_engine::tools::subagent::explicit_nickname(agent_id, agent.nickname.as_deref())
5648 .map(str::to_string)
5649 .or_else(|| self.agent_session_name(agent_id))
5650 }
5651
5652 /// #3030: return the stable user-facing label for an agent id. Labels are
5653 /// resolved from the child's own identity and never downgraded once set;
5654 /// only the generic `Agent N` placeholder upgrades when dispatch metadata
5655 /// arrives. A raw agent id is never used as a label.
5656 pub(crate) fn ensure_agent_label(&mut self, agent_id: &str) -> String {
5657 let existing = self.agent_label_map.get(agent_id).cloned();
5658 if let Some(existing) = existing {
5659 if !Self::is_agent_counter_placeholder(&existing) {
5660 return existing;
5661 }
5662 // Upgrade a placeholder only once identity metadata is available.
5663 if let Some(label) = self.resolved_identity_label(agent_id) {
5664 self.agent_label_map
5665 .insert(agent_id.to_string(), label.clone());
5666 return label;
5667 }
5668 return existing;
5669 }
5670 let label = self
5671 .resolved_identity_label(agent_id)
5672 .unwrap_or_else(|| self.next_agent_placeholder());
5673 self.agent_label_map
5674 .insert(agent_id.to_string(), label.clone());
5675 label
5676 }
5677
5678 /// #3030: read-only label lookup with raw-id fallback for agents the
5679 /// label map has never seen.
5680 pub(crate) fn agent_display_label(&self, agent_id: &str) -> String {
5681 self.agent_label_map
5682 .get(agent_id)
5683 .cloned()
5684 .unwrap_or_else(|| agent_id.to_string())
5685 }
5686
5687 pub fn mark_history_updated(&mut self) {
5688 self.history_version = self.history_version.wrapping_add(1);
5689 // Resync per-cell revisions to history.len(). This is the
5690 // "I-don't-know-which-cell-changed" path: if cells were appended in
5691 // bulk (e.g. session resume, compaction), every new cell gets a
5692 // fresh revision; if cells were removed, drop trailing revs. We
5693 // intentionally do NOT bump revisions for indices that already had
5694 // one — the cache will reuse those. Callers that mutate a specific
5695 // cell's content must call `bump_history_cell(idx)` instead.
5696 self.resync_history_revisions();
5697 self.needs_redraw = true;
5698 }
5699
5700 /// Invalidate only transcript rows whose visible liveness marker is
5701 /// time-based. Animation redraws must not churn settled history, but they
5702 /// do need fresh cache keys for running history and active-cell entries.
5703 pub(crate) fn mark_live_motion_updated(&mut self) {
5704 self.mark_live_motion_updated_inner(true);
5705 }
5706
5707 /// Invalidate only committed live rows. The translation placeholder path
5708 /// already bumps the whole active-cell cache when it changes, so the UI
5709 /// uses this narrower path to avoid bumping that revision twice.
5710 pub(crate) fn mark_live_history_motion_updated(&mut self) {
5711 self.mark_live_motion_updated_inner(false);
5712 }
5713
5714 fn mark_live_motion_updated_inner(&mut self, invalidate_active_cell: bool) {
5715 self.resync_history_revisions();
5716 let live_history_indices: Vec<usize> = self
5717 .history
5718 .iter()
5719 .enumerate()
5720 .filter_map(|(index, cell)| cell.has_live_motion().then_some(index))
5721 .collect();
5722 for index in live_history_indices {
5723 let previous_revision = self.history_revisions.get(index).copied();
5724 let streaming_content_len = (self.streaming_message_index == Some(index))
5725 .then(|| match self.history.get(index) {
5726 Some(HistoryCell::Assistant {
5727 content,
5728 streaming: true,
5729 }) => Some(content.len()),
5730 _ => None,
5731 })
5732 .flatten();
5733 let revision = self.fresh_history_revision();
5734 if let Some(slot) = self.history_revisions.get_mut(index) {
5735 *slot = revision;
5736 }
5737 if let (Some(previous_revision), Some(content_len)) =
5738 (previous_revision, streaming_content_len)
5739 {
5740 let from_revision = self
5741 .streaming_source_receipt
5742 .filter(|receipt| {
5743 receipt.cell_index == index && receipt.to_revision == previous_revision
5744 })
5745 .map_or(previous_revision, |receipt| receipt.from_revision);
5746 self.streaming_source_receipt =
5747 Some(crate::tui::transcript::StreamingSourceReceipt {
5748 cell_index: index,
5749 from_revision,
5750 to_revision: revision,
5751 content_len,
5752 });
5753 }
5754 }
5755
5756 let active_has_live_motion = self
5757 .active_cell
5758 .as_ref()
5759 .is_some_and(|active| active.entries().iter().any(HistoryCell::has_live_motion));
5760 if invalidate_active_cell && active_has_live_motion {
5761 self.active_cell_revision = self.active_cell_revision.wrapping_add(1);
5762 if let Some(active) = self.active_cell.as_mut() {
5763 active.bump_revision();
5764 }
5765 }
5766
5767 self.history_version = self.history_version.wrapping_add(1);
5768 self.needs_redraw = true;
5769 }
5770
5771 /// Issue a fresh, monotonically increasing revision counter for a new
5772 /// history cell. Wrapping is acceptable — collisions are astronomically
5773 /// rare and at worst trigger one extra re-render.
5774 fn fresh_history_revision(&mut self) -> u64 {
5775 let rev = self.next_history_revision;
5776 self.next_history_revision = self.next_history_revision.wrapping_add(1);
5777 rev
5778 }
5779
5780 /// Bring `history_revisions` back into shape (`history_revisions.len() ==
5781 /// history.len()`). Pushes fresh revs for newly appended cells, truncates
5782 /// for cells that were removed. **Does not** invalidate existing entries.
5783 pub fn resync_history_revisions(&mut self) {
5784 if self.history_revisions.len() < self.history.len() {
5785 let needed = self.history.len() - self.history_revisions.len();
5786 for _ in 0..needed {
5787 let rev = self.fresh_history_revision();
5788 self.history_revisions.push(rev);
5789 }
5790 } else if self.history_revisions.len() > self.history.len() {
5791 self.history_revisions.truncate(self.history.len());
5792 }
5793 }
5794
5795 /// Bump the revision counter of a single history cell so the transcript
5796 /// cache re-renders it on the next frame. Use this whenever a cell's
5797 /// content (e.g. a streaming Assistant body) is mutated in place.
5798 pub fn bump_history_cell(&mut self, idx: usize) {
5799 // Resync first in case callers mutated `history` directly without
5800 // pushing through `add_message`. After resync, the index is valid
5801 // (or out of bounds — in which case there's nothing to bump).
5802 self.resync_history_revisions();
5803 if self
5804 .streaming_source_receipt
5805 .is_some_and(|receipt| receipt.cell_index == idx)
5806 {
5807 self.streaming_source_receipt = None;
5808 }
5809 if let Some(rev) = self.history_revisions.get_mut(idx) {
5810 let new_rev = self.next_history_revision;
5811 self.next_history_revision = self.next_history_revision.wrapping_add(1);
5812 *rev = new_rev;
5813 }
5814 self.history_version = self.history_version.wrapping_add(1);
5815 self.needs_redraw = true;
5816 }
5817
5818 /// Append a single history cell, allocating a fresh per-cell revision.
5819 /// Equivalent to `add_message` but exposed as a generic alias so call
5820 /// sites currently doing `app.history.push(...)` followed by
5821 /// `app.mark_history_updated()` can collapse to one helper.
5822 pub fn push_history_cell(&mut self, cell: HistoryCell) {
5823 self.rebase_active_cell_bindings(1);
5824 let rev = self.fresh_history_revision();
5825 self.history.push(cell);
5826 self.history_revisions.push(rev);
5827 self.history_version = self.history_version.wrapping_add(1);
5828 self.maybe_fold_history();
5829 self.needs_redraw = true;
5830 }
5831
5832 /// Append a batch of history cells, allocating fresh revisions.
5833 pub fn extend_history<I>(&mut self, cells: I)
5834 where
5835 I: IntoIterator<Item = HistoryCell>,
5836 {
5837 for cell in cells {
5838 self.rebase_active_cell_bindings(1);
5839 let rev = self.fresh_history_revision();
5840 self.history.push(cell);
5841 self.history_revisions.push(rev);
5842 }
5843 self.maybe_fold_history();
5844 self.history_version = self.history_version.wrapping_add(1);
5845 self.needs_redraw = true;
5846 }
5847
5848 pub(crate) fn adopt_session_mutation(&mut self, metadata: &SessionMetadata) {
5849 if self.current_session_id.as_deref() == Some(metadata.id.as_str())
5850 && let Some(mutation) = metadata.native_mutation_observation.as_ref()
5851 && let Some(receipt) = self.session_write_receipt.as_ref()
5852 && let Ok(receipt) = receipt.adopt_mutation(mutation)
5853 {
5854 self.session_write_receipt = Some(receipt);
5855 }
5856 }
5857
5858 pub(crate) fn owns_session_projection(
5859 &self,
5860 source: Option<&codewhale_engine::core::ops::SessionSnapshotSource>,
5861 ) -> bool {
5862 self.session_write_owner
5863 .as_ref()
5864 .zip(source)
5865 .is_some_and(|(owner, source)| owner.matches_source(source))
5866 }
5867
5868 pub(crate) fn session_sync_control(&mut self) -> codewhale_engine::core::ops::SessionControlId {
5869 let id = codewhale_engine::core::ops::SessionControlId::new();
5870 self.session_write_owner =
5871 Some(codewhale_engine::session_manager::SessionWriteOwner::Control(id.clone()));
5872 id
5873 }
5874
5875 pub(crate) fn agent_preset(&self) -> Option<String> {
5876 self.conversation_mode.clone()
5877 }
5878
5879 pub(crate) fn conversation_mode_locked(&self) -> bool {
5880 !self.api_messages.is_empty()
5881 || self.is_loading
5882 || !self.queued_messages.is_empty()
5883 || self.queued_draft.is_some()
5884 || self.pending_fresh_session.is_some()
5885 }
5886
5887 pub(crate) fn install_conversation_mode(
5888 &mut self,
5889 stored: Option<String>,
5890 unavailable: Option<String>,
5891 ) {
5892 self.conversation_mode = stored;
5893 self.conversation_mode_unavailable = unavailable;
5894 self.needs_redraw = true;
5895 }
5896
5897 pub(crate) fn conversation_mode_label(&self) -> Option<String> {
5898 crate::tui::conversation_mode::label(
5899 self.ui_locale,
5900 self.conversation_mode.as_deref(),
5901 self.conversation_mode_unavailable.as_deref(),
5902 None,
5903 )
5904 }
5905
5906 pub(crate) fn set_current_session_id(&mut self, session_id: Option<String>) {
5907 if self.current_session_id != session_id {
5908 self.view_stack.remove_owned_evidence_pagers();
5909 self.mcp_announced_problems.clear();
5910 self.session_write_receipt = None;
5911 self.session_write_owner = None;
5912 self.subagent_cache.clear();
5913 self.subagent_terminal_seen_at.clear();
5914 self.subagent_cache_received_at = None;
5915 self.agent_progress.clear();
5916 self.agent_progress_meta.clear();
5917 self.subagent_card_index.clear();
5918 self.last_fanout_card_index = None;
5919 self.pending_subagent_dispatch = None;
5920 self.agent_activity_started_at = None;
5921 self.agent_counter = 0;
5922 self.agent_label_map.clear();
5923 self.agent_focus = None;
5924 self.agent_queued_follow_ups.clear();
5925 self.agent_roster.clear();
5926 self.agent_roster_session_id = None;
5927 self.agent_roster_print_requested = false;
5928 self.coordination_detail = None;
5929 self.work_surface.reset_session_state(session_id.as_deref());
5930 }
5931 self.current_session_id = session_id;
5932 }
5933
5934 /// Clear the history and its session-scoped side indexes. Used by /clear,
5935 /// session reset, and other "wipe and reload" flows.
5936 pub fn clear_history(&mut self) {
5937 self.view_stack.remove_owned_evidence_pagers();
5938 self.history.clear();
5939 self.history_revisions.clear();
5940 self.completed_assistant_outputs.clear();
5941 self.pending_plan_handoff = None;
5942 self.context_references_by_cell.clear();
5943 self.session_context_references.clear();
5944 self.session_artifacts.clear();
5945 self.session_turn_outcomes.clear();
5946 self.delegated_writes.clear();
5947 self.prune_transcript_index_state(0);
5948 self.history_version = self.history_version.wrapping_add(1);
5949 self.needs_redraw = true;
5950 }
5951
5952 /// Record one user-visible assistant message after its typed completion
5953 /// boundary. Interrupted salvage never calls this path.
5954 pub(crate) fn record_completed_assistant_output(&mut self, history_index: usize, text: &str) {
5955 if text.trim().is_empty() {
5956 return;
5957 }
5958 if let Some(receipt) = self
5959 .completed_assistant_outputs
5960 .iter_mut()
5961 .find(|receipt| receipt.history_index == history_index)
5962 {
5963 receipt.text = text.to_string();
5964 return;
5965 }
5966 self.completed_assistant_outputs
5967 .push(CompletedAssistantOutputReceipt {
5968 history_index,
5969 text: text.to_string(),
5970 });
5971 }
5972
5973 pub(crate) fn extend_restored_history(&mut self, message: &Message, cells: Vec<HistoryCell>) {
5974 if message.role == "assistant" {
5975 let base = self.history.len();
5976 self.completed_assistant_outputs
5977 .extend(
5978 cells
5979 .iter()
5980 .enumerate()
5981 .filter_map(|(offset, cell)| match cell {
5982 HistoryCell::Assistant {
5983 content,
5984 streaming: false,
5985 } if !content.trim().is_empty() => {
5986 Some(CompletedAssistantOutputReceipt {
5987 history_index: base + offset,
5988 text: content.clone(),
5989 })
5990 }
5991 _ => None,
5992 }),
5993 );
5994 }
5995 self.extend_history(cells);
5996 }
5997
5998 pub(crate) fn completed_assistant_output_receipt(&self) -> Option<&str> {
5999 self.completed_assistant_outputs
6000 .iter()
6001 .rev()
6002 .find(|receipt| !receipt.text.trim().is_empty())
6003 .map(|receipt| receipt.text.as_str())
6004 }
6005
6006 /// Freeze only output completed inside this turn's transcript boundary.
6007 /// Restored/older receipts cannot cause a new hand-off.
6008 pub(crate) fn prepare_plan_handoff(
6009 &mut self,
6010 status: codewhale_engine::core::events::TurnOutcomeStatus,
6011 turn_id: Option<&str>,
6012 has_open_todos: bool,
6013 ) -> Option<String> {
6014 let receipt = self
6015 .completed_assistant_outputs
6016 .iter()
6017 .rev()
6018 .find(|receipt| {
6019 receipt.history_index >= self.ocean_turn_history_start
6020 && receipt.history_index < self.history.len()
6021 });
6022 if !crate::tui::plan_handoff::plan_ready(
6023 self.mode,
6024 status,
6025 receipt.map(|receipt| receipt.text.as_str()),
6026 ) {
6027 return None;
6028 }
6029 let session_id = self.current_session_id.as_ref()?;
6030 let turn_id = turn_id.filter(|id| self.runtime_turn_id.as_deref() == Some(*id))?;
6031 if self.pending_plan_handoff.is_some() {
6032 return None;
6033 }
6034 let request_id = format!(
6035 "{}:{}:{}:{}",
6036 crate::tui::plan_handoff::REQUEST_ID,
6037 session_id.len(),
6038 session_id,
6039 turn_id
6040 );
6041 self.pending_plan_handoff = Some(crate::tui::plan_handoff::PendingPlanHandoff {
6042 request_id: request_id.clone(),
6043 session_id: session_id.clone(),
6044 turn_id: turn_id.to_string(),
6045 history_start: self.ocean_turn_history_start,
6046 transcript_epoch: self.transcript_identity_epoch,
6047 text: receipt?.text.clone(),
6048 // Only successful typed receipts inside this turn can preserve a
6049 // checklist. Tool evidence can outlive UI-initiated dispatch.
6050 has_current_checklist: has_open_todos
6051 && self.history.get(self.ocean_turn_history_start..).is_some_and(|cells| {
6052 cells.iter().any(|cell| {
6053 matches!(cell, HistoryCell::Tool(crate::tui::history::ToolCell::Generic(tool))
6054 if tool.status == crate::tui::history::ToolStatus::Success
6055 && crate::tui::history::is_checklist_tool_name(&tool.name))
6056 })
6057 }),
6058 seeded_todo_id: None,
6059 });
6060 Some(request_id)
6061 }
6062
6063 pub(crate) fn plan_handoff_is_current(
6064 &self,
6065 plan: &crate::tui::plan_handoff::PendingPlanHandoff,
6066 request_id: &str,
6067 ) -> bool {
6068 plan.request_id == request_id
6069 && self.current_session_id.as_deref() == Some(plan.session_id.as_str())
6070 && self.runtime_turn_id.as_deref() == Some(plan.turn_id.as_str())
6071 && self.ocean_turn_history_start == plan.history_start
6072 && self.transcript_identity_epoch == plan.transcript_epoch
6073 && self.mode == AppMode::Plan
6074 && !self.is_loading
6075 && !self.dispatch_in_flight
6076 && !self.remote_control.runtime_chat_blocks_local_dispatch()
6077 && self.queued_message_count() == 0
6078 && self.queued_draft.is_none()
6079 && self.input.is_empty()
6080 && self.view_stack.is_empty()
6081 && self.agent_focus.is_none()
6082 }
6083
6084 /// Pop the trailing history cell, keeping revisions in sync.
6085 pub fn pop_history(&mut self) -> Option<HistoryCell> {
6086 let cell = self.history.pop();
6087 if cell.is_some() {
6088 self.history_revisions.pop();
6089 self.completed_assistant_outputs
6090 .retain(|receipt| receipt.history_index < self.history.len());
6091 self.context_references_by_cell.remove(&self.history.len());
6092 self.rebuild_session_context_references();
6093 self.prune_transcript_index_state(self.history.len());
6094 self.history_version = self.history_version.wrapping_add(1);
6095 self.needs_redraw = true;
6096 }
6097 cell
6098 }
6099
6100 /// Truncate `history` (and the parallel `history_revisions` + auxiliary
6101 /// per-cell maps) so that only cells with index `< new_len` remain.
6102 /// Used by Esc-Esc backtrack (#133) to roll the visible transcript
6103 /// back to a chosen user message. Cells dropped here are gone — the
6104 /// caller is expected to also trim the matching `api_messages` so the
6105 /// next turn matches what the user sees.
6106 pub fn truncate_history_to(&mut self, new_len: usize) {
6107 if new_len >= self.history.len() {
6108 return;
6109 }
6110 self.history.truncate(new_len);
6111 if self.history_revisions.len() > new_len {
6112 self.history_revisions.truncate(new_len);
6113 }
6114 self.completed_assistant_outputs
6115 .retain(|receipt| receipt.history_index < new_len);
6116 // Drop any auxiliary maps keyed on history indices that now point
6117 // past the new tail. We keep the rest intact so unaffected tool
6118 // cells continue to render correctly.
6119 self.tool_cells.retain(|_, idx| *idx < new_len);
6120 self.tool_details_by_cell.retain(|idx, _| *idx < new_len);
6121 self.context_references_by_cell
6122 .retain(|idx, _| *idx < new_len);
6123 self.rebuild_session_context_references();
6124 self.subagent_card_index.retain(|_, idx| *idx < new_len);
6125 if self
6126 .last_fanout_card_index
6127 .is_some_and(|idx| idx >= new_len)
6128 {
6129 self.last_fanout_card_index = None;
6130 }
6131 self.prune_transcript_index_state(new_len);
6132 self.history_version = self.history_version.wrapping_add(1);
6133 self.needs_redraw = true;
6134 }
6135
6136 pub(crate) fn prune_transcript_index_state(&mut self, len: usize) {
6137 self.transcript_identity_epoch = self.transcript_identity_epoch.wrapping_add(1);
6138 self.pending_thinking_translation_cells
6139 .retain(|_, idx| *idx < len);
6140 self.collapsed_cells.retain(|idx| *idx < len);
6141 self.cell_folds.retain(|idx, _| *idx < len);
6142 self.expanded_tool_runs.retain(|idx| *idx < len);
6143 self.turn_work_durations.retain(|idx, _| *idx < len);
6144 self.turn_durations_revision = self.turn_durations_revision.wrapping_add(1);
6145 if self.active_turn_user_index.is_some_and(|idx| idx >= len) {
6146 self.active_turn_user_index = None;
6147 }
6148 self.collapsed_cell_map.clear();
6149 }
6150
6151 /// Mutable access to the shared transcript mirror. Copy-on-write: an
6152 /// exclusive `Arc` mutates in place, a shared one detaches first, so an
6153 /// outstanding engine snapshot can never observe the mutation.
6154 pub fn api_messages_mut(&mut self) -> &mut Vec<Message> {
6155 self.context_token_cache.get_mut().clear();
6156 Arc::make_mut(&mut self.api_messages)
6157 }
6158
6159 /// Append a message and stamp when it landed — the persisted journal's
6160 /// `created_at` reads this stamp, so an entry's time is append time, not
6161 /// save time.
6162 pub fn push_api_message(&mut self, message: Message) {
6163 if self.api_messages.is_empty() && !self.session_journal.entries.is_empty() {
6164 self.window_reroot_cause
6165 .get_or_insert("user_turn_after_empty_path");
6166 }
6167 self.api_message_stamps
6168 .resize_with(self.api_messages.len(), Utc::now);
6169 Arc::make_mut(&mut self.api_messages).push(message);
6170 self.api_message_stamps.push(Utc::now());
6171 }
6172
6173 /// Mirror an engine `SessionUpdated` projection into `api_messages`. The
6174 /// unchanged prefix keeps the stamps it already earned — the engine
6175 /// mirrors the same messages back in the same order — and only entries
6176 /// that are new or were rewritten (compaction) are stamped now, which
6177 /// lands within a turn-event of the real append. The shared snapshot is
6178 /// installed without copying.
6179 pub fn set_api_messages(&mut self, messages: Arc<Vec<Message>>) -> usize {
6180 let exact = self
6181 .api_messages
6182 .iter()
6183 .zip(messages.iter())
6184 .take_while(|(old, new)| old == new)
6185 .count();
6186 let unchanged = exact
6187 + self.api_messages[exact..]
6188 .iter()
6189 .zip(&messages[exact..])
6190 .take_while(|(old, new)| {
6191 codewhale_models::turn_classify::same_recorded_turn(old, new)
6192 })
6193 .count();
6194 self.api_message_stamps
6195 .truncate(unchanged.min(self.api_message_stamps.len()));
6196 self.api_message_stamps
6197 .resize_with(messages.len(), Utc::now);
6198 self.session_turn_outcomes
6199 .retain(|outcome| outcome.after_message_count <= unchanged);
6200 if unchanged == 0 {
6201 match (!self.api_messages.is_empty(), !messages.is_empty()) {
6202 (true, true) => {
6203 self.window_reroot_cause.get_or_insert("engine_projection");
6204 }
6205 (true, false) => {
6206 self.window_reroot_cause
6207 .get_or_insert("engine_projection_empty");
6208 }
6209 (false, true) if !self.session_journal.entries.is_empty() => {
6210 self.window_reroot_cause
6211 .get_or_insert("engine_projection_no_active_path");
6212 }
6213 _ => {}
6214 }
6215 }
6216 if unchanged == 0 || messages.len() < self.api_messages.len() {
6217 self.last_billed_input_tokens = None;
6218 }
6219 self.context_token_cache
6220 .get_mut()
6221 .message_tokens
6222 .truncate(exact);
6223 self.api_messages = messages;
6224 exact
6225 }
6226
6227 /// Install a resumed conversation, reusing the persisted journal's
6228 /// per-entry `created_at` as the stamps so a next save does not rewrite
6229 /// history to resume time. Entries without a matching stamp fall back to
6230 /// now.
6231 pub fn restore_api_messages(
6232 &mut self,
6233 messages: Vec<Message>,
6234 session: &codewhale_engine::session_manager::SavedSession,
6235 ) {
6236 self.session_write_receipt = session.write_receipt.clone();
6237 self.session_write_owner = session
6238 .write_receipt
6239 .as_ref()
6240 .map(|_| codewhale_engine::session_manager::SessionWriteOwner::control());
6241 let journal = session.journal.clone().unwrap_or_else(|| {
6242 codewhale_runtime::session_tree::SessionJournal::from_messages(
6243 session.messages.clone(),
6244 session.metadata.spawn_depth,
6245 )
6246 });
6247 self.install_restored_api_messages(messages, journal, session.journal_message_stamps());
6248 }
6249
6250 /// [`Self::restore_api_messages`] for a caller that owns the loaded
6251 /// session: the journal and the message history are *moved* out of it,
6252 /// not cloned, and the history goes through the owned restore projection,
6253 /// so a resume holds one copy of the transcript instead of three (memory
6254 /// note M3). `session.journal` and `session.messages` are left empty.
6255 pub fn restore_api_messages_from_owned(
6256 &mut self,
6257 session: &mut codewhale_engine::session_manager::SavedSession,
6258 ) {
6259 self.session_write_receipt = session.write_receipt.clone();
6260 self.session_write_owner = session
6261 .write_receipt
6262 .as_ref()
6263 .map(|_| codewhale_engine::session_manager::SessionWriteOwner::control());
6264 let stamps = session.journal_message_stamps();
6265 let journal = match session.journal.take() {
6266 Some(journal) => journal,
6267 // Legacy session without a journal: rebuild it from the saved
6268 // history, as the borrowing path does.
6269 None => codewhale_runtime::session_tree::SessionJournal::from_messages(
6270 session.messages.clone(),
6271 session.metadata.spawn_depth,
6272 ),
6273 };
6274 let messages = codewhale_engine::runtime_handoff::project_owned_messages_for_restore(
6275 std::mem::take(&mut session.messages),
6276 );
6277 self.install_restored_api_messages(messages, journal, stamps);
6278 }
6279
6280 fn install_restored_api_messages(
6281 &mut self,
6282 messages: Vec<Message>,
6283 journal: codewhale_runtime::session_tree::SessionJournal,
6284 stamps: Vec<DateTime<Utc>>,
6285 ) {
6286 self.session_journal = journal;
6287 self.api_message_stamps = stamps;
6288 self.api_message_stamps
6289 .resize_with(messages.len(), Utc::now);
6290 self.window_reroot_cause = Some("session_restore");
6291 self.last_billed_input_tokens = None;
6292 self.context_token_cache.get_mut().clear();
6293 self.api_messages = Arc::new(messages);
6294 }
6295
6296 pub fn clear_api_messages(&mut self) {
6297 self.session_journal = codewhale_runtime::session_tree::SessionJournal::new();
6298 self.api_messages_mut().clear();
6299 self.api_message_stamps.clear();
6300 self.window_reroot_cause = None;
6301 self.last_billed_input_tokens = None;
6302 self.session_turn_outcomes.clear();
6303 self.delegated_writes.clear();
6304 }
6305
6306 #[must_use]
6307 pub fn tool_collapse_active(&self) -> bool {
6308 self.tool_collapse_threshold > 0 && self.tool_collapse_mode.is_active(self.calm_mode)
6309 }
6310
6311 #[must_use]
6312 pub(crate) fn turn_fold_open_tail(&self) -> bool {
6313 self.is_loading || self.active_cell.is_some()
6314 }
6315
6316 #[must_use]
6317 pub(crate) fn echoed_queued_user_count(&self) -> usize {
6318 self.queued_messages
6319 .iter()
6320 .filter(|message| message.history_echoed && message.extension_command.is_none())
6321 .count()
6322 }
6323
6324 #[must_use]
6325 pub(crate) fn turn_fold_projection(&self) -> crate::tui::history::TurnFoldProjection {
6326 if !self.tool_collapse_active() {
6327 return crate::tui::history::TurnFoldProjection::default();
6328 }
6329 let active_entries = self
6330 .active_cell
6331 .as_ref()
6332 .map_or(&[][..], crate::tui::active_cell::ActiveCell::entries);
6333 let superseded_todos =
6334 crate::tui::history::superseded_todo_write_indices(&self.history, active_entries);
6335 crate::tui::history::detect_turn_folds(
6336 &self.history,
6337 active_entries,
6338 self.turn_fold_open_tail(),
6339 self.active_turn_user_index,
6340 self.echoed_queued_user_count(),
6341 &superseded_todos,
6342 &self.turn_work_durations,
6343 )
6344 }
6345
6346 #[must_use]
6347 pub(crate) fn folded_turn_at(&self, index: usize) -> Option<crate::tui::history::TurnFold> {
6348 self.turn_fold_projection()
6349 .turns
6350 .into_iter()
6351 .find(|turn| turn.host() == Some(index))
6352 .filter(|turn| !self.expanded_tool_runs.contains(&turn.key))
6353 }
6354
6355 #[must_use]
6356 pub fn tool_run_start_for_history_index(&self, index: usize) -> Option<usize> {
6357 if !self.tool_collapse_active() {
6358 return None;
6359 }
6360 let active_entries = self
6361 .active_cell
6362 .as_ref()
6363 .map_or(&[][..], crate::tui::active_cell::ActiveCell::entries);
6364 if index >= self.history.len().saturating_add(active_entries.len()) {
6365 return None;
6366 }
6367 let folds = self.turn_fold_projection();
6368 if folds.agents.contains(&index) {
6369 return Some(index);
6370 }
6371 let turn = folds.turn_containing(index).map(|turn| turn.key);
6372 if let Some(key) = turn.filter(|key| !self.expanded_tool_runs.contains(key)) {
6373 return Some(key);
6374 }
6375 crate::tui::history::detect_tool_runs_from_slices(
6376 &self.history,
6377 active_entries,
6378 self.tool_collapse_threshold,
6379 )
6380 .into_iter()
6381 .find(|run| index >= run.start && index < run.start.saturating_add(run.count))
6382 .map(|run| run.start)
6383 .or(turn)
6384 }
6385
6386 #[must_use]
6387 pub(crate) fn transcript_fold_header_at(&self, index: usize) -> bool {
6388 let Some(key) = self.tool_run_start_for_history_index(index) else {
6389 return false;
6390 };
6391 key == index
6392 || self
6393 .turn_fold_projection()
6394 .turns
6395 .iter()
6396 .any(|turn| turn.key == key && turn.host() == Some(index))
6397 }
6398
6399 pub fn toggle_tool_run_expansion_at(&mut self, index: usize) -> bool {
6400 let Some(start) = self.tool_run_start_for_history_index(index) else {
6401 return false;
6402 };
6403 if self.expanded_tool_runs.remove(&start) {
6404 self.show_command_result("Tool group collapsed".to_string(), StatusToastLevel::Info);
6405 } else {
6406 self.expanded_tool_runs.insert(start);
6407 self.show_command_result("Tool group expanded".to_string(), StatusToastLevel::Info);
6408 }
6409 self.mark_history_updated();
6410 true
6411 }
6412
6413 /// Bump the active-cell revision counter and request a redraw.
6414 ///
6415 /// Use this whenever an entry inside `active_cell` is mutated. The
6416 /// transcript cache combines this counter with `history_version` to
6417 /// produce a per-cell revision so the synthetic active-cell row can be
6418 /// re-rendered without invalidating committed history cells.
6419 pub fn bump_active_cell_revision(&mut self) {
6420 self.active_cell_revision = self.active_cell_revision.wrapping_add(1);
6421 if let Some(active) = self.active_cell.as_mut() {
6422 active.bump_revision();
6423 }
6424 self.history_version = self.history_version.wrapping_add(1);
6425 self.needs_redraw = true;
6426 }
6427
6428 /// Total number of cells in the *virtual* transcript: `history.len()`
6429 /// plus active cell entries (if any).
6430 #[must_use]
6431 pub fn virtual_cell_count(&self) -> usize {
6432 self.history.len() + self.active_cell.as_ref().map_or(0, ActiveCell::entry_count)
6433 }
6434
6435 #[must_use]
6436 pub fn original_cell_index_for_rendered(&self, rendered_index: usize) -> usize {
6437 self.collapsed_cell_map
6438 .get(rendered_index)
6439 .copied()
6440 .unwrap_or(rendered_index)
6441 }
6442
6443 /// Resolve a virtual cell index to either a committed history cell or an
6444 /// active-cell entry. Used by the pager / details lookup code so it can
6445 /// transparently address still-in-flight cells.
6446 #[must_use]
6447 pub fn cell_at_virtual_index(&self, index: usize) -> Option<&HistoryCell> {
6448 if index < self.history.len() {
6449 self.history.get(index)
6450 } else {
6451 let entry_idx = index - self.history.len();
6452 self.active_cell
6453 .as_ref()
6454 .and_then(|active| active.entries().get(entry_idx))
6455 }
6456 }
6457
6458 /// Resolve the tool-detail record for a committed or still-active virtual
6459 /// transcript cell.
6460 #[must_use]
6461 pub fn tool_detail_record_for_cell(&self, index: usize) -> Option<&ToolDetailRecord> {
6462 if let Some(detail) = self.tool_details_by_cell.get(&index) {
6463 return Some(detail);
6464 }
6465 let active_entry = |tool_id: &str| {
6466 self.active_cell
6467 .as_ref()
6468 .and_then(|active| active.entry_index_for_tool(tool_id))
6469 .map(|entry| self.history.len() + entry)
6470 };
6471 self.active_tool_details.values().find(|detail| {
6472 self.tool_cells.get(&detail.tool_id).copied() == Some(index)
6473 || active_entry(&detail.tool_id) == Some(index)
6474 })
6475 }
6476
6477 /// Whether a virtual transcript cell can open a meaningful `v` detail
6478 /// view. Thinking cells render their own raw text inline so there is no
6479 /// separate "raw" target. Error cells always get a full-message target so
6480 /// recovery instructions cannot be stranded below a short terminal view.
6481 #[must_use]
6482 pub fn cell_has_detail_target(&self, index: usize) -> bool {
6483 self.tool_detail_record_for_cell(index).is_some()
6484 || matches!(
6485 self.cell_at_virtual_index(index),
6486 Some(HistoryCell::Error { .. } | HistoryCell::Tool(_) | HistoryCell::SubAgent(_))
6487 )
6488 }
6489
6490 /// Space owner: selection, newest visible cell, then latest virtual cell.
6491 #[must_use]
6492 pub(crate) fn transcript_action_owner(&self) -> Option<TranscriptActionOwner> {
6493 let meta = self.viewport.transcript_cache.line_meta();
6494 let selected = self
6495 .viewport
6496 .transcript_selection
6497 .ordered_endpoints()
6498 .and_then(|(start, _)| meta.get(start.line_index));
6499 let start = self.viewport.last_transcript_top.min(meta.len());
6500 let end = start
6501 .saturating_add(self.viewport.last_transcript_visible)
6502 .min(meta.len());
6503 let cell_index = selected
6504 .into_iter()
6505 .chain(meta[start..end].iter().rev())
6506 .find_map(|meta| {
6507 meta.cell_line()
6508 .map(|(idx, _)| self.original_cell_index_for_rendered(idx))
6509 .filter(|&idx| self.cell_at_virtual_index(idx).is_some())
6510 })
6511 .or_else(|| self.virtual_cell_count().checked_sub(1))?;
6512 Some(TranscriptActionOwner {
6513 cell_index,
6514 identity_epoch: self.transcript_identity_epoch,
6515 })
6516 }
6517
6518 /// Pick the detail target for the current viewport. The footer hint and
6519 /// Alt+V both resolve through this so they agree on the target.
6520 #[must_use]
6521 pub(crate) fn transcript_owner_at_line(
6522 &self,
6523 line_index: usize,
6524 ) -> Option<TranscriptActionOwner> {
6525 let (rendered, _) = self
6526 .viewport
6527 .transcript_cache
6528 .line_meta()
6529 .get(line_index)?
6530 .cell_line()?;
6531 Some(TranscriptActionOwner {
6532 cell_index: self.original_cell_index_for_rendered(rendered),
6533 identity_epoch: self.transcript_identity_epoch,
6534 })
6535 }
6536
6537 pub(crate) fn selection_owner_cell(&self) -> Option<usize> {
6538 let selection = &self.viewport.transcript_selection;
6539 selection
6540 .owner
6541 .filter(|owner| {
6542 selection.is_active()
6543 && owner.identity_epoch == self.transcript_identity_epoch
6544 && self.cell_at_virtual_index(owner.cell_index).is_some()
6545 })
6546 .map(|owner| owner.cell_index)
6547 }
6548
6549 pub fn detail_cell_index_for_viewport(
6550 &self,
6551 top: usize,
6552 visible: usize,
6553 line_meta: &[TranscriptLineMeta],
6554 ) -> Option<usize> {
6555 let original = |meta: &TranscriptLineMeta| {
6556 meta.cell_line()
6557 .map(|(idx, _)| self.original_cell_index_for_rendered(idx))
6558 };
6559 let selected = self
6560 .selection_owner_cell()
6561 .or_else(|| {
6562 self.viewport
6563 .transcript_selection
6564 .ordered_endpoints()
6565 .and_then(|(start, _)| line_meta.get(start.line_index))
6566 .and_then(original)
6567 })
6568 .filter(|&idx| self.cell_has_detail_target(idx));
6569 let start = top.min(line_meta.len().saturating_sub(1));
6570 let end = start.saturating_add(visible).min(line_meta.len());
6571 let mut visible_cells = line_meta[start..end].iter().filter_map(original);
6572 // A visible error is the most urgent detail target. Prefer the newest
6573 // visible error over an earlier tool card so Alt+V opens the failure
6574 // the user is looking at, even when both occupy the viewport.
6575 selected
6576 .or_else(|| {
6577 visible_cells.clone().rev().find(|&idx| {
6578 matches!(
6579 self.cell_at_virtual_index(idx),
6580 Some(HistoryCell::Error { .. })
6581 )
6582 })
6583 })
6584 .or_else(|| visible_cells.find(|&idx| self.cell_has_detail_target(idx)))
6585 .or_else(|| {
6586 (0..self.virtual_cell_count())
6587 .rev()
6588 .find(|&idx| self.cell_has_detail_target(idx))
6589 })
6590 }
6591
6592 pub fn record_context_references(
6593 &mut self,
6594 history_cell: usize,
6595 message_index: usize,
6596 references: Vec<ContextReference>,
6597 ) {
6598 if references.is_empty() {
6599 return;
6600 }
6601 let records: Vec<SessionContextReference> = references
6602 .into_iter()
6603 .map(|reference| SessionContextReference {
6604 message_index,
6605 reference,
6606 })
6607 .collect();
6608 self.context_references_by_cell
6609 .insert(history_cell, records.clone());
6610 self.rebuild_session_context_references();
6611 self.needs_redraw = true;
6612 }
6613
6614 pub fn sync_context_references_from_session(
6615 &mut self,
6616 references: &[SessionContextReference],
6617 message_to_cell: &HashMap<usize, usize>,
6618 ) {
6619 self.context_references_by_cell.clear();
6620 for record in references {
6621 let Some(&cell_index) = message_to_cell.get(&record.message_index) else {
6622 continue;
6623 };
6624 self.context_references_by_cell
6625 .entry(cell_index)
6626 .or_default()
6627 .push(record.clone());
6628 }
6629 self.rebuild_session_context_references();
6630 }
6631
6632 fn rebuild_session_context_references(&mut self) {
6633 let mut records: Vec<SessionContextReference> = self
6634 .context_references_by_cell
6635 .values()
6636 .flat_map(|records| records.iter().cloned())
6637 .collect();
6638 records.sort_by_key(|record| record.message_index);
6639 self.session_context_references = records;
6640 }
6641
6642 /// Mutable variant of [`Self::cell_at_virtual_index`]. Bumps the
6643 /// appropriate revision counter (active-cell revision when targeting an
6644 /// in-flight entry, history version otherwise).
6645 /// Shift every binding that points *into the active cell* up by `added`,
6646 /// to keep it pointing at the same entry after `added` cells are appended
6647 /// to history.
6648 ///
6649 /// Bindings below `history.len()` address finalized cells and must not
6650 /// move. Only called when an active cell exists: with no active cell there
6651 /// are no virtual indices to re-base, and shifting would corrupt real ones.
6652 fn rebase_active_cell_bindings(&mut self, added: usize) {
6653 if added == 0 || self.active_cell.is_none() {
6654 return;
6655 }
6656 let boundary = self.history.len();
6657 // The same positional shift applies to presentation state. A late
6658 // orphan result must not inherit the active row's fold or Hide choice.
6659 self.cell_folds = std::mem::take(&mut self.cell_folds)
6660 .into_iter()
6661 .map(|(index, fold)| {
6662 (
6663 if index >= boundary {
6664 index.saturating_add(added)
6665 } else {
6666 index
6667 },
6668 fold,
6669 )
6670 })
6671 .collect();
6672 for indices in [&mut self.collapsed_cells, &mut self.expanded_tool_runs] {
6673 *indices = std::mem::take(indices)
6674 .into_iter()
6675 .map(|index| {
6676 if index >= boundary {
6677 index.saturating_add(added)
6678 } else {
6679 index
6680 }
6681 })
6682 .collect();
6683 }
6684 // A pre-insertion action still names the old virtual index. Reject
6685 // it until the renderer establishes the owner's new position.
6686 let previous_epoch = self.transcript_identity_epoch;
6687 self.transcript_identity_epoch = self.transcript_identity_epoch.wrapping_add(1);
6688 if let Some(owner) = self.viewport.transcript_selection.owner.as_mut()
6689 && owner.identity_epoch == previous_epoch
6690 {
6691 if owner.cell_index >= boundary {
6692 owner.cell_index = owner.cell_index.saturating_add(added);
6693 }
6694 owner.identity_epoch = self.transcript_identity_epoch;
6695 }
6696 for index in self
6697 .tool_cells
6698 .values_mut()
6699 .chain(self.pending_thinking_translation_cells.values_mut())
6700 {
6701 if *index >= boundary {
6702 *index = index.saturating_add(added);
6703 }
6704 }
6705 for (cell_index, _) in self.exploring_entries.values_mut() {
6706 if *cell_index >= boundary {
6707 *cell_index = cell_index.saturating_add(added);
6708 }
6709 }
6710 }
6711
6712 pub fn cell_at_virtual_index_mut(&mut self, index: usize) -> Option<&mut HistoryCell> {
6713 if index < self.history.len() {
6714 // Bump only the targeted cell's revision; leave every other
6715 // cell's cached render intact.
6716 self.resync_history_revisions();
6717 if let Some(rev) = self.history_revisions.get_mut(index) {
6718 let new_rev = self.next_history_revision;
6719 self.next_history_revision = self.next_history_revision.wrapping_add(1);
6720 *rev = new_rev;
6721 }
6722 self.history_version = self.history_version.wrapping_add(1);
6723 self.history.get_mut(index)
6724 } else {
6725 let entry_idx = index - self.history.len();
6726 self.active_cell_revision = self.active_cell_revision.wrapping_add(1);
6727 self.history_version = self.history_version.wrapping_add(1);
6728 self.active_cell
6729 .as_mut()
6730 .and_then(|active| active.entry_mut(entry_idx))
6731 }
6732 }
6733
6734 /// Drain the active cell into history. Companion maps that reference
6735 /// active-cell entries by virtual index (`tool_cells`,
6736 /// `tool_details_by_cell`) are rewritten to point at the new history
6737 /// indices. Idempotent — calling this when there is no active cell is a
6738 /// no-op.
6739 ///
6740 /// Caller is responsible for first marking in-progress entries with the
6741 /// terminal status they want (e.g. via
6742 /// [`ActiveCell::mark_in_progress_as_interrupted`]).
6743 pub fn flush_active_cell(&mut self) {
6744 let Some(mut active) = self.active_cell.take() else {
6745 self.streaming_thinking_active_entry = None;
6746 return;
6747 };
6748 if active.is_empty() {
6749 self.exploring_entries.clear();
6750 self.active_tool_details.clear();
6751 self.active_tool_entry_completed_at.clear();
6752 self.streaming_thinking_active_entry = None;
6753 self.bump_active_cell_revision();
6754 return;
6755 }
6756
6757 if let Some(entry_idx) = self.streaming_thinking_active_entry.take()
6758 && let Some(HistoryCell::Thinking { streaming, .. }) = active.entry_mut(entry_idx)
6759 {
6760 *streaming = false;
6761 }
6762
6763 let base_index = self.history.len();
6764 // Completed tools are removed from `tool_cells` before the active
6765 // group flushes, but `ActiveCell` deliberately keeps the stable
6766 // tool-to-entry binding until drain. Capture that binding first so
6767 // sequential or parallel tools in one model turn retain distinct raw
6768 // detail records instead of all falling back to the first cell.
6769 let detail_cell_indices: HashMap<String, usize> = self
6770 .active_tool_details
6771 .keys()
6772 .filter_map(|tool_id| {
6773 active
6774 .entry_index_for_tool(tool_id)
6775 .map(|entry_idx| (tool_id.clone(), base_index + entry_idx))
6776 })
6777 .collect();
6778 let drained = active.drain();
6779
6780 let mut details = std::mem::take(&mut self.active_tool_details);
6781 self.active_tool_entry_completed_at.clear();
6782 for (tool_id, detail) in details.drain() {
6783 let cell_index = detail_cell_indices
6784 .get(&tool_id)
6785 .copied()
6786 .or_else(|| self.tool_cells.get(&tool_id).copied())
6787 .unwrap_or(base_index);
6788 self.tool_details_by_cell
6789 .entry(cell_index)
6790 .or_insert(detail);
6791 }
6792
6793 crate::tui::tool_routing::release_oldest_tool_detail_outputs(self);
6794 self.exploring_entries.clear();
6795
6796 for cell in drained {
6797 let rev = self.fresh_history_revision();
6798 self.history.push(cell);
6799 self.history_revisions.push(rev);
6800 }
6801 self.history_version = self.history_version.wrapping_add(1);
6802 self.needs_redraw = true;
6803 let selection_has_range = self
6804 .viewport
6805 .transcript_selection
6806 .ordered_endpoints()
6807 .is_some_and(|(start, end)| start != end);
6808 if self.viewport.transcript_scroll.is_at_tail()
6809 && !self.viewport.transcript_selection.dragging
6810 && !selection_has_range
6811 && !self.user_scrolled_during_stream
6812 // While a worker's transcript owns the conversation area, its
6813 // pin governs the visible viewport: main-conversation activity
6814 // must not yank the user's read position in the focused
6815 // transcript (same stick-to-bottom rule as the main pane).
6816 && self
6817 .agent_focus
6818 .as_ref()
6819 .is_none_or(|focus| focus.scroll_top.is_none())
6820 {
6821 self.scroll_to_bottom();
6822 }
6823 // A foreground workflow's finish line waits for its start card to
6824 // leave the active group, so the transcript reads started → finished.
6825 self.announce_settled_workflows();
6826 }
6827
6828 /// Mark every still-running entry in the active cell as interrupted, then
6829 /// flush. Convenience helper for cancellation paths.
6830 pub fn finalize_active_cell_as_interrupted(&mut self) {
6831 if let Some(active) = self.active_cell.as_mut() {
6832 active.mark_in_progress_as_interrupted();
6833 }
6834 // A detached workflow outlives the turn that started it, and a
6835 // foreground one is cancelled by the engine, which says so with its
6836 // own `run_cancelled`. Neither is marked here.
6837 self.flush_active_cell();
6838 }
6839
6840 /// Apply one event to the run it names, creating that run's state on
6841 /// first sight. Runs are independent: a newer run never replaces one that
6842 /// is still going, so ten concurrent workflows are ten rows.
6843 ///
6844 /// Returns whether the event was applied. Only a run's start and end ask
6845 /// for a repaint here; progress leaves it to the caller, which paces a
6846 /// fan-out's event stream (#4095).
6847 pub fn apply_workflow_panel_event(
6848 &mut self,
6849 event_run_id: &str,
6850 event: crate::tui::widgets::workflow_panel::WorkflowPanelEvent,
6851 ) -> bool {
6852 use crate::tui::widgets::workflow_panel::{
6853 WorkflowPanel, WorkflowPanelEvent, WorkflowPanelLifecycle,
6854 };
6855 if event_run_id.trim().is_empty() {
6856 return false;
6857 }
6858 if let WorkflowPanelEvent::RunStarted { run_id, .. } = &event
6859 && run_id != event_run_id
6860 {
6861 return false;
6862 }
6863
6864 let lifecycle = matches!(
6865 &event,
6866 WorkflowPanelEvent::RunStarted { .. }
6867 | WorkflowPanelEvent::RunCompleted { .. }
6868 | WorkflowPanelEvent::RunCancelled { .. }
6869 );
6870 // #5528: a failed run must be loud, not just a row. Capture the
6871 // failure before the event is consumed below; the sticky notice fires
6872 // once per run because the live stream and the tool-complete hydration
6873 // can both deliver the same terminal event.
6874 let run_failure = match &event {
6875 WorkflowPanelEvent::RunCompleted {
6876 status: WorkflowPanelLifecycle::Failed,
6877 error,
6878 ..
6879 } => Some(error.clone()),
6880 _ => None,
6881 };
6882 // A cancelled run stays cancelled (the panel ignores a late
6883 // `run_completed`), so it must not raise a failure notice either.
6884 let existing = self
6885 .workflow_runs
6886 .iter()
6887 .position(|panel| panel.run_id == event_run_id);
6888 let already_failed = existing.is_some_and(|index| {
6889 matches!(
6890 self.workflow_runs[index].lifecycle,
6891 WorkflowPanelLifecycle::Failed | WorkflowPanelLifecycle::Cancelled
6892 )
6893 });
6894 match (existing, &event) {
6895 (Some(index), _) => self.workflow_runs[index].apply_event(event),
6896 (
6897 None,
6898 WorkflowPanelEvent::RunStarted {
6899 run_id,
6900 workflow_goal,
6901 workflow_id,
6902 at_ms,
6903 ..
6904 },
6905 ) => {
6906 let label = workflow_goal
6907 .clone()
6908 .or_else(|| workflow_id.clone())
6909 .unwrap_or_else(|| "workflow".to_string());
6910 let mut panel = WorkflowPanel::new(run_id.clone(), label, *at_ms);
6911 panel.locale = self.ui_locale;
6912 self.push_workflow_run(panel);
6913 }
6914 (None, _) => {
6915 // A late event for a run this view never saw start still
6916 // surfaces, under its id, rather than being dropped.
6917 let mut panel = WorkflowPanel::new(event_run_id, event_run_id, 0);
6918 panel.locale = self.ui_locale;
6919 panel.apply_event(event);
6920 self.push_workflow_run(panel);
6921 }
6922 }
6923 if lifecycle {
6924 self.needs_redraw = true;
6925 }
6926 if let Some(error) = run_failure
6927 && !already_failed
6928 {
6929 // The same reason the workbar and the finish row show: a failed
6930 // agent's own cause ("Authorization failed: …") when nothing
6931 // succeeded, not the run's aggregate summary.
6932 let detail = self
6933 .workflow_run(event_run_id)
6934 .and_then(WorkflowPanel::outcome_reason)
6935 .or_else(|| {
6936 error
6937 .as_deref()
6938 .map(str::trim)
6939 .filter(|detail| !detail.is_empty())
6940 .map(str::to_string)
6941 });
6942 let message = match detail.as_deref() {
6943 Some(detail) => format!(
6944 "{} · {}",
6945 self.tr(MessageId::WorkflowRunFailedToast),
6946 bound_agent_activity_text(detail)
6947 ),
6948 None => self.tr(MessageId::WorkflowRunFailedToast).into_owned(),
6949 };
6950 self.set_sticky_status(
6951 message,
6952 StatusToastLevel::Error,
6953 Some(Self::STICKY_ERROR_TTL_MS),
6954 );
6955 }
6956 self.announce_settled_workflows();
6957 true
6958 }
6959
6960 /// Most runs kept at once. Past it the oldest settled run goes first; a
6961 /// live run is never evicted.
6962 const MAX_WORKFLOW_RUNS: usize = 64;
6963
6964 pub(crate) fn push_workflow_run(
6965 &mut self,
6966 panel: crate::tui::widgets::workflow_panel::WorkflowPanel,
6967 ) {
6968 self.workflow_runs.push(panel);
6969 while self.workflow_runs.len() > Self::MAX_WORKFLOW_RUNS {
6970 let Some(oldest_settled) = self
6971 .workflow_runs
6972 .iter()
6973 .position(|run| run.lifecycle.is_terminal() && run.finish_announced)
6974 else {
6975 break;
6976 };
6977 self.workflow_runs.remove(oldest_settled);
6978 }
6979 }
6980
6981 /// The state of one run, by id.
6982 pub(crate) fn workflow_run(
6983 &self,
6984 run_id: &str,
6985 ) -> Option<&crate::tui::widgets::workflow_panel::WorkflowPanel> {
6986 self.workflow_runs.iter().find(|run| run.run_id == run_id)
6987 }
6988
6989 pub(crate) fn workflow_run_mut(
6990 &mut self,
6991 run_id: &str,
6992 ) -> Option<&mut crate::tui::widgets::workflow_panel::WorkflowPanel> {
6993 self.workflow_runs
6994 .iter_mut()
6995 .find(|run| run.run_id == run_id)
6996 }
6997
6998 /// Whether any workflow run is still going.
6999 pub(crate) fn workflow_run_live(&self) -> bool {
7000 self.workflow_runs
7001 .iter()
7002 .any(|run| run.lifecycle.is_running())
7003 }
7004
7005 /// A new turn clears settled rows from the workbar once nothing is still
7006 /// running — their finish lines are already in the transcript. While any
7007 /// run is live the settled ones stay, so a batch reads as one batch.
7008 pub(crate) fn prune_settled_workflow_runs(&mut self) {
7009 if self.workflow_run_live() {
7010 return;
7011 }
7012 let before = self.workflow_runs.len();
7013 self.workflow_runs
7014 .retain(|run| !(run.lifecycle.is_terminal() && run.finish_announced));
7015 if self.workflow_runs.len() != before {
7016 self.needs_redraw = true;
7017 }
7018 }
7019
7020 /// Write each settled run's finish line into the transcript, once. The
7021 /// line is a `workflow` card marked `transcript_line: finished`, so it
7022 /// reuses the card renderer and expands in Transcript mode.
7023 ///
7024 /// One row per run: when the call that started the run is already in
7025 /// history (its call returned, its record still says running) and the
7026 /// conversation has not moved past it, that card becomes the finish — the
7027 /// final state replaces `started` rather than stacking a second row under
7028 /// it. A run that settles after a later user message gets its finish at
7029 /// the tail, where it is seen. The card's tool-detail record is keyed
7030 /// separately and still holds what the model saw.
7031 ///
7032 /// While a `workflow` card is still in the active group (a foreground
7033 /// `run`, or a `start` whose turn has not flushed) the line waits: pushed
7034 /// now it would land above the card that started it. `flush_active_cell`
7035 /// calls back here once the card is in history.
7036 pub(crate) fn announce_settled_workflows(&mut self) {
7037 use crate::tui::history::{GenericToolCell, HistoryCell, ToolCell, ToolStatus};
7038 use crate::tui::widgets::workflow_panel::WorkflowPanelLifecycle;
7039 if !self
7040 .workflow_runs
7041 .iter()
7042 .any(|run| run.lifecycle.is_terminal() && !run.finish_announced)
7043 {
7044 return;
7045 }
7046 let card_in_flight = self.active_cell.as_ref().is_some_and(|active| {
7047 active.entries().iter().any(|cell| {
7048 matches!(cell, HistoryCell::Tool(ToolCell::Generic(tool)) if tool.name == "workflow")
7049 })
7050 });
7051 if card_in_flight {
7052 return;
7053 }
7054 let record_of = |tool: &GenericToolCell| {
7055 tool.output
7056 .as_deref()
7057 .and_then(|out| serde_json::from_str::<serde_json::Value>(out).ok())
7058 };
7059 // A foreground `run` card that returned its settled record already
7060 // shows the finish (history.rs); writing another would say it twice.
7061 let card_owns_finish = |history: &[HistoryCell], run_id: &str| {
7062 history.iter().rev().any(|cell| {
7063 let HistoryCell::Tool(ToolCell::Generic(tool)) = cell else {
7064 return false;
7065 };
7066 if tool.name != "workflow" || tool.status.is_active() {
7067 return false;
7068 }
7069 let Some(value) = record_of(tool) else {
7070 return false;
7071 };
7072 value.get("run_id").and_then(serde_json::Value::as_str) == Some(run_id)
7073 && value.get("transcript_line").is_none()
7074 && matches!(
7075 value.get("status").and_then(serde_json::Value::as_str),
7076 Some("completed" | "succeeded" | "degraded" | "failed" | "cancelled")
7077 )
7078 })
7079 };
7080 // The card that started this run, when it is still showing `started`
7081 // and still in the current exchange. The first card naming a run is
7082 // the one that launched it (the id does not exist before `start`); a
7083 // later `status` poll returns the same running shape and must not be
7084 // mistaken for it. Once the conversation has moved on (a user message
7085 // after the card), rewriting a row far up in scrollback would leave
7086 // nothing at the tail to say the run settled, so the finish is
7087 // appended instead. A card whose call is still running is left alone:
7088 // its result would overwrite the finish.
7089 let start_card = |history: &[HistoryCell], run_id: &str| {
7090 let first = history.iter().position(|cell| {
7091 let HistoryCell::Tool(ToolCell::Generic(tool)) = cell else {
7092 return false;
7093 };
7094 tool.name == "workflow"
7095 && record_of(tool).is_some_and(|value| {
7096 value.get("run_id").and_then(serde_json::Value::as_str) == Some(run_id)
7097 && value.get("transcript_line").is_none()
7098 })
7099 })?;
7100 let HistoryCell::Tool(ToolCell::Generic(tool)) = &history[first] else {
7101 return None;
7102 };
7103 let still_started = !tool.status.is_active()
7104 && record_of(tool).is_some_and(|value| {
7105 matches!(
7106 value.get("status").and_then(serde_json::Value::as_str),
7107 None | Some("running" | "pending" | "started")
7108 )
7109 });
7110 let same_exchange = !history[first + 1..]
7111 .iter()
7112 .any(|cell| matches!(cell, HistoryCell::User { .. }));
7113 (still_started && same_exchange).then_some(first)
7114 };
7115 let mut replaced = Vec::new();
7116 let mut lines = Vec::new();
7117 for run in &mut self.workflow_runs {
7118 if !run.lifecycle.is_terminal() || run.finish_announced {
7119 continue;
7120 }
7121 run.finish_announced = true;
7122 // A later card (a `status` poll, a foreground `run`) that returned
7123 // the settled record already shows the finish; rewriting the start
7124 // card too would say it twice.
7125 if card_owns_finish(&self.history, &run.run_id) {
7126 continue;
7127 }
7128 let start = start_card(&self.history, &run.run_id);
7129 let mut output = run.to_run_json();
7130 output["transcript_line"] = serde_json::Value::from("finished");
7131 let status = match run.lifecycle {
7132 WorkflowPanelLifecycle::Succeeded => ToolStatus::Success,
7133 WorkflowPanelLifecycle::Degraded => ToolStatus::Warning,
7134 _ => ToolStatus::Failed,
7135 };
7136 if let Some(index) = start
7137 && let Some(HistoryCell::Tool(ToolCell::Generic(card))) =
7138 self.history.get_mut(index)
7139 {
7140 card.status = status;
7141 card.output = Some(output.to_string());
7142 replaced.push(index);
7143 continue;
7144 }
7145 lines.push(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
7146 name: "workflow".to_string(),
7147 status,
7148 input_summary: None,
7149 output: Some(output.to_string()),
7150 prompts: None,
7151 spillover_path: None,
7152 output_summary: None,
7153 is_diff: false,
7154 })));
7155 }
7156 for index in replaced {
7157 self.bump_history_cell(index);
7158 }
7159 for line in lines {
7160 self.add_message(line);
7161 }
7162 self.needs_redraw = true;
7163 }
7164
7165 /// How long the "press Ctrl+C again to quit" prompt stays armed before it
7166 /// silently expires.
7167 pub const QUIT_CONFIRMATION_WINDOW: Duration = Duration::from_secs(2);
7168
7169 /// Arm the quit confirmation timer. The next Ctrl+C within
7170 /// [`Self::QUIT_CONFIRMATION_WINDOW`] should exit the app cleanly. Call this only
7171 /// from idle state — while a turn is in flight or a modal is open Ctrl+C
7172 /// retains its existing "interrupt this turn" / "close modal" semantics.
7173 ///
7174 /// A live cloud job survives the quit by design (its runner is
7175 /// detached), but its sandbox keeps billing until the next startup
7176 /// sweep reconciles it — so arming the quit prompt also surfaces that
7177 /// cost in the status line. Ctrl+D exits without arming and therefore
7178 /// without this warning.
7179 pub fn arm_quit(&mut self) {
7180 self.quit_armed_until = Some(Instant::now() + Self::QUIT_CONFIRMATION_WINDOW);
7181 // The armed state must be spoken, not silent: surface the localized
7182 // press-again hint as a typed toast with the same lifetime as the
7183 // confirmation window, so the user learns a second Ctrl+C exits.
7184 self.push_status_toast(
7185 self.tr(MessageId::FooterPressCtrlCAgain),
7186 StatusToastLevel::Info,
7187 Some(Self::QUIT_CONFIRMATION_WINDOW.as_millis() as u64),
7188 );
7189 }
7190
7191 /// Whether the quit timer is currently armed (i.e. a prior Ctrl+C set it
7192 /// and it hasn't expired yet).
7193 pub fn quit_is_armed(&self) -> bool {
7194 self.quit_armed_until
7195 .map(|deadline| Instant::now() < deadline)
7196 .unwrap_or(false)
7197 }
7198
7199 /// Clear the quit-armed timer. Call when expiry is detected on a tick or
7200 /// when the user takes any other action that should disarm the prompt
7201 /// (typing, sending a message, etc.).
7202 pub fn disarm_quit(&mut self) {
7203 if self.quit_armed_until.is_some() {
7204 self.quit_armed_until = None;
7205 self.needs_redraw = true;
7206 }
7207 }
7208
7209 /// Tick called from the redraw loop. Lets time-based UI state (the
7210 /// quit-armed prompt) expire even when no input event is delivered.
7211 pub fn tick_quit_armed(&mut self) {
7212 if let Some(deadline) = self.quit_armed_until
7213 && Instant::now() >= deadline
7214 {
7215 self.quit_armed_until = None;
7216 self.needs_redraw = true;
7217 }
7218 }
7219
7220 pub const RECEIPT_VISIBLE_DURATION: Duration = Duration::from_secs(8);
7221
7222 pub fn set_receipt_text(&mut self, text: impl Into<String>) {
7223 self.receipt_text = Some(text.into());
7224 self.receipt_started_at = Some(Instant::now());
7225 self.needs_redraw = true;
7226 }
7227
7228 pub fn clear_receipt(&mut self) {
7229 if self.receipt_text.is_some() || self.receipt_started_at.is_some() {
7230 self.receipt_text = None;
7231 self.receipt_started_at = None;
7232 self.needs_redraw = true;
7233 }
7234 }
7235
7236 /// Tick called from the redraw loop so transient receipts leave the UI
7237 /// without waiting for the next keypress.
7238 pub fn tick_receipt(&mut self) {
7239 if self
7240 .receipt_started_at
7241 .is_some_and(|started| started.elapsed() > Self::RECEIPT_VISIBLE_DURATION)
7242 {
7243 self.clear_receipt();
7244 }
7245 }
7246
7247 pub fn close_slash_menu(&mut self) {
7248 self.slash_menu_hidden = true;
7249 self.needs_redraw = true;
7250 }
7251
7252 /// Ceiling on how far the ambient clock advances per sampled frame.
7253 /// Bursty draw schedules (fast token streams) slow the aquarium down
7254 /// instead of teleporting creatures across the gap.
7255 pub const AMBIENT_MAX_STEP_MS: u128 = 260;
7256 /// Gentle-motion grace before a fully idle aquarium settles still.
7257 pub const AMBIENT_IDLE_SETTLE_MS: u64 = 6_000;
7258
7259 /// Advance and read the ambient animation clock. Every decorative
7260 /// position derives from this value; it moves by real elapsed time
7261 /// clamped to [`Self::AMBIENT_MAX_STEP_MS`] per sample, so motion stays
7262 /// continuous no matter how irregular the draw schedule is.
7263 pub fn sample_ambient_clock_ms(&mut self) -> u128 {
7264 let now = Instant::now();
7265 let step = self
7266 .ambient_clock_sampled_at
7267 .map(|last| {
7268 now.duration_since(last)
7269 .as_millis()
7270 .min(Self::AMBIENT_MAX_STEP_MS)
7271 })
7272 .unwrap_or(0);
7273 self.ambient_clock_sampled_at = Some(now);
7274 self.ambient_clock_ms = self.ambient_clock_ms.saturating_add(step);
7275 self.ambient_clock_ms
7276 }
7277
7278 /// Track idleness and report whether the ambient scene has settled.
7279 /// `busy` is the caller's aggregation of live activity signals (running
7280 /// turn, live sub-agents, active durable tasks, completion exhale, user
7281 /// browsing). While busy the idle anchor clears; once quiet, motion gets
7282 /// [`Self::AMBIENT_IDLE_SETTLE_MS`] of grace and then stills.
7283 pub fn ambient_idle_settled(&mut self, busy: bool, now: Instant) -> bool {
7284 if busy {
7285 self.ambient_idle_since = None;
7286 self.ambient_life_held_ms = None;
7287 return false;
7288 }
7289 let since = *self.ambient_idle_since.get_or_insert(now);
7290 let settled =
7291 now.duration_since(since) >= Duration::from_millis(Self::AMBIENT_IDLE_SETTLE_MS);
7292 if settled {
7293 self.ambient_life_held_ms
7294 .get_or_insert(self.ambient_clock_ms);
7295 }
7296 settled
7297 }
7298
7299 /// Resolve one motion policy for every surface that can request or paint
7300 /// animation. `fancy_animations = false` is a true still mode even when
7301 /// the separate accessibility preference is left at its default.
7302 #[must_use]
7303 pub(crate) fn motion_policy(&self) -> MotionPolicy {
7304 MotionPolicy::from_settings(
7305 self.low_motion,
7306 self.fancy_animations,
7307 self.constrained_frame_rate,
7308 )
7309 }
7310
7311 /// Resolve the `[title] …` window-title prefix for the terminal title.
7312 ///
7313 /// Precedence: the session-level `/title` override wins over the `title`
7314 /// config default; neither configured means no prefix (the historical
7315 /// window titles stay byte-for-byte unchanged). This is deliberately
7316 /// independent of [`session_title`](Self::session_title) — the session
7317 /// *name* keeps identifying the composer border and picker, while this
7318 /// prefix only decorates the terminal window/tab title.
7319 #[must_use]
7320 pub(crate) fn window_title_prefix(&self) -> Option<&str> {
7321 self.window_title
7322 .as_deref()
7323 .or(self.title_default.as_deref())
7324 .filter(|prefix| !prefix.trim().is_empty())
7325 }
7326
7327 /// Bridge the centralized policy into transcript renderers that still
7328 /// accept the legacy boolean motion contract.
7329 #[must_use]
7330 pub(crate) fn effective_low_motion_for_status(&self) -> bool {
7331 self.motion_policy().as_low_motion()
7332 }
7333
7334 pub fn transcript_render_options(&self) -> TranscriptRenderOptions {
7335 TranscriptRenderOptions {
7336 superseded_work_receipt: false,
7337 newest_user_turn: false,
7338 locale: self.ui_locale,
7339 show_thinking: self.show_thinking,
7340 thinking_checkpoints: self.thinking_read_window.projection(),
7341 thinking_highlight: self.thinking_highlight,
7342 thinking_default_expanded: self.thinking_default_expanded,
7343 thinking_preview_lines: self.thinking_preview_lines,
7344 verbose: self.verbose_transcript,
7345 show_tool_details: self.show_tool_details,
7346 inline_diff_mode: self.inline_diff_mode,
7347 calm_mode: self.calm_mode,
7348 low_motion: self.effective_low_motion_for_status(),
7349 motion_mode: self.motion_policy().mode(),
7350 spacing: self.transcript_spacing,
7351 palette_mode: self.ui_theme.mode,
7352 prose_measure: self.prose_measure,
7353 }
7354 }
7355
7356 /// Handle terminal resize event.
7357 pub fn handle_resize(&mut self, width: u16, height: u16) {
7358 let preserved_scroll = (!self.viewport.transcript_scroll.is_at_tail())
7359 .then_some(self.viewport.last_transcript_top);
7360 // Wrapped rows already key themselves by width and render options.
7361 // Height changes only affect the final reasoning preview (#6652).
7362 self.viewport.pending_terminal_size = Some(ratatui::layout::Size::new(width, height));
7363
7364 if let Some(top) = preserved_scroll {
7365 self.viewport.transcript_scroll = TranscriptScroll::at_line(top);
7366 }
7367
7368 self.viewport.pending_scroll_delta = 0;
7369 self.viewport.transcript_selection.clear();
7370
7371 self.viewport.last_transcript_area = None;
7372 self.viewport.last_prompt_area = None;
7373 self.viewport.last_transcript_top = 0;
7374 // Seed visible height from the resize event so paging keys use a
7375 // useful page size immediately, before the next render updates it.
7376 self.viewport.last_transcript_visible = (height as usize).saturating_sub(2).max(1);
7377 self.viewport.last_transcript_total = 0;
7378 self.viewport.last_transcript_padding_top = 0;
7379 self.viewport.jump_to_latest_button_area = None;
7380 self.viewport.pinned_prompt_area = None;
7381 self.viewport.pinned_prompt_message = None;
7382
7383 self.needs_redraw = true;
7384 }
7385
7386 pub fn scroll_up(&mut self, amount: usize) {
7387 let delta = i32::try_from(amount).unwrap_or(i32::MAX);
7388 self.viewport.pending_scroll_delta =
7389 self.viewport.pending_scroll_delta.saturating_sub(delta);
7390 self.user_scrolled_during_stream = true;
7391 self.needs_redraw = true;
7392 }
7393
7394 pub fn scroll_down(&mut self, amount: usize) {
7395 let delta = i32::try_from(amount).unwrap_or(i32::MAX);
7396 self.viewport.pending_scroll_delta =
7397 self.viewport.pending_scroll_delta.saturating_add(delta);
7398 self.user_scrolled_during_stream = true;
7399 self.needs_redraw = true;
7400 }
7401
7402 pub fn scroll_to_bottom(&mut self) {
7403 self.viewport.transcript_scroll = TranscriptScroll::to_bottom();
7404 self.viewport.pending_scroll_delta = 0;
7405 self.viewport.jump_to_latest_button_area = None;
7406 self.user_scrolled_during_stream = false;
7407 // While a worker's transcript owns the conversation area, the
7408 // jump-to-bottom affordances (Ctrl+End, Alt+G, the jump-to-latest
7409 // button, sending a follow-up) must release its pin too: the two
7410 // surfaces share one command set, so returning to the live tail has
7411 // to mean the tail the user is actually looking at.
7412 if let Some(focus) = self.agent_focus.as_mut() {
7413 focus.scroll_top = None;
7414 }
7415 self.needs_redraw = true;
7416 }
7417
7418 /// Jump the transcript viewport so rendered line `line` becomes its top
7419 /// row. The pinned prompt header calls this to return to the user message
7420 /// it names. Mirrors the wheel/scrollbar path: pending wheel deltas are
7421 /// dropped so the jump lands where it was asked to, and the viewport
7422 /// leaves the live tail.
7423 pub fn scroll_to_transcript_line(&mut self, line: usize) {
7424 self.viewport.transcript_scroll = TranscriptScroll::at_line(line);
7425 self.viewport.pending_scroll_delta = 0;
7426 // `at_line` is never the tail sentinel, so this reads as `true` today;
7427 // keep the same expression the scrollbar-jump path uses so the two
7428 // stay in step if `at_line` ever clamps to tail on its own.
7429 self.user_scrolled_during_stream = !self.viewport.transcript_scroll.is_at_tail();
7430 self.needs_redraw = true;
7431 }
7432
7433 /// First rendered line of the user message named by the pinned prompt
7434 /// header, resolved against the current transcript layout.
7435 ///
7436 /// The header records the message, not a line offset, and this resolves
7437 /// that identity at click time — a rewrite between paint and click then
7438 /// cannot land the jump on a stale offset. Returns `None` when the
7439 /// message is no longer rendered (collapsed or filtered out), so a stale
7440 /// click cannot teleport the viewport.
7441 pub fn pinned_prompt_target_line(&self) -> Option<usize> {
7442 let message = self.viewport.pinned_prompt_message?;
7443 let map = &self.collapsed_cell_map;
7444 self.viewport
7445 .transcript_cache
7446 .line_meta()
7447 .iter()
7448 .enumerate()
7449 .find_map(|(line_index, meta)| {
7450 let TranscriptLineMeta::CellLine {
7451 cell_index,
7452 line_in_cell: 0,
7453 ..
7454 } = meta
7455 else {
7456 return None;
7457 };
7458 let original = map.get(*cell_index).copied().unwrap_or(*cell_index);
7459 (original == message).then_some(line_index)
7460 })
7461 }
7462
7463 pub(crate) fn follow_up_queue_full(&self) -> bool {
7464 self.queued_messages.len() + self.preparing_steers.len() >= MAX_QUEUED_MESSAGES
7465 }
7466
7467 pub fn queue_message(&mut self, message: QueuedMessage) {
7468 if message.extension_command.is_some() {
7469 self.restore_unsent_message(message);
7470 return;
7471 }
7472 if self.follow_up_queue_full() {
7473 self.restore_unsent_message(message);
7474 let notice = self
7475 .tr(MessageId::QueueFullNotice)
7476 .replace("{max}", &MAX_QUEUED_MESSAGES.to_string());
7477 self.push_status_toast(notice, StatusToastLevel::Warning, None);
7478 return;
7479 }
7480 self.queued_messages.push_back(message);
7481 }
7482
7483 pub fn pop_queued_message(&mut self) -> Option<QueuedMessage> {
7484 if self.held_restored_queue > 0 {
7485 return None;
7486 }
7487 self.remove_queued_message(0)
7488 }
7489
7490 pub(crate) fn settle_queue_after_turn(
7491 &mut self,
7492 status: codewhale_engine::core::events::TurnOutcomeStatus,
7493 ) -> Option<QueuedMessage> {
7494 if status == codewhale_engine::core::events::TurnOutcomeStatus::Completed {
7495 self.pop_queued_message()
7496 } else {
7497 self.held_restored_queue = self.queued_messages.len();
7498 if self.queued_draft.is_some() {
7499 self.queued_draft_was_held = true;
7500 }
7501 None
7502 }
7503 }
7504
7505 pub fn remove_queued_message(&mut self, index: usize) -> Option<QueuedMessage> {
7506 let message = self.take_queued_message_for_dispatch(index)?;
7507 let mut removed_index = index;
7508 for pending in self.preparing_steers.iter_mut().rev() {
7509 removed_index = pending.forget_queue_position(removed_index);
7510 }
7511 Some(message)
7512 }
7513
7514 pub(crate) fn clear_visible_queued_messages(&mut self) {
7515 while let Some(index) = self.queued_messages.len().checked_sub(1) {
7516 self.remove_queued_message(index);
7517 }
7518 }
7519
7520 pub(crate) fn take_queued_message_for_dispatch(
7521 &mut self,
7522 index: usize,
7523 ) -> Option<QueuedMessage> {
7524 let message = self.queued_messages.remove(index)?;
7525 if index < self.held_restored_queue {
7526 self.held_restored_queue -= 1;
7527 }
7528 Some(message)
7529 }
7530
7531 pub fn queued_message_count(&self) -> usize {
7532 self.queued_messages.len()
7533 }
7534
7535 /// Pop the most-recently queued message back into the composer for editing
7536 /// (issue #85 — ↑ affordance). The popped message is parked in
7537 /// [`Self::queued_draft`] so the next Enter re-queues it carrying its
7538 /// original skill instruction. No-op if the composer already has typed
7539 /// content or a draft is already being edited — surfacing the affordance
7540 /// would be ambiguous in either case.
7541 ///
7542 /// Returns `true` when the composer state was mutated.
7543 pub fn pop_last_queued_into_draft(&mut self) -> bool {
7544 let Some(last) = self.queued_messages.len().checked_sub(1) else {
7545 return false;
7546 };
7547 self.pop_queued_into_draft(last)
7548 }
7549
7550 /// Same as [`Self::pop_last_queued_into_draft`] for the oldest held
7551 /// message, so a backlog stays in the order it was typed.
7552 pub fn pop_first_queued_into_draft(&mut self) -> bool {
7553 self.pop_queued_into_draft(0)
7554 }
7555
7556 fn pop_queued_into_draft(&mut self, index: usize) -> bool {
7557 if !self.input.is_empty() || self.queued_draft.is_some() {
7558 return false;
7559 }
7560 let was_held = index < self.held_restored_queue;
7561 let Some(msg) = self.remove_queued_message(index) else {
7562 return false;
7563 };
7564 self.held_restored_queue = self.held_restored_queue.min(self.queued_messages.len());
7565 self.input = msg.display.clone();
7566 self.cursor_position = char_count(&self.input);
7567 self.selected_attachment_index = None;
7568 self.queued_draft = Some(msg);
7569 self.queued_draft_was_held = was_held;
7570 self.needs_redraw = true;
7571 true
7572 }
7573
7574 /// Stop editing a queued follow-up and return it to the held or live queue.
7575 pub fn cancel_queued_draft_edit(&mut self) -> bool {
7576 let Some(draft) = self.queued_draft.take() else {
7577 return false;
7578 };
7579 let was_held = std::mem::take(&mut self.queued_draft_was_held);
7580 if was_held {
7581 let insert_index = self.held_restored_queue.min(self.queued_messages.len());
7582 self.queued_messages.insert(insert_index, draft);
7583 self.held_restored_queue = insert_index + 1;
7584 let mut shifted_index = insert_index;
7585 for pending in self.preparing_steers.iter_mut().rev() {
7586 shifted_index = pending.shift_for_queue_insert(shifted_index);
7587 }
7588 } else {
7589 self.queued_messages.push_back(draft);
7590 }
7591 self.clear_input_recoverable();
7592 self.needs_redraw = true;
7593 true
7594 }
7595
7596 /// Decide how to route a fresh non-empty composer submit.
7597 ///
7598 /// Running turns always queue bare-Enter submissions. Ctrl+Enter is the
7599 /// single explicit gesture for amending the active turn, regardless of
7600 /// whether the provider has emitted its first token yet.
7601 ///
7602 /// Truth table:
7603 /// offline=F, busy=F → Immediate
7604 /// offline=F, busy=T, streaming=* → Queue (Ctrl+Enter steers)
7605 /// offline=T, busy=* → Queue
7606 #[must_use]
7607 pub fn decide_submit_disposition(&self) -> SubmitDisposition {
7608 if self.offline_mode {
7609 return SubmitDisposition::Queue;
7610 }
7611 // A spawned dispatch is still resolving route/sending the op (#4605);
7612 // queue rather than spawn a second dispatch that could reorder ops.
7613 if self.dispatch_in_flight {
7614 return SubmitDisposition::Queue;
7615 }
7616 if !self.is_loading {
7617 return SubmitDisposition::Immediate;
7618 }
7619 // Busy: queue the message. Steer is an explicit Ctrl+Enter gesture,
7620 // not a timing-sensitive change in bare Enter behavior.
7621 SubmitDisposition::Queue
7622 }
7623
7624 /// Resolve Enter-shaped input from the same state used by composer hints.
7625 ///
7626 /// Bare Enter is portable across supported terminals: it sends while idle,
7627 /// queues while busy, and an empty Enter sends the oldest queued message
7628 /// now, into the active turn or as a new one. Ctrl+Enter remains accepted
7629 /// when a terminal can report it distinctly, but is intentionally not
7630 /// advertised because many terminals encode it exactly like Enter.
7631 #[must_use]
7632 pub fn decide_composer_submit(&self, chord: ComposerSubmitChord) -> ComposerSubmitAction {
7633 if self.input.is_empty() {
7634 if !self.offline_mode && self.queued_draft.is_none() && !self.queued_messages.is_empty()
7635 {
7636 return ComposerSubmitAction::SendQueuedNow;
7637 }
7638 return ComposerSubmitAction::Noop;
7639 }
7640
7641 let disposition = match chord {
7642 ComposerSubmitChord::Enter => self.decide_submit_disposition(),
7643 ComposerSubmitChord::CtrlEnter
7644 if self.is_loading && !self.offline_mode && !self.dispatch_in_flight =>
7645 {
7646 SubmitDisposition::Steer
7647 }
7648 ComposerSubmitChord::CtrlEnter => self.decide_submit_disposition(),
7649 };
7650 ComposerSubmitAction::Submit(disposition)
7651 }
7652
7653 /// Mark the in-flight streaming Assistant cell as interrupted: prepend
7654 /// `[interrupted]` to whatever streamed so far (so the user can see what
7655 /// was salvaged) and flip `streaming` off so the spinner halts. No-op if
7656 /// no Assistant cell is currently streaming.
7657 ///
7658 /// Deliberate divergence from openai/codex which discards partial output
7659 /// on abort — V4 thinking is expensive and the user usually wants to see
7660 /// what the model produced before steering.
7661 pub fn finalize_streaming_assistant_as_interrupted(&mut self) {
7662 let Some(index) = self.streaming_message_index.take() else {
7663 return;
7664 };
7665 if let Some(HistoryCell::Assistant { content, streaming }) = self.history.get_mut(index) {
7666 *streaming = false;
7667 if content.is_empty() {
7668 *content = "[interrupted]".to_string();
7669 } else if !content.starts_with("[interrupted]") {
7670 content.insert_str(0, "[interrupted] ");
7671 }
7672 }
7673 self.bump_history_cell(index);
7674 }
7675
7676 /// Retry a `try_lock` up to `retries` times, yielding the thread between
7677 /// attempts. Returns `Some(guard)` on success, `None` if the lock
7678 /// remains contended after all retries. Reached from the async UI/event
7679 /// paths, so this must not park a Tokio worker with `thread::sleep` —
7680 /// `yield_now` covers the microsecond-scale critical sections behind
7681 /// these mutexes, and a still-contended lock degrades to `None`.
7682 fn retry_lock<T>(
7683 mutex: &tokio::sync::Mutex<T>,
7684 retries: u32,
7685 ) -> Option<tokio::sync::MutexGuard<'_, T>> {
7686 for _ in 0..retries {
7687 if let Ok(guard) = mutex.try_lock() {
7688 return Some(guard);
7689 }
7690 std::thread::yield_now();
7691 }
7692 None
7693 }
7694
7695 /// Capture the durable Work state without ever converting lock contention
7696 /// into an empty snapshot.
7697 pub fn work_state_snapshot(&self) -> Result<Option<SessionWorkState>, String> {
7698 if let Some(work) = self.runtime_services.work.as_ref() {
7699 return work
7700 .capture(self.current_session_id.as_deref())
7701 .map(|state| {
7702 state.map(|state| SessionWorkState {
7703 graph: Some(state.graph),
7704 todos: state.todos,
7705 plan: state.plan,
7706 })
7707 });
7708 }
7709 let todos = Self::retry_lock(&self.todos, 100)
7710 .ok_or_else(|| "To-do state is busy; try saving again".to_string())?;
7711 let plan = Self::retry_lock(&self.plan_state, 100)
7712 .ok_or_else(|| "Plan state is busy; try saving again".to_string())?;
7713 let state = SessionWorkState {
7714 graph: None,
7715 todos: todos.snapshot(),
7716 plan: plan.snapshot(),
7717 };
7718 Ok((!state.is_empty()).then_some(state))
7719 }
7720
7721 /// Non-blocking snapshot for the render/event loop. Automatic persistence
7722 /// must skip a contended first save instead of pausing the UI or writing a
7723 /// false empty state.
7724 pub fn try_work_state_snapshot(&mut self) -> Result<Option<SessionWorkState>, String> {
7725 if let Some(work) = self.runtime_services.work.as_ref() {
7726 let state = work
7727 .try_capture(self.current_session_id.as_deref())
7728 .map(|state| {
7729 state.map(|state| SessionWorkState {
7730 graph: Some(state.graph),
7731 todos: state.todos,
7732 plan: state.plan,
7733 })
7734 })?;
7735 self.last_known_work_state = Some(state.clone());
7736 return Ok(state);
7737 }
7738 let todos = self
7739 .todos
7740 .try_lock()
7741 .map_err(|_| "To-do state is busy".to_string())?;
7742 let plan = self
7743 .plan_state
7744 .try_lock()
7745 .map_err(|_| "Plan state is busy".to_string())?;
7746 let state = SessionWorkState {
7747 graph: None,
7748 todos: todos.snapshot(),
7749 plan: plan.snapshot(),
7750 };
7751 let state = (!state.is_empty()).then_some(state);
7752 drop(plan);
7753 drop(todos);
7754 self.last_known_work_state = Some(state.clone());
7755 Ok(state)
7756 }
7757
7758 /// Atomically replace the live Work state from a saved session.
7759 pub fn restore_work_state(
7760 &mut self,
7761 session_id: &str,
7762 workspace: &Path,
7763 state: Option<&SessionWorkState>,
7764 ) -> Result<(), String> {
7765 if let Some(work) = self.runtime_services.work.as_ref() {
7766 let empty = SessionWorkState::default();
7767 let state = state.unwrap_or(&empty);
7768 let restored = work.restore_with_workspace_owner_bindings(
7769 session_id,
7770 workspace,
7771 state.graph.as_ref(),
7772 &state.todos,
7773 &state.plan,
7774 )?;
7775 let normalized_state = restored.map(|state| SessionWorkState {
7776 graph: Some(state.graph),
7777 todos: state.todos,
7778 plan: state.plan,
7779 });
7780 self.work_surface.record_restored_session(
7781 session_id,
7782 normalized_state
7783 .as_ref()
7784 .and_then(|state| state.graph.as_ref()),
7785 );
7786 self.last_known_work_state = Some(normalized_state);
7787 return Ok(());
7788 }
7789 let (restored_todos, restored_plan) = match state {
7790 Some(state) => (
7791 TodoList::from_snapshot(&state.todos)?,
7792 PlanState::from_snapshot(&state.plan),
7793 ),
7794 None => (TodoList::new(), PlanState::default()),
7795 };
7796 let normalized_state = SessionWorkState {
7797 graph: None,
7798 todos: restored_todos.snapshot(),
7799 plan: restored_plan.snapshot(),
7800 };
7801
7802 let mut todos = Self::retry_lock(&self.todos, 100)
7803 .ok_or_else(|| "To-do state is busy; session was not restored".to_string())?;
7804 let mut plan = Self::retry_lock(&self.plan_state, 100)
7805 .ok_or_else(|| "Plan state is busy; session was not restored".to_string())?;
7806 *todos = restored_todos;
7807 *plan = restored_plan;
7808 drop(plan);
7809 drop(todos);
7810 self.work_surface.record_restored_session(session_id, None);
7811 self.last_known_work_state =
7812 Some((!normalized_state.is_empty()).then_some(normalized_state));
7813 Ok(())
7814 }
7815
7816 pub fn clear_todos(&mut self) -> bool {
7817 if let Some(work) = self.runtime_services.work.as_ref() {
7818 if !work.clear(self.current_session_id.as_deref()) {
7819 return false;
7820 }
7821 self.last_known_work_state = Some(None);
7822 return true;
7823 }
7824 // Acquire both stores before mutating either one. `/clear` must never
7825 // report success after clearing only half of the Work surface.
7826 let Some(mut todos) = Self::retry_lock(&self.todos, 100) else {
7827 return false;
7828 };
7829 let Some(mut plan) = Self::retry_lock(&self.plan_state, 100) else {
7830 return false;
7831 };
7832 todos.clear();
7833 *plan = PlanState::default();
7834 drop(plan);
7835 drop(todos);
7836 self.last_known_work_state = Some(None);
7837 true
7838 }
7839
7840 pub fn publish_saved_work_state(
7841 &mut self,
7842 owner: Option<&str>,
7843 state: Option<&SessionWorkState>,
7844 ) -> Result<bool, String> {
7845 let Some(work) = self.runtime_services.work.as_ref() else {
7846 return Ok(false);
7847 };
7848 let published = work
7849 .publish_pending_sync_matching(owner, state.and_then(|state| state.graph.as_ref()))?;
7850 if !published && work.has_pending_publish() {
7851 return Err("a newer Work update remains pending".to_string());
7852 }
7853 Ok(published)
7854 }
7855
7856 pub fn update_model_compaction_budget(&mut self) {
7857 let (provider, model, limits, window) = self.effective_budget_route();
7858 let model = model.to_string();
7859 self.compact_threshold =
7860 codewhale_engine::route_budget::compaction_threshold_for_route_at_percent_with_window(
7861 provider,
7862 &model,
7863 limits,
7864 window.map(|window| window.tokens),
7865 self.auto_compact_threshold_percent,
7866 );
7867 if !self.auto_compact_user_configured {
7868 self.auto_compact = codewhale_engine::route_budget::auto_compact_default_for_route(
7869 provider, &model, limits,
7870 );
7871 }
7872 }
7873
7874 pub fn set_active_route_limits(&mut self, limits: RouteLimits) {
7875 self.active_route_limits = codewhale_engine::route_budget::known_route_limits(limits);
7876 }
7877
7878 /// Install an already-resolved runtime route receipt in one operation so
7879 /// endpoint-sensitive reasoning and context reporting cannot drift apart.
7880 pub fn set_active_route_resolution(
7881 &mut self,
7882 base_url: impl Into<String>,
7883 limits: RouteLimits,
7884 context_window: codewhale_engine::route_runtime::ContextWindowResolution,
7885 ) {
7886 self.active_route_base_url = base_url.into();
7887 self.set_active_route_limits(limits);
7888 self.active_context_window_source = context_window.source;
7889 self.active_context_window = Some(context_window);
7890 }
7891
7892 /// Refresh the operator-configured windows for the active provider
7893 /// identity: the provider-level default plus its per-model table (#6108).
7894 pub fn set_active_context_window_override(
7895 &mut self,
7896 config: &codewhale_runtime::config::Config,
7897 identity: &codewhale_runtime::config::ProviderIdentity,
7898 ) {
7899 self.active_context_window_override = config.context_window_for_provider_config(identity);
7900 self.active_model_context_windows = config.model_context_windows_for(identity).cloned();
7901 self.active_context_window = self.configured_context_window_for(&self.model.clone());
7902 if let Some(resolution) = self.active_context_window {
7903 self.active_context_window_source = resolution.source;
7904 }
7905 if self.active_route_limits.is_none() {
7906 self.active_route_limits = self.context_window_override_limits();
7907 }
7908 }
7909
7910 /// Effective operator-configured window for an exact wire model id on the
7911 /// active provider: a `model_context_windows` hit wins over the provider
7912 /// default (#6108). `None` when the operator configured neither rung.
7913 pub(crate) fn configured_context_window_for(
7914 &self,
7915 model: &str,
7916 ) -> Option<codewhale_engine::route_runtime::ContextWindowResolution> {
7917 self.active_model_context_windows
7918 .as_ref()
7919 .and_then(|table| table.get(model).copied())
7920 .filter(|window| *window > 0)
7921 .map(
7922 |tokens| codewhale_engine::route_runtime::ContextWindowResolution {
7923 tokens,
7924 source: codewhale_engine::route_runtime::ContextWindowSource::ConfiguredModel,
7925 },
7926 )
7927 .or_else(|| {
7928 self.active_context_window_override
7929 .filter(|window| *window > 0)
7930 .map(
7931 |tokens| codewhale_engine::route_runtime::ContextWindowResolution {
7932 tokens,
7933 source:
7934 codewhale_engine::route_runtime::ContextWindowSource::Configured,
7935 },
7936 )
7937 })
7938 }
7939
7940 pub fn context_window_override_limits(&self) -> Option<RouteLimits> {
7941 self.configured_context_window_for(&self.model)
7942 .map(|resolution| RouteLimits {
7943 context_tokens: Some(u64::from(resolution.tokens)),
7944 ..RouteLimits::default()
7945 })
7946 }
7947
7948 pub fn set_model_selection(&mut self, model: String) {
7949 let auto_model = model.trim().eq_ignore_ascii_case("auto");
7950 let model_changed = self.model != model || self.auto_model != auto_model;
7951 self.model = if auto_model {
7952 "auto".to_string()
7953 } else {
7954 model
7955 };
7956 self.auto_model = auto_model;
7957 if model_changed {
7958 self.active_route_limits = self.context_window_override_limits();
7959 self.active_context_window = self.configured_context_window_for(&self.model);
7960 self.active_context_window_source = self.active_context_window.map_or_else(
7961 || {
7962 codewhale_engine::route_runtime::resolve_context_window(
7963 self.api_provider,
7964 &self.model,
7965 self.active_route_limits,
7966 None,
7967 None,
7968 )
7969 .source
7970 },
7971 |window| window.source,
7972 );
7973 }
7974 self.last_effective_model = None;
7975 self.last_effective_budget = None;
7976 self.last_effective_provider = None;
7977 self.last_effective_provider_identity = None;
7978 self.last_auto_route_receipt = None;
7979 self.pending_auto_route_receipt = None;
7980 self.last_effective_reasoning_effort = None;
7981 // Auto model routing is independent from an explicitly requested raw
7982 // reasoning tier. Never reuse the route-normalized live value here:
7983 // fixed DeepSeek can collapse low→high and Codex off→low.
7984 if auto_model {
7985 self.reasoning_effort = self
7986 .reasoning_effort_preference
7987 .unwrap_or(ReasoningEffort::Auto);
7988 } else {
7989 let requested = self
7990 .reasoning_effort_preference
7991 .unwrap_or(self.reasoning_effort);
7992 self.reasoning_effort = requested.normalize_for_provider(self.api_provider);
7993 }
7994 }
7995
7996 pub fn model_selection_for_persistence(&self) -> String {
7997 if self.auto_model || self.model.trim().eq_ignore_ascii_case("auto") {
7998 "auto".to_string()
7999 } else {
8000 self.model.clone()
8001 }
8002 }
8003
8004 /// Atomic latest Auto route metadata for session snapshots. The provider,
8005 /// exact identity, model, and receipt are either persisted together or
8006 /// omitted together so a resumed session cannot display a mixed route.
8007 #[must_use]
8008 pub(crate) fn auto_route_for_persistence(
8009 &self,
8010 ) -> Option<codewhale_engine::session_manager::SavedAutoRouteReceipt> {
8011 if !self.auto_model {
8012 return None;
8013 }
8014 let (provider, model, receipt) = (
8015 self.last_effective_provider?,
8016 self.last_effective_model.as_ref()?,
8017 self.last_auto_route_receipt.as_ref()?,
8018 );
8019 if model.trim().is_empty() {
8020 return None;
8021 }
8022 let provider_identity = self
8023 .last_effective_provider_identity
8024 .clone()
8025 .unwrap_or_else(|| {
8026 if provider == ProviderKind::Custom {
8027 self.provider_identity_for_persistence().to_string()
8028 } else {
8029 provider.as_str().to_string()
8030 }
8031 });
8032 Some(codewhale_engine::session_manager::SavedAutoRouteReceipt {
8033 provider,
8034 provider_identity,
8035 model: model.clone(),
8036 receipt: receipt.clone(),
8037 effective_reasoning_effort: self.last_effective_reasoning_effort.map(Into::into),
8038 context_window: self.matching_auto_budget().map(|budget| budget.window),
8039 })
8040 }
8041
8042 #[must_use]
8043 pub(crate) fn provider_identity_for_persistence(&self) -> &str {
8044 self.provider_identity
8045 .as_ref()
8046 .map_or("unavailable", |identity| identity.key.as_str())
8047 }
8048
8049 #[must_use]
8050 pub(crate) fn provider_id_for_persistence(&self) -> Option<&str> {
8051 self.provider_identity
8052 .as_ref()
8053 .and_then(codewhale_runtime::config::ProviderIdentity::persisted_id)
8054 }
8055
8056 #[cfg(test)]
8057 pub(crate) fn set_provider_identity(
8058 &mut self,
8059 provider: ProviderKind,
8060 identity: impl Into<String>,
8061 ) {
8062 let key: String = identity.into();
8063 // This fixture helper has no parsed Config proof for an absent ID.
8064 // Legacy-root tests must install their actually captured record instead.
8065 self.set_provider_identity_record(
8066 codewhale_runtime::config::ProviderIdentity::test_exact_identity(provider, key),
8067 );
8068 }
8069
8070 pub(crate) fn set_provider_identity_record(
8071 &mut self,
8072 identity: codewhale_runtime::config::ProviderIdentity,
8073 ) {
8074 self.api_provider = identity.provider;
8075 self.provider_identity = Some(identity);
8076 }
8077
8078 pub(crate) fn admitted_provider_identity(
8079 &self,
8080 ) -> Result<&codewhale_runtime::config::ProviderIdentity, String> {
8081 self.provider_identity.as_ref().filter(|identity| identity.provider == self.api_provider)
8082 .ok_or_else(|| "The active provider route was not admitted; repair its configuration before running a request.".to_string())
8083 }
8084
8085 pub fn accepts_custom_model_ids(&self) -> bool {
8086 self.model_ids_passthrough
8087 || codewhale_config::descriptors::provider_passes_model_through(self.api_provider)
8088 }
8089
8090 pub(crate) fn apply_provider_switch_reasoning_effort(
8091 &mut self,
8092 provider: ProviderKind,
8093 base_url: &str,
8094 model_override: Option<&str>,
8095 ) {
8096 let wire_model = model_override.unwrap_or(&self.model);
8097 let inferred = model_override.and_then(|model| {
8098 codewhale_runtime::config::legacy_deepseek_alias_effort_for_route(
8099 provider, base_url, model,
8100 )
8101 });
8102 self.reasoning_effort = if let Some(requested) = self.reasoning_effort_preference {
8103 requested.normalize_for_route_identity(
8104 provider,
8105 self.provider_identity_for_persistence(),
8106 base_url,
8107 wire_model,
8108 )
8109 } else if let Some(effort) = inferred {
8110 ReasoningEffort::from_setting(effort)
8111 .normalize_for_route(provider, base_url, wire_model)
8112 } else if let Some(default) =
8113 ReasoningEffort::catalog_default(provider, base_url, wire_model)
8114 {
8115 default
8116 } else {
8117 self.reasoning_effort.normalize_for_route_identity(
8118 provider,
8119 self.provider_identity_for_persistence(),
8120 base_url,
8121 wire_model,
8122 )
8123 };
8124 self.invalidate_route_receipts_for_reasoning_change();
8125 }
8126
8127 pub fn effective_model_for_budget(&self) -> &str {
8128 if self.auto_model {
8129 return self
8130 .matching_auto_budget()
8131 .filter(|budget| !budget.restored)
8132 .map_or(DEFAULT_TEXT_MODEL, |budget| budget.model.as_str());
8133 }
8134 &self.model
8135 }
8136
8137 pub(crate) fn effective_context_window(&self) -> u32 {
8138 let (provider, model, limits, window) = self.effective_budget_route();
8139 window.map_or_else(
8140 || codewhale_engine::route_budget::route_context_window_tokens(provider, model, limits),
8141 |window| window.tokens,
8142 )
8143 }
8144
8145 pub(crate) fn matching_auto_budget(&self) -> Option<&AutoRouteBudget> {
8146 self.last_effective_budget.as_ref().filter(|budget| {
8147 self.auto_model
8148 && self.last_effective_provider == Some(budget.provider)
8149 && self.last_effective_provider_identity.as_deref()
8150 == Some(&budget.provider_identity)
8151 && self.last_effective_model.as_deref() == Some(&budget.model)
8152 })
8153 }
8154
8155 pub(crate) fn effective_budget_route(
8156 &self,
8157 ) -> (
8158 ProviderKind,
8159 &str,
8160 Option<RouteLimits>,
8161 Option<codewhale_engine::route_runtime::ContextWindowResolution>,
8162 ) {
8163 if let Some(budget) = self.matching_auto_budget()
8164 && !budget.restored
8165 {
8166 return (
8167 budget.provider,
8168 &budget.model,
8169 budget.limits,
8170 Some(budget.window),
8171 );
8172 }
8173 (
8174 self.api_provider,
8175 self.effective_model_for_budget(),
8176 self.active_route_limits,
8177 self.active_context_window,
8178 )
8179 }
8180
8181 pub(crate) fn effective_context_window_source(
8182 &self,
8183 ) -> codewhale_engine::route_runtime::ContextWindowSource {
8184 self.effective_budget_route()
8185 .3
8186 .map_or(self.active_context_window_source, |window| window.source)
8187 }
8188
8189 pub fn model_display_label(&self) -> String {
8190 if let Some(session) = self.external_agent.as_ref() {
8191 return session.agent_name.clone();
8192 }
8193 if self.auto_model {
8194 if let Some(effective) = self.last_effective_model.as_deref()
8195 && effective != "auto"
8196 {
8197 return format!("auto: {effective}");
8198 }
8199 return "auto".to_string();
8200 }
8201 self.model.clone()
8202 }
8203
8204 /// Provider/model identity used by the in-flight or most recent request.
8205 /// This is the display contract for auto routing and must match billing.
8206 #[must_use]
8207 pub fn effective_route_display(&self) -> (ProviderKind, String) {
8208 if let Some((provider, model, _)) = self.pending_turn_route.as_ref() {
8209 return (*provider, model.clone());
8210 }
8211 if self.auto_model
8212 && let (Some(provider), Some(model)) = (
8213 self.last_effective_provider,
8214 self.last_effective_model.as_ref(),
8215 )
8216 {
8217 return (provider, model.clone());
8218 }
8219 (self.api_provider, self.model_display_label())
8220 }
8221
8222 /// Exact non-secret route label for user-visible status surfaces.
8223 #[must_use]
8224 pub fn effective_route_identity_display(&self) -> (String, String) {
8225 if let Some(session) = self.external_agent.as_ref() {
8226 return ("ACP".to_string(), session.agent_name.clone());
8227 }
8228 let (provider, model) = self.effective_route_display();
8229 let identity = if provider == ProviderKind::Custom {
8230 if self.pending_turn_route.is_none() && self.auto_model {
8231 self.last_effective_provider_identity
8232 .as_deref()
8233 .unwrap_or_else(|| self.provider_identity_for_persistence())
8234 } else {
8235 self.provider_identity_for_persistence()
8236 }
8237 } else {
8238 provider.provider().display_name()
8239 };
8240 (identity.to_string(), model)
8241 }
8242
8243 fn effective_reasoning_effort_for_active_route(
8244 &self,
8245 requested: ReasoningEffort,
8246 ) -> EffectiveReasoningEffort {
8247 let route_truth = self.active_reasoning_route_truth();
8248 let auto_route_has_receipt = self
8249 .active_turn
8250 .as_ref()
8251 .and_then(|turn| turn.route.as_ref())
8252 .is_some_and(|route| route.receipt.is_some());
8253 if self.auto_model
8254 && !auto_route_has_receipt
8255 && self.last_auto_route_receipt.is_some()
8256 && requested == self.reasoning_effort
8257 && let Some(effective) = self.last_effective_reasoning_effort
8258 {
8259 // Once a concrete Auto route has been accepted, its normalized
8260 // tier remains the display authority until the model or requested
8261 // effort changes. The configured classifier route is not evidence
8262 // of what the completed turn received.
8263 return effective;
8264 }
8265 if requested == self.reasoning_effort
8266 && requested == ReasoningEffort::Auto
8267 && let Some(effective) = self.last_effective_reasoning_effort
8268 {
8269 // The accepted route receipt is already the strongest available
8270 // truth. Preserve enabled-but-untiered and unavailable states
8271 // instead of forcing them through the tier-only projection.
8272 return effective;
8273 }
8274 let effective = if requested == ReasoningEffort::Auto {
8275 ReasoningEffort::Auto
8276 } else if self.auto_model && !auto_route_has_receipt {
8277 // The configured provider is only the classifier's starting
8278 // point, not the route that will receive the request.
8279 requested
8280 } else if let Some((provider, _, base_url, model)) = route_truth {
8281 requested.normalize_for_route(provider, base_url, model)
8282 } else {
8283 requested.normalize_for_route(
8284 self.api_provider,
8285 &self.active_route_base_url,
8286 &self.model,
8287 )
8288 };
8289
8290 // Prefer the immutable installed-client receipt while a turn is live.
8291 // If it is unavailable, only use the configured route when no pending
8292 // or active foreign route could make that identity stale.
8293 if let Some((provider, _, base_url, model)) = route_truth {
8294 if let Some(constrained) =
8295 codewhale_engine::work_graph::constrained_effective_reasoning_for_route(
8296 requested.into(),
8297 provider,
8298 base_url,
8299 model,
8300 )
8301 {
8302 return constrained.into();
8303 }
8304 } else if self.active_turn.as_ref().is_some_and(|turn| {
8305 turn.route.as_ref().is_some_and(|route| {
8306 matches!(
8307 route.provider,
8308 ProviderKind::Zai
8309 | ProviderKind::Minimax
8310 | ProviderKind::MinimaxAnthropic
8311 | ProviderKind::Custom
8312 ) && route.receipt.is_none()
8313 })
8314 }) || self
8315 .pending_turn_route
8316 .as_ref()
8317 .is_some_and(|(provider, _, _)| {
8318 matches!(
8319 provider,
8320 ProviderKind::Zai
8321 | ProviderKind::Minimax
8322 | ProviderKind::MinimaxAnthropic
8323 | ProviderKind::Custom
8324 )
8325 })
8326 {
8327 // A route without its immutable endpoint receipt cannot prove
8328 // first-party semantics from provider/model identity alone.
8329 return EffectiveReasoningEffort::Unavailable;
8330 }
8331 EffectiveReasoningEffort::Tier(effective)
8332 }
8333
8334 fn active_reasoning_route_truth(&self) -> Option<(ProviderKind, &str, &str, &str)> {
8335 if let Some(route) = self
8336 .active_turn
8337 .as_ref()
8338 .and_then(|turn| turn.route.as_ref())
8339 {
8340 route.receipt.as_ref().map(|receipt| {
8341 (
8342 receipt.provider(),
8343 receipt.provider_identity(),
8344 receipt.endpoint_identity(),
8345 receipt.wire_model(),
8346 )
8347 })
8348 } else if self.pending_turn_route.is_none() {
8349 Some((
8350 self.api_provider,
8351 self.provider_identity_for_persistence(),
8352 self.active_route_base_url.as_str(),
8353 self.model.as_str(),
8354 ))
8355 } else {
8356 None
8357 }
8358 }
8359
8360 fn reasoning_effort_resolution_label(
8361 requested: ReasoningEffort,
8362 effective: EffectiveReasoningEffort,
8363 provider: ProviderKind,
8364 ) -> String {
8365 match effective {
8366 EffectiveReasoningEffort::Tier(effective) => {
8367 if requested == effective {
8368 return effective.display_label_for_provider(provider).to_string();
8369 }
8370 let effective = effective.display_label_for_provider(provider);
8371 format!("{}→{effective}", requested.short_label())
8372 }
8373 EffectiveReasoningEffort::ThinkingEnabledGranularityUnavailable => format!(
8374 "{}→thinking enabled; granularity unavailable",
8375 requested.short_label()
8376 ),
8377 EffectiveReasoningEffort::Unavailable => {
8378 format!("{}→effective unavailable", requested.short_label())
8379 }
8380 }
8381 }
8382
8383 pub fn reasoning_effort_display_label(&self) -> String {
8384 let requested = self.reasoning_effort;
8385 let effective = self.effective_reasoning_effort_for_active_route(requested);
8386 Self::reasoning_effort_resolution_label(requested, effective, self.api_provider)
8387 }
8388
8389 /// The effort label the metrics line's route segment may state: the
8390 /// resolution label when the route can prove an effective tier (or an
8391 /// enabled-but-untiered toggle), `None` when it cannot (#5950). A custom
8392 /// OpenAI-compatible route with no endpoint receipt is the usual `None`;
8393 /// printing `high→effective unavailable` there was a placeholder that
8394 /// could never resolve, so the row omits the field instead. `/status`
8395 /// and the effort cycle message still state the unavailable case in
8396 /// full via [`Self::reasoning_effort_display_label`].
8397 #[must_use]
8398 pub(crate) fn provable_reasoning_effort_label(&self) -> Option<String> {
8399 if self.external_agent.is_some() {
8400 return None;
8401 }
8402 (self.effective_reasoning_effort_for_active_route(self.reasoning_effort)
8403 != EffectiveReasoningEffort::Unavailable)
8404 .then(|| self.reasoning_effort_display_label())
8405 }
8406
8407 /// Return the concrete provider/model route whose current prompt may be
8408 /// inspected or replayed.
8409 ///
8410 /// For a fixed selection, the active route is authoritative. For Auto,
8411 /// `self.model` is only the selector sentinel, so the latest completed
8412 /// turn supplies provider/model/endpoint truth. A restored Auto session
8413 /// retains provider/model but not a raw endpoint; warmup may re-resolve
8414 /// that route from live config, while inspect fails honestly until a new
8415 /// turn captures the endpoint.
8416 #[must_use]
8417 pub(crate) fn cache_replay_target(&self) -> Option<CacheReplayTarget> {
8418 if !self.auto_model {
8419 let model = self.model.trim();
8420 if model.is_empty() || model.eq_ignore_ascii_case("auto") {
8421 return None;
8422 }
8423 let base_url = (!self.active_route_base_url.trim().is_empty())
8424 .then(|| self.active_route_base_url.clone());
8425 return Some(CacheReplayTarget {
8426 provider: self.api_provider,
8427 provider_identity: self.provider_identity_for_persistence().to_string(),
8428 provider_id: self.provider_id_for_persistence().map(str::to_string),
8429 model: model.to_string(),
8430 base_url,
8431 });
8432 }
8433
8434 let provider = self.last_effective_provider?;
8435 let model = self.last_effective_model.as_deref()?.trim();
8436 if model.is_empty() || model.eq_ignore_ascii_case("auto") {
8437 return None;
8438 }
8439 let provider_identity = self
8440 .last_effective_provider_identity
8441 .as_deref()
8442 .map(str::trim)
8443 .filter(|identity| !identity.is_empty())
8444 .map(str::to_string)
8445 .or_else(|| {
8446 (provider != ProviderKind::Custom).then(|| provider.as_str().to_string())
8447 })?;
8448 let provider_id = if provider != ProviderKind::Custom {
8449 Some(provider.as_str().to_string())
8450 } else if !provider_identity.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) {
8451 Some(provider_identity.clone())
8452 } else if self.api_provider == ProviderKind::Custom
8453 && self
8454 .provider_identity_for_persistence()
8455 .eq_ignore_ascii_case(&provider_identity)
8456 {
8457 self.provider_id_for_persistence().map(str::to_string)
8458 } else {
8459 None
8460 };
8461
8462 let latest_matches_route = self
8463 .session
8464 .turn_cache_history
8465 .back()
8466 .is_some_and(|record| {
8467 record.auto_model
8468 && record.provider == Some(provider)
8469 && record
8470 .model
8471 .as_deref()
8472 .is_some_and(|record_model| record_model.eq_ignore_ascii_case(model))
8473 && record
8474 .provider_identity
8475 .as_deref()
8476 .map(str::trim)
8477 .filter(|identity| !identity.is_empty())
8478 .map_or(provider != ProviderKind::Custom, |identity| {
8479 identity == provider_identity
8480 })
8481 });
8482 let warmup_base_url = self
8483 .session
8484 .last_warmup_key
8485 .as_ref()
8486 .filter(|key| {
8487 key.provider == provider_identity
8488 && key.model.eq_ignore_ascii_case(model)
8489 && !key.base_url.trim().is_empty()
8490 })
8491 .map(|key| key.base_url.clone());
8492 let base_url = latest_matches_route
8493 .then(|| self.session.last_base_url.clone())
8494 .flatten()
8495 .or(warmup_base_url)
8496 .filter(|base_url| !base_url.trim().is_empty());
8497
8498 Some(CacheReplayTarget {
8499 provider,
8500 provider_identity,
8501 provider_id,
8502 model: model.to_string(),
8503 base_url,
8504 })
8505 }
8506
8507 /// Provider-facing effort used when replaying the current prompt for cache
8508 /// inspection or warmup on one exact route.
8509 #[must_use]
8510 pub(crate) fn reasoning_effort_api_value_for_replay(
8511 &self,
8512 provider: ProviderKind,
8513 identity: &str,
8514 base_url: &str,
8515 model: &str,
8516 ) -> Option<&'static str> {
8517 let requested = if self.reasoning_effort == ReasoningEffort::Auto {
8518 self.last_effective_reasoning_effort?
8519 .request_tier_for_replay()?
8520 } else {
8521 self.reasoning_effort
8522 };
8523 requested
8524 .normalize_for_route_identity(provider, identity, base_url, model)
8525 .api_value_for_provider(provider)
8526 }
8527
8528 pub fn compaction_config(&self) -> CompactionConfig {
8529 let (provider, model, limits, window) = self.effective_budget_route();
8530 let mut config = self.compaction_config_for_route(provider, model, limits, window);
8531 // These cached fields are the active-route compatibility authority and
8532 // are updated together by `update_model_compaction_budget`. Commands
8533 // and embedders may also adjust them directly between route updates.
8534 config.enabled = self.auto_compact;
8535 config.token_threshold = self.compact_threshold;
8536 config
8537 }
8538
8539 /// Build compaction policy from one already-resolved provider route.
8540 ///
8541 /// Auto routing can select a provider/model whose context limits differ
8542 /// from the route currently displayed by the app. Callers dispatching that
8543 /// turn must derive every compaction input from the selected descriptor,
8544 /// not from the previous route cached in `App`.
8545 pub(crate) fn compaction_config_for_route(
8546 &self,
8547 provider: ProviderKind,
8548 model: &str,
8549 route_limits: Option<RouteLimits>,
8550 context_window: Option<codewhale_engine::route_runtime::ContextWindowResolution>,
8551 ) -> CompactionConfig {
8552 CompactionConfig {
8553 enabled: if self.auto_compact_user_configured {
8554 self.auto_compact
8555 } else {
8556 codewhale_engine::route_budget::auto_compact_default_for_route(provider, model, route_limits)
8557 },
8558 token_threshold:
8559 codewhale_engine::route_budget::compaction_threshold_for_route_at_percent_with_window(
8560 provider,
8561 model,
8562 route_limits,
8563 context_window.map(|window| window.tokens),
8564 self.auto_compact_threshold_percent,
8565 ),
8566 model: model.to_string(),
8567 effective_context_window: Some(context_window.map_or_else(
8568 || codewhale_engine::route_budget::route_context_window_tokens(provider, model, route_limits),
8569 |window| window.tokens,
8570 )),
8571 summary_instructions: self.compaction_summary_instructions.clone(),
8572 retained_user_message_tokens: self.compaction_retained_user_message_tokens,
8573 ..Default::default()
8574 }
8575 }
8576
8577 pub fn fallback_chain_entries(&self) -> Vec<(usize, ProviderKind, bool)> {
8578 let Some(chain) = &self.provider_chain else {
8579 return Vec::new();
8580 };
8581 let position = chain.position();
8582 chain
8583 .providers()
8584 .iter()
8585 .enumerate()
8586 .map(|(index, provider)| (index, *provider, index == position))
8587 .collect()
8588 }
8589
8590 pub fn fallback_chain_position(&self) -> Option<usize> {
8591 self.provider_chain.as_ref().map(ProviderChain::position)
8592 }
8593
8594 pub fn fallback_chain_len(&self) -> usize {
8595 self.provider_chain
8596 .as_ref()
8597 .map_or(0, |chain| chain.providers().len())
8598 }
8599
8600 /// Whether a fallback chain entry can serve a turn right now (#2574).
8601 ///
8602 /// Mirrors the provider picker's eligibility: hosted providers need a key
8603 /// (`has_api_key_for`, captured into `provider_readiness` at startup) while
8604 /// self-hosted providers (Ollama/vLLM/SGLang) are always ready. Providers
8605 /// absent from the captured identity snapshot remain unready; a display
8606 /// kind cannot establish credentials for a missing or custom route.
8607 fn fallback_provider_is_ready(&self, provider: ProviderKind) -> bool {
8608 self.provider_readiness
8609 .iter()
8610 .find_map(|(candidate, ready)| {
8611 (candidate.provider == provider && candidate.key.as_str() == provider.as_str())
8612 .then_some(*ready)
8613 })
8614 .unwrap_or(false)
8615 }
8616
8617 /// Advance to the next *eligible* provider in the fallback chain (#2574).
8618 ///
8619 /// Walks the chain from the current position, skipping entries that are not
8620 /// ready (hosted providers missing auth) and recording a clear note for each
8621 /// skip. Local providers are always eligible. Returns the first ready
8622 /// provider, or `None` (with an exhaustion reason) when every remaining entry
8623 /// is unready or the end of the chain is reached. `ProviderChain::advance`
8624 /// stays pure — the readiness filtering lives here at the App level.
8625 ///
8626 /// Note: auth-rejection (401) failures never reach this path; the caller
8627 /// excludes them from fallback so a bad key does not silently rotate
8628 /// providers (see `apply_engine_error_to_app`).
8629 ///
8630 /// Local/private policy (#2574): when the chain's primary provider is a
8631 /// self-hosted / local runtime, cloud candidates are skipped with a clear
8632 /// note so a local/private route never silently falls back out to a hosted
8633 /// provider. Self-hosted siblings remain eligible. The policy is anchored
8634 /// to the original primary; a cloud primary may still hop through a local
8635 /// runtime and then back to another cloud fallback.
8636 pub fn advance_fallback(&mut self, reason: impl Into<String>) -> Option<ProviderKind> {
8637 let reason = reason.into();
8638 self.provider_chain.as_ref()?;
8639
8640 let origin_is_local = self
8641 .provider_chain
8642 .as_ref()
8643 .and_then(|chain| chain.providers().first().copied())
8644 .is_some_and(|kind| {
8645 kind.provider().credential_help().acquisition
8646 == codewhale_config::provider::CredentialAcquisition::LocalOptional
8647 });
8648
8649 let mut skip_notes: Vec<String> = Vec::new();
8650 let mut chosen: Option<ProviderKind> = None;
8651 while let Some(next_kind) = self
8652 .provider_chain
8653 .as_mut()
8654 .and_then(ProviderChain::advance)
8655 {
8656 let candidate = next_kind;
8657 if origin_is_local
8658 && candidate.provider().credential_help().acquisition
8659 != codewhale_config::provider::CredentialAcquisition::LocalOptional
8660 {
8661 skip_notes.push(format!(
8662 "skipped {}: local/private policy (no local->cloud fallback)",
8663 candidate.as_str()
8664 ));
8665 continue;
8666 }
8667 if self.fallback_provider_is_ready(candidate) {
8668 chosen = Some(candidate);
8669 break;
8670 }
8671 skip_notes.push(format!("skipped {}: needs auth", candidate.as_str()));
8672 }
8673
8674 let skipped = if skip_notes.is_empty() {
8675 String::new()
8676 } else {
8677 format!(" ({})", skip_notes.join("; "))
8678 };
8679
8680 let Some(next_provider) = chosen else {
8681 let total = self
8682 .provider_chain
8683 .as_ref()
8684 .map_or(0, |chain| chain.providers().len());
8685 self.last_fallback_reason = Some(format!(
8686 "Fallback chain exhausted after {total} provider(s): {reason}{skipped}"
8687 ));
8688 return None;
8689 };
8690
8691 let identity = self
8692 .provider_readiness
8693 .iter()
8694 .find(|(identity, ready)| {
8695 *ready
8696 && identity.provider == next_provider
8697 && identity.key.as_str() == next_provider.as_str()
8698 })?
8699 .0
8700 .clone();
8701 self.set_provider_identity_record(identity);
8702 self.last_fallback_reason = Some(format!(
8703 "Fell back to {} after recoverable provider error: {reason}{skipped}",
8704 next_provider.as_str()
8705 ));
8706 Some(next_provider)
8707 }
8708
8709 pub fn is_fallback_active(&self) -> bool {
8710 self.provider_chain
8711 .as_ref()
8712 .is_some_and(ProviderChain::is_fallback_active)
8713 }
8714 }
8715
8716 fn active_agent_approved_plugin_names(registry: &codewhale_plugins::PluginRegistry) -> Vec<String> {
8717 registry
8718 .list()
8719 .iter()
8720 .filter(|plugin| {
8721 plugin.active()
8722 && matches!(
8723 plugin.approved_by,
8724 Some(codewhale_plugins::host_services::PluginApprover::Agent(_))
8725 )
8726 })
8727 .map(|plugin| {
8728 crate::commands::groups::plugins::render::escape_review_text(
8729 plugin.name(),
8730 crate::commands::groups::plugins::render::ReviewTextContext::Plain,
8731 )
8732 })
8733 .collect()
8734 }
8735
8736 pub fn media_attachment_reference(kind: &str, path: &Path, description: Option<&str>) -> String {
8737 match description {
8738 Some(description) if !description.trim().is_empty() => {
8739 format!(
8740 "[Attached {kind}: {} at {}]",
8741 description.trim(),
8742 path.display()
8743 )
8744 }
8745 _ => format!("[Attached {kind}: {}]", path.display()),
8746 }
8747 }
8748
8749 #[cfg(test)]
8750 mod tests;
8751
8752 #[cfg(test)]
8753 impl App {
8754 pub(crate) fn capture_session_fixture_source(&mut self) {
8755 use codewhale_engine::session_manager::{SessionManager, SessionWriteOwner};
8756 let Some(id) = self.current_session_id.as_deref() else {
8757 return;
8758 };
8759 let manager = SessionManager::default_location().expect("fixture session manager");
8760 let source = match manager.load_session_snapshot(id) {
8761 Ok(session) => session.write_receipt,
8762 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
8763 match manager
8764 .load_session_checkpoint(id)
8765 .expect("fixture checkpoint source")
8766 {
8767 Some(session) => session.write_receipt,
8768 None => Some(
8769 manager
8770 .expect_absent_session(id)
8771 .expect("fresh fixture source"),
8772 ),
8773 }
8774 }
8775 Err(error) => panic!("fixture session source: {error}"),
8776 };
8777 self.session_write_receipt = Some(source.expect("fixture admitted source"));
8778 self.session_write_owner = Some(SessionWriteOwner::control());
8779 }
8780 }
8781
8781 lines RUST