Skip to main content

mermaid_cli/domain/
state.rs

1//! The single state shape for the whole application.
2//!
3//! `State` is the value the reducer operates on. Everything the UI
4//! shows — from the chat log to the input buffer to the "Thinking…"
5//! animation — is derived from fields in this struct. Mutation happens
6//! only inside `update(state, msg)`; no other code is allowed to hold
7//! a `&mut State`.
8//!
9//! The sub-state enums (`TurnState`, `UiMode`, `McpServerStatus`) are
10//! intentionally explicit sum types. A previous generation of this
11//! codebase used bools like `is_generating: bool`, `is_cancelling:
12//! bool`, `is_tool_call_pending: bool` — the invariants between those
13//! bools were load-bearing and enforced by convention. Expressing the
14//! same state as a single enum makes it impossible to be in two modes
15//! at once, and the reducer can pattern-match instead of guarding with
16//! if-chains.
17
18use std::collections::{HashMap, VecDeque};
19use std::path::PathBuf;
20use std::time::SystemTime;
21
22use chrono::{DateTime, Local};
23
24use crate::app::instructions::LoadedInstructions;
25use crate::app::{Config, McpServerConfig};
26use crate::models::ChatMessage;
27use crate::models::tool_call::ToolCall as ModelToolCall;
28use crate::models::{ProviderContinuation, ReasoningLevel, TokenUsage, TokenUsageSource};
29use crate::runtime::SafetyMode;
30use crate::session::ConversationHistory;
31
32use super::cmd::ChatRequest;
33use super::compaction::CompactionTrigger;
34use super::ids::{IdAllocator, ToolCallId, TurnId};
35use super::msg::Msg;
36use super::question::PendingQuestionSet;
37use super::runtime::{RuntimeState, ToolArtifact, ToolRunMetadata, ToolStatus};
38
39/// Root state. The reducer takes `State` by value, returns a new
40/// `State`, and emits any side-effects as a `Vec<Cmd>`. No `&mut` — a
41/// deliberate choice so tests can diff before/after without aliasing
42/// worries, and so replay ("compute the final State that this Msg log
43/// would produce") is a straight fold.
44#[derive(Debug, Clone)]
45pub struct State {
46    pub session: Session,
47    pub turn: TurnState,
48    pub ui: UiState,
49    pub mcp: McpState,
50    pub settings: Config,
51    pub instructions: Option<LoadedInstructions>,
52    /// Durable semantic memory snapshot (auto-derived index + entries),
53    /// refreshed per turn like `instructions`. Its index is injected into the
54    /// model prompt alongside project instructions.
55    pub memory: Option<crate::app::memory::LoadedMemory>,
56    /// Discovered SKILL.md playbooks (project/user/plugin) plus the rendered
57    /// index injected into the model prompt alongside instructions and memory.
58    /// Loaded once at startup — skills are authored artifacts, not live state.
59    pub skills: Option<crate::app::skills::LoadedSkills>,
60    /// Context strings injected by `before_tool_use` plugin hooks
61    /// (`additionalContext`), buffered until the next dispatched model
62    /// request consumes them (see `push_call_model`). Byte-capped; transient
63    /// (never persisted with the session).
64    pub pending_hook_context: Vec<String>,
65    /// One-line notices about the task checklist for the model's next
66    /// request: user `/todos` edits, vetoed completions, staleness nudges.
67    /// Same lifecycle as `pending_hook_context` (consumed by the next real
68    /// dispatch, transient, never persisted).
69    pub pending_task_notices: Vec<String>,
70    /// Current working directory. Captured once at startup; tools
71    /// receive it via `ExecContext::workdir` and spawned subprocesses
72    /// inherit it. Centralized here so tests can inject a fake cwd.
73    pub cwd: PathBuf,
74    /// System temp dir, captured once at startup (`std::env::temp_dir()`).
75    /// Pasted-image attachments build their scratch path from it; holding it
76    /// here keeps the reducer free of the env read it used to do inline (#54).
77    pub temp_dir: PathBuf,
78    pub ids: IdAllocatorBundle,
79    /// When `Some`, the next render should pop up a modal confirmation
80    /// (e.g. "are you sure you want to /clear?"). Cleared by the
81    /// reducer when the user answers.
82    pub confirm: Option<Confirmation>,
83    /// FIFO queue of tool actions awaiting the user's inline approval
84    /// (interactive `ask` mode + Auto-mode escalations). The front item is
85    /// rendered as a modal; answering it pops the item and emits
86    /// `Cmd::ResolveApproval`, which unblocks the parked tool task. Empty in
87    /// headless mode (no broker → the out-of-band `/approve` flow instead).
88    pub pending_approval: VecDeque<PendingApproval>,
89    /// FIFO queue of `ask_user_question` batches awaiting the user's answers.
90    /// The front item renders as a selectable modal; submitting pops it and
91    /// emits `Cmd::ResolveQuestion`, unblocking the parked tool task. Empty in
92    /// headless mode (no broker → the tool proceeds without asking).
93    pub pending_question: VecDeque<PendingQuestionSet>,
94    /// Runtime-only observability state: process registry, provider
95    /// capability snapshot, and lifecycle timeline. Not sent to the
96    /// model.
97    pub runtime: RuntimeState,
98    /// Quit flag. When set, the main loop drains pending effects and
99    /// exits. The reducer never panics on its own; it sets this instead.
100    pub should_exit: bool,
101    /// Prompt-backed slash commands contributed by enabled plugins
102    /// (`manifest.prompts`). Loaded once at startup by the run loop (like
103    /// `skills`); the reducer expands `/name args` into a normal
104    /// `Msg::SubmitPrompt`, so recordings replay without the plugin
105    /// installed. Sorted by name.
106    pub plugin_commands: Vec<PluginCommand>,
107    /// `mermaid run --output-schema`: set by the headless driver before the
108    /// dedicated formatting turn; `build_chat_request` copies it onto the
109    /// request (dropping all tools for that turn). Never set interactively.
110    pub output_schema: Option<serde_json::Value>,
111    /// Wall-clock for the current reducer step, injected as data (Cause 3).
112    /// The driver stamps this once per tick — `Local::now()` live, or the
113    /// recorded entry's `ts` on replay — *before* calling `update`. The
114    /// reducer and the `transition` helpers read `state.now` instead of
115    /// `Local::now()` / `SystemTime::now()`, so `update(State, Msg)` is a pure
116    /// function of its inputs: the same `(State, Msg)` always yields the same
117    /// `State`, and folding a recorded `Msg` log recomputes State exactly.
118    pub now: DateTime<Local>,
119}
120
121impl State {
122    /// Build a fresh state tied to a specific model + project dir.
123    ///
124    /// Pure given its inputs: `now` seeds the injected clock and derives the
125    /// initial conversation's id/title, so `--replay` reconstructs the same
126    /// starting state from a recorded header. (The one environment read left
127    /// is `env::temp_dir()` — stable within a machine, and only feeds paste
128    /// scratch paths.) Nothing here touches the filesystem or tokio.
129    pub fn new(settings: Config, cwd: PathBuf, model_id: String, now: DateTime<Local>) -> Self {
130        let project_path = cwd.display().to_string();
131        let conversation = ConversationHistory::new(project_path, model_id.clone(), now);
132        let initial_title = conversation.title.clone();
133        // F5: seed `mcp.servers` from the user's configured MCP
134        // servers with `Starting` status. Previously the map started
135        // empty, and `McpServerReady` handlers used `get_mut` —
136        // configured servers never populated, so their tools never
137        // reached `build_chat_request`'s outgoing tool list.
138        let mcp = {
139            let mut m = McpState::default();
140            for (name, cfg) in &settings.mcp_servers {
141                m.servers.insert(
142                    name.clone(),
143                    McpServerEntry {
144                        config: cfg.clone(),
145                        status: McpServerStatus::Starting,
146                        tools: Vec::new(),
147                    },
148                );
149            }
150            m
151        };
152        // F11: honor the per-model reasoning preference (persisted via
153        // `/reasoning high` while using a specific model). Falls back to
154        // the global default when no entry exists.
155        let reasoning = settings
156            .reasoning_per_model
157            .get(&model_id)
158            .copied()
159            .unwrap_or(settings.default_model.reasoning);
160        let runtime = RuntimeState::new(&model_id);
161        Self {
162            session: Session {
163                conversation,
164                model_id,
165                reasoning,
166                safety_mode: settings.safety.mode,
167                last_token_usage: None,
168                cumulative_token_usage: TokenUsageTotals::default(),
169                context_usage: None,
170                is_subagent: false,
171                agent_preamble: None,
172                plan: None,
173                // Materialized by the effect layer after startup dispatches
174                // `Cmd::EnsureScratchpad`; the pure constructor never touches
175                // the filesystem.
176                scratchpad: None,
177            },
178            turn: TurnState::Idle,
179            ui: UiState {
180                last_title_dispatched: Some(initial_title),
181                theme: settings.ui.theme,
182                ..UiState::default()
183            },
184            mcp,
185            settings,
186            instructions: None,
187            memory: None,
188            skills: None,
189            pending_hook_context: Vec::new(),
190            pending_task_notices: Vec::new(),
191            cwd,
192            temp_dir: std::env::temp_dir(),
193            ids: IdAllocatorBundle::default(),
194            confirm: None,
195            pending_approval: VecDeque::new(),
196            pending_question: VecDeque::new(),
197            runtime,
198            should_exit: false,
199            output_schema: None,
200            plugin_commands: Vec::new(),
201            // Seed the injected clock from the caller (live: startup wall
202            // clock; replay: the recorded header's ts). The driver overwrites
203            // this on every iteration (Cause 3); the reducer never reads the
204            // wall clock directly.
205            now,
206        }
207    }
208
209    /// Apply a `--continue` / `--sessions` seed: replace the fresh
210    /// conversation with the loaded history and re-dispatch the terminal
211    /// title once. Shared by the live driver and `--replay` so both
212    /// construct the same starting state by definition.
213    pub fn seed_conversation(&mut self, history: ConversationHistory) {
214        let title = history.title.clone();
215        // Restore the live meters + safety mode that ride on the saved file
216        // (see `Session::snapshot_conversation`). Sessions saved before these
217        // fields existed leave them at None/0, so keep the config-default
218        // safety mode (already set by `State::new`) when the file has none.
219        if let Some(mode) = history.safety_mode {
220            self.session.safety_mode = mode;
221        }
222        // Restore planning-in-progress (None for sessions saved before the
223        // field existed, and for sessions that weren't planning).
224        self.session.plan = history.plan.clone();
225        self.session.last_token_usage = history.last_token_usage;
226        self.session.cumulative_token_usage = history.cumulative_token_usage;
227        self.session.context_usage = history.context_usage.clone();
228        self.session.conversation = history;
229        // A session persisted mid-tool (an assistant `tool_use` with no committed
230        // result, or a result whose call was archived out) would otherwise resume
231        // with an orphan and 400 the first request. Repair pairing on the loaded
232        // prefix so both the transcript and the next request are valid.
233        crate::domain::compaction::normalize_history(&mut self.session.conversation.messages);
234        // Continue global image numbering past the highest number already in the
235        // loaded transcript, so `[Image #16]` keeps referring to that same image
236        // across --resume/--continue. Sessions saved before image numbering (no
237        // `image_numbers`) yield max 0 → start at 1, the default. Shared live +
238        // --replay seed path, so both reconstruct an identical allocator.
239        let max_image = self
240            .session
241            .conversation
242            .messages
243            .iter()
244            .filter_map(|m| m.image_numbers.as_ref())
245            .flatten()
246            .copied()
247            .max()
248            .unwrap_or(0);
249        self.ids.image = crate::domain::ids::IdAllocator::starting_at(max_image + 1);
250        self.ui.last_title_dispatched = Some(title);
251    }
252
253    /// True iff the reducer is currently mid-turn. UI uses this for
254    /// the "⏎ cancels generation" hint and for keybind routing.
255    pub fn is_busy(&self) -> bool {
256        !matches!(self.turn, TurnState::Idle)
257    }
258
259    /// The active `TurnId`, if any turn is in flight. The reducer
260    /// filters incoming effect messages by comparing their embedded
261    /// `TurnId` to this value — if the user cancelled and started a
262    /// new turn, stale results from the old turn are dropped cleanly.
263    pub fn current_turn_id(&self) -> Option<TurnId> {
264        self.turn.id()
265    }
266}
267
268/// Per-component token counts accumulated for UI display. Components
269/// are disjoint (mirrors `TokenUsage`); totals are derived, never
270/// stored. Providers report usage per API request; the session keeps
271/// both the last request and the cumulative API usage so the footer
272/// does not imply this is the current model context length.
273#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
274pub struct TokenUsageTotals {
275    pub prompt_tokens: usize,
276    pub completion_tokens: usize,
277    pub cached_input_tokens: usize,
278    pub cache_creation_input_tokens: usize,
279    pub reasoning_output_tokens: usize,
280}
281
282impl TokenUsageTotals {
283    pub fn from_usage(usage: &TokenUsage) -> Self {
284        Self {
285            prompt_tokens: usage.prompt_tokens,
286            completion_tokens: usage.completion_tokens,
287            cached_input_tokens: usage.cached_input_tokens,
288            cache_creation_input_tokens: usage.cache_creation_input_tokens,
289            reasoning_output_tokens: usage.reasoning_output_tokens,
290        }
291    }
292
293    pub fn add_assign(&mut self, other: Self) {
294        self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
295        self.completion_tokens = self
296            .completion_tokens
297            .saturating_add(other.completion_tokens);
298        self.cached_input_tokens = self
299            .cached_input_tokens
300            .saturating_add(other.cached_input_tokens);
301        self.cache_creation_input_tokens = self
302            .cache_creation_input_tokens
303            .saturating_add(other.cache_creation_input_tokens);
304        self.reasoning_output_tokens = self
305            .reasoning_output_tokens
306            .saturating_add(other.reasoning_output_tokens);
307    }
308
309    pub fn input_total_tokens(&self) -> usize {
310        self.prompt_tokens
311            .saturating_add(self.cached_input_tokens)
312            .saturating_add(self.cache_creation_input_tokens)
313    }
314
315    pub fn output_total_tokens(&self) -> usize {
316        self.completion_tokens
317            .saturating_add(self.reasoning_output_tokens)
318    }
319
320    pub fn total_tokens(&self) -> usize {
321        self.input_total_tokens()
322            .saturating_add(self.output_total_tokens())
323    }
324}
325
326/// Approximate request-context breakdown used before provider usage
327/// arrives. These numbers are diagnostic estimates, not billing facts.
328#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
329pub struct PromptTokenBreakdown {
330    pub system_tokens: usize,
331    pub instructions_tokens: usize,
332    pub message_tokens: usize,
333    pub tool_schema_tokens: usize,
334    pub image_count: usize,
335    pub message_count: usize,
336    pub tool_count: usize,
337}
338
339impl PromptTokenBreakdown {
340    pub fn total_tokens(&self) -> usize {
341        self.system_tokens
342            .saturating_add(self.instructions_tokens)
343            .saturating_add(self.message_tokens)
344            .saturating_add(self.tool_schema_tokens)
345    }
346}
347
348/// The model-visible context for the latest request. This is separate
349/// from cumulative session usage, which is an API/accounting total.
350#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
351pub struct ContextUsageSnapshot {
352    pub used_tokens: usize,
353    pub max_tokens: Option<usize>,
354    pub remaining_tokens: Option<usize>,
355    pub used_percent: Option<u8>,
356    pub source: TokenUsageSource,
357    pub prompt_tokens: usize,
358    pub cached_input_tokens: usize,
359    pub cache_creation_input_tokens: usize,
360    pub completion_tokens: usize,
361    pub reasoning_output_tokens: usize,
362    pub breakdown: Option<PromptTokenBreakdown>,
363}
364
365impl ContextUsageSnapshot {
366    pub fn from_usage(usage: &TokenUsage, max_tokens: Option<usize>) -> Self {
367        // input + output ≈ what the next request's prompt will occupy;
368        // derived from disjoint components so it means the same thing
369        // for every provider.
370        Self::new(
371            usage.total_tokens(),
372            max_tokens,
373            usage.source,
374            usage.prompt_tokens,
375            usage.cached_input_tokens,
376            usage.cache_creation_input_tokens,
377            usage.completion_tokens,
378            usage.reasoning_output_tokens,
379            None,
380        )
381    }
382
383    pub fn from_estimate(breakdown: PromptTokenBreakdown, max_tokens: Option<usize>) -> Self {
384        let used = breakdown.total_tokens();
385        Self::new(
386            used,
387            max_tokens,
388            TokenUsageSource::Estimate,
389            used,
390            0,
391            0,
392            0,
393            0,
394            Some(breakdown),
395        )
396    }
397
398    #[allow(clippy::too_many_arguments)]
399    fn new(
400        used_tokens: usize,
401        max_tokens: Option<usize>,
402        source: TokenUsageSource,
403        prompt_tokens: usize,
404        cached_input_tokens: usize,
405        cache_creation_input_tokens: usize,
406        completion_tokens: usize,
407        reasoning_output_tokens: usize,
408        breakdown: Option<PromptTokenBreakdown>,
409    ) -> Self {
410        let remaining_tokens = max_tokens.map(|max| max.saturating_sub(used_tokens));
411        let used_percent = max_tokens
412            .filter(|max| *max > 0)
413            .map(|max| ((used_tokens.saturating_mul(100)) / max).min(100) as u8);
414        Self {
415            used_tokens,
416            max_tokens,
417            remaining_tokens,
418            used_percent,
419            source,
420            prompt_tokens,
421            cached_input_tokens,
422            cache_creation_input_tokens,
423            completion_tokens,
424            reasoning_output_tokens,
425            breakdown,
426        }
427    }
428
429    pub fn is_estimate(&self) -> bool {
430        self.source == TokenUsageSource::Estimate
431    }
432
433    /// Return a copy with `extra` tokens folded into the running total. Used by
434    /// `/context` to add built-in tool-schema tokens that the reducer's
435    /// MCP-only request estimate can't see. Recomputes `remaining_tokens` and
436    /// `used_percent`; the breakdown is left untouched (the caller surfaces the
437    /// built-in figure on its own line so the MCP line stays accurate).
438    pub fn with_additional_tokens(mut self, extra: usize) -> Self {
439        if extra == 0 {
440            return self;
441        }
442        self.used_tokens = self.used_tokens.saturating_add(extra);
443        self.remaining_tokens = self
444            .max_tokens
445            .map(|max| max.saturating_sub(self.used_tokens));
446        self.used_percent = self
447            .max_tokens
448            .filter(|max| *max > 0)
449            .map(|max| ((self.used_tokens.saturating_mul(100)) / max).min(100) as u8);
450        self
451    }
452}
453
454pub fn estimate_context_usage_for_request(
455    request: &ChatRequest,
456    max_tokens: Option<usize>,
457) -> ContextUsageSnapshot {
458    let system_tokens = approx_tokens(&request.system_prompt);
459    let instructions_tokens = request
460        .instructions
461        .as_deref()
462        .map(approx_tokens)
463        .unwrap_or(0);
464    let message_tokens = request
465        .messages
466        .iter()
467        .map(|msg| {
468            let image_chars = msg
469                .images
470                .as_ref()
471                .map(|imgs| imgs.iter().map(|img| img.len()).sum::<usize>())
472                .unwrap_or(0);
473            // Include assistant tool-call name + arguments JSON, which the
474            // estimate previously ignored (see estimate_message_tokens).
475            let tool_call_chars = msg
476                .tool_calls
477                .as_ref()
478                .map(|calls| {
479                    calls
480                        .iter()
481                        .map(|tc| {
482                            tc.function.name.len()
483                                + tc.function.arguments.to_string().len()
484                                + tc.id.as_deref().map(str::len).unwrap_or(0)
485                        })
486                        .sum::<usize>()
487                })
488                .unwrap_or(0);
489            approx_tokens(&msg.content)
490                .saturating_add(approx_tokens(&format!(
491                    "{:?}{}{}",
492                    msg.role,
493                    msg.tool_name.as_deref().unwrap_or(""),
494                    msg.tool_call_id.as_deref().unwrap_or("")
495                )))
496                .saturating_add(image_chars.div_ceil(4))
497                .saturating_add(tool_call_chars.div_ceil(4))
498        })
499        .sum();
500    let tool_schema_tokens = estimate_tool_schema_tokens(&request.tools);
501    let image_count = request
502        .messages
503        .iter()
504        .filter_map(|msg| msg.images.as_ref())
505        .map(Vec::len)
506        .sum();
507    ContextUsageSnapshot::from_estimate(
508        PromptTokenBreakdown {
509            system_tokens,
510            instructions_tokens,
511            message_tokens,
512            tool_schema_tokens,
513            image_count,
514            message_count: request.messages.len(),
515            tool_count: request.tools.len(),
516        },
517        max_tokens,
518    )
519}
520
521fn approx_tokens(text: &str) -> usize {
522    text.len().div_ceil(4)
523}
524
525/// Estimate the token cost of a set of tool schemas as the model sees them
526/// (serialized OpenAI-style). Shared by `estimate_context_usage_for_request`
527/// and the effect runner so the reducer's `/context` preview can account for
528/// the built-in tool schemas that are only appended to the request during
529/// dispatch enrichment.
530pub fn estimate_tool_schema_tokens(tools: &[super::cmd::ToolDefinition]) -> usize {
531    let tool_schema: Vec<_> = tools.iter().map(|tool| tool.to_openai_json()).collect();
532    serde_json::to_string(&tool_schema)
533        .map(|s| approx_tokens(&s))
534        .unwrap_or(0)
535}
536
537/// Live plan-mode state: present iff the session is currently drafting a
538/// plan. Plan mode is deliberately NOT a fifth `SafetyMode` — it *remembers
539/// and restores* the mode the user was in, which a flat cycle can't express.
540/// While this is `Some`, tool dispatch floors the effective safety mode to
541/// `ReadOnly` and the policy gate applies the plan carve-outs (the plan file
542/// itself, memory writes, known-safe builds).
543///
544/// `Session.safety_mode` is left untouched while planning — it IS the restore
545/// target (the status bar shows it as "restores: <mode>", and Shift+Tab /
546/// `/safety` may retune it mid-plan); only the *effective* mode at tool
547/// dispatch changes.
548///
549/// Serialized into `ConversationHistory` on every save (like `safety_mode`)
550/// so `--resume` restores planning-in-progress; sessions saved before this
551/// field existed deserialize to `None`.
552#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
553pub struct PlanState {
554    /// Absolute path of the plan file the model authors — the single path the
555    /// policy gate exempts from the read-only floor.
556    pub plan_path: std::path::PathBuf,
557    /// Model to restore when plan mode ends. `Some` only when `[plan] model`
558    /// swapped the session onto a plan-phase model at entry.
559    #[serde(default)]
560    pub prev_model_id: Option<String>,
561    /// Reasoning level to restore when plan mode ends. `Some` only when
562    /// `[plan] reasoning` overrode it at entry.
563    #[serde(default)]
564    pub prev_reasoning: Option<crate::models::ReasoningLevel>,
565}
566
567/// Persistent conversational state that survives across turns.
568///
569/// "Session" here means the user-visible chat session, not the tokio
570/// runtime or the TCP connection to the provider. One chat = one
571/// `Session` = one on-disk `ConversationHistory` file.
572#[derive(Debug, Clone)]
573pub struct Session {
574    pub conversation: ConversationHistory,
575    pub model_id: String,
576    pub reasoning: ReasoningLevel,
577    /// Live safety mode for this session. Initialized from
578    /// `config.safety.mode`, then mutated in-session by `Shift+Tab` /
579    /// `/safety` (session-scoped — never written back to the config file).
580    /// The reducer threads this into `Cmd::ExecuteTool` so the policy gate
581    /// enforces the *current* mode, not the startup snapshot.
582    pub safety_mode: SafetyMode,
583    /// Token usage for the most recent completed provider request.
584    /// `None` means the provider did not report usage for that turn.
585    pub last_token_usage: Option<TokenUsageTotals>,
586    /// Prompt/completion/total API usage accumulated for this session.
587    pub cumulative_token_usage: TokenUsageTotals,
588    /// Latest model-visible context snapshot. This may be an estimate
589    /// while a request is in flight and is replaced by provider-reported
590    /// usage when available.
591    pub context_usage: Option<ContextUsageSnapshot>,
592    /// True when this session IS a subagent (a child reducer driven by
593    /// `SubagentTool`). `system_prompt_for_state` appends the subagent
594    /// contract (final message = the report returned to the parent) when
595    /// set. Never true for a user-facing session.
596    pub is_subagent: bool,
597    /// Agent-type system-prompt block (e.g. the Explore type's "read-only
598    /// reconnaissance" charter), appended after the subagent contract.
599    /// Only ever `Some` on subagent sessions.
600    pub agent_preamble: Option<String>,
601    /// `Some` while the session is in plan mode (see [`PlanState`]). Never
602    /// `Some` on subagent sessions — children explore, they don't plan.
603    pub plan: Option<PlanState>,
604    /// Per-session scratch directory, once the effect layer has materialized
605    /// it on disk (`Cmd::EnsureScratchpad` -> `Msg::ScratchpadReady`). `None`
606    /// until then, and reset whenever the conversation id changes (`/clear`,
607    /// `/load`, rewind fork) — the reducer re-emits `EnsureScratchpad` at
608    /// those points. The reducer stamps this onto `Cmd::ExecuteTool` so tools
609    /// see it via `ExecContext::scratchpad`. Runtime-only, never persisted.
610    pub scratchpad: Option<PathBuf>,
611}
612
613impl Session {
614    /// Clone the conversation with the live meters + safety mode overlaid, so
615    /// a saved file carries the full restorable state. These fields live on
616    /// `Session` (which is NOT serialized — only `conversation` is), so every
617    /// `Cmd::SaveConversation` snapshots them in and `seed_conversation`
618    /// hydrates them back on resume.
619    pub fn snapshot_conversation(&self) -> ConversationHistory {
620        let mut history = self.conversation.clone();
621        history.safety_mode = Some(self.safety_mode);
622        history.plan = self.plan.clone();
623        history.last_token_usage = self.last_token_usage;
624        history.cumulative_token_usage = self.cumulative_token_usage;
625        history.context_usage = self.context_usage.clone();
626        history
627    }
628
629    /// The committed message log. All messages visible in the chat
630    /// widget live here; partial in-flight content lives in
631    /// `TurnState::Generating`.
632    pub fn messages(&self) -> &[ChatMessage] {
633        &self.conversation.messages
634    }
635
636    /// Append a committed assistant/user/tool message. Mutation happens
637    /// through here so the reducer has one chokepoint to update the
638    /// conversation's `updated_at` and derived title.
639    ///
640    /// `now` is the reducer's injected clock (`state.now`). It stamps both
641    /// the message's commit timestamp and `updated_at` — the wall-clock
642    /// stamp `ChatMessage::new` put on the message at construction is
643    /// deliberately overwritten with the deterministic one, so `update()`
644    /// is a pure function and `--replay` recommits identical messages.
645    pub fn append(&mut self, mut msg: ChatMessage, now: DateTime<Local>) {
646        msg.timestamp = now;
647        self.conversation.add_messages(&[msg], now);
648    }
649}
650
651/// The turn state machine. Each variant carries its own `TurnId` so
652/// the reducer can cheaply check "is this effect result for the
653/// current turn?" without threading the ID through every match arm.
654///
655/// The `ExecutingTools::outcomes: Vec<Option<ToolOutcome>>` field is
656/// the architectural payoff: every slot starts `None`, flips to
657/// `Some(outcome)` as each tool finishes, and the transition to the
658/// follow-up `Generating` state requires `outcomes` to be fully
659/// populated. Statically impossible to "lose" a tool result.
660#[derive(Debug, Clone)]
661pub enum TurnState {
662    Idle,
663    Generating {
664        id: TurnId,
665        started: SystemTime,
666        partial_text: String,
667        partial_reasoning: String,
668        /// Running token estimate — updated by `StreamText` events.
669        tokens: usize,
670        /// Sub-phase for richer status display (see `GenPhase`).
671        phase: GenPhase,
672        /// Opaque provider state carried until the assistant message commits.
673        provider_continuation: Option<ProviderContinuation>,
674        /// Tool calls the model has streamed so far this turn.
675        /// `StreamToolCall` messages push here; `StreamDone` drains
676        /// the vec, allocates `PendingToolCall` entries, and
677        /// transitions to `ExecutingTools`. When the vec is empty at
678        /// stream end, the turn returns to `Idle`.
679        pending_tool_calls: Vec<ModelToolCall>,
680        /// True when this turn resumes a reply cut by the per-response
681        /// output cap (auto-continue). The commit stamps the resulting
682        /// message `ChatMessageKind::Continuation` so the transcript can
683        /// stitch it into the previous bubble. Survives an intervening
684        /// empty-retry or truncation-recovery compaction so a chain never
685        /// loses the marker mid-way.
686        continuation: bool,
687    },
688    ExecutingTools {
689        id: TurnId,
690        /// When tool execution started, so the status line can show elapsed
691        /// time (a long-running command — `npm run dev`, a slow build — would
692        /// otherwise look frozen at 0s).
693        started: SystemTime,
694        calls: Vec<PendingToolCall>,
695        outcomes: Vec<Option<ToolOutcome>>,
696    },
697    /// Summarizing history as a step of its own: a manual `/compact`
698    /// (`trigger: Manual`, ends the turn afterwards) or a truncation recovery
699    /// (`trigger: TruncationRecovery`, resumes the run afterwards). Pre-turn auto
700    /// compaction instead runs while `Generating` because it is preflight for the
701    /// same user turn. `trigger` is what the finished/failed handlers key off.
702    Compacting {
703        id: TurnId,
704        started: SystemTime,
705        trigger: CompactionTrigger,
706        /// True when the turn that led into this compaction was itself a
707        /// continuation (see `Generating::continuation`): a `TruncationRecovery`
708        /// resume must re-enter `Generating` with the flag intact or a
709        /// continuation chain interrupted by a genuine context-full compaction
710        /// would commit its remaining text unmarked.
711        resume_continuation: bool,
712    },
713    /// `CancelTurn` was dispatched. The reducer has already emitted a
714    /// `Cmd::CancelScope` — now we wait for the final `Cancelled` /
715    /// `StreamDone` that the effect runner sends back when the scope's
716    /// `JoinSet` drains. Only then do we transition to `Idle`.
717    ///
718    /// Stuck in `Cancelling` too long = effect runner has a bug. UI
719    /// surfaces a "cleanup taking a while…" hint after 2s.
720    Cancelling {
721        id: TurnId,
722        since: SystemTime,
723    },
724}
725
726impl TurnState {
727    pub fn id(&self) -> Option<TurnId> {
728        match self {
729            TurnState::Idle => None,
730            TurnState::Generating { id, .. }
731            | TurnState::ExecutingTools { id, .. }
732            | TurnState::Compacting { id, .. }
733            | TurnState::Cancelling { id, .. } => Some(*id),
734        }
735    }
736
737    /// True when a `Msg` tagged with the given `TurnId` should be
738    /// accepted. Events from prior turns return false — the reducer's
739    /// first line on every effect-result arm.
740    pub fn accepts(&self, event_turn: TurnId) -> bool {
741        self.id() == Some(event_turn)
742    }
743}
744
745/// Sub-phase of `Generating`. Informational — the reducer updates it
746/// as the provider's stream progresses so the UI can show a meaningful
747/// status ("Thinking…" vs "Sending…" vs "Streaming").
748#[derive(Debug, Clone, Copy, PartialEq, Eq)]
749pub enum GenPhase {
750    /// Request dispatched, awaiting first byte.
751    Sending,
752    /// First chunk was reasoning content — currently inside a
753    /// thinking/reasoning block.
754    Thinking,
755    /// Streaming assistant content (post-thinking, or no thinking at
756    /// all).
757    Streaming,
758}
759
760/// One pending tool call that the model has asked us to execute. Wraps
761/// the wire-format tool call with an internal ID + the original
762/// provider-native structure so the reducer never loses provenance.
763#[derive(Debug, Clone)]
764pub struct PendingToolCall {
765    pub call_id: ToolCallId,
766    /// The raw tool call as it appeared in the model's response.
767    /// Preserved verbatim so the follow-up tool-result message can
768    /// reference the right function name + id on the wire.
769    pub source: ModelToolCall,
770}
771
772/// Outcome of a single tool execution.
773///
774/// `model_content` is the text that goes back to the model in the
775/// follow-up tool message. Everything else is Mermaid-owned
776/// structure for rendering, replay, process tracking, and timeline
777/// inspection.
778#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
779pub struct ToolOutcome {
780    pub status: ToolStatus,
781    pub summary: String,
782    pub model_content: String,
783    pub error: Option<String>,
784    pub metadata: Box<ToolRunMetadata>,
785    pub artifacts: Vec<ToolArtifact>,
786    pub duration_secs: Option<f64>,
787}
788
789impl ToolOutcome {
790    pub fn success(
791        model_content: impl Into<String>,
792        summary: impl Into<String>,
793        duration_secs: f64,
794    ) -> Self {
795        let duration = Some(duration_secs);
796        let metadata = ToolRunMetadata {
797            duration_secs: duration,
798            ..ToolRunMetadata::default()
799        };
800        Self {
801            status: ToolStatus::Success,
802            summary: summary.into(),
803            model_content: model_content.into(),
804            error: None,
805            metadata: Box::new(metadata),
806            artifacts: Vec::new(),
807            duration_secs: duration,
808        }
809    }
810
811    pub fn error(error: impl Into<String>, duration_secs: f64) -> Self {
812        let error = error.into();
813        let duration = Some(duration_secs);
814        Self {
815            status: ToolStatus::Error,
816            summary: error.clone(),
817            model_content: format!("Error: {}", error),
818            error: Some(error),
819            metadata: Box::new(ToolRunMetadata {
820                duration_secs: duration,
821                ..ToolRunMetadata::default()
822            }),
823            artifacts: Vec::new(),
824            duration_secs: duration,
825        }
826    }
827
828    pub fn cancelled() -> Self {
829        Self {
830            status: ToolStatus::Cancelled,
831            summary: "[cancelled]".to_string(),
832            model_content: "[Tool call skipped: the user cancelled before execution]".to_string(),
833            error: None,
834            metadata: Box::new(ToolRunMetadata::default()),
835            artifacts: Vec::new(),
836            duration_secs: None,
837        }
838    }
839
840    pub fn with_metadata(mut self, mut metadata: ToolRunMetadata) -> Self {
841        metadata.duration_secs = self.duration_secs;
842        self.metadata = Box::new(metadata);
843        self
844    }
845
846    pub fn with_artifacts(mut self, artifacts: Vec<ToolArtifact>) -> Self {
847        self.artifacts = artifacts.clone();
848        self.metadata.artifacts = artifacts;
849        self
850    }
851
852    pub fn with_images(self, images: Vec<String>) -> Self {
853        self.with_artifacts(
854            images
855                .into_iter()
856                .map(|data| ToolArtifact::Image { data })
857                .collect(),
858        )
859    }
860
861    /// Override the status after construction. When transitioning to
862    /// `Error`, populate `error` from `model_content` (if not already set)
863    /// so the renderer — `action_display_for`, which falls back to
864    /// `error_message().unwrap_or("[cancelled]")` — surfaces the failure
865    /// instead of mislabeling it as a cancellation. The MCP proxy uses this
866    /// for `isError: true` results (#91): the model still sees the server's
867    /// content verbatim via `model_content`, but the outcome reads as an
868    /// error rather than a success.
869    pub fn with_status(mut self, status: ToolStatus) -> Self {
870        if status == ToolStatus::Error && self.error.is_none() {
871            self.error = Some(self.model_content.clone());
872        }
873        self.status = status;
874        self
875    }
876
877    pub fn was_cancelled(&self) -> bool {
878        self.status == ToolStatus::Cancelled
879    }
880
881    pub fn is_success(&self) -> bool {
882        self.status == ToolStatus::Success
883    }
884
885    pub fn output(&self) -> &str {
886        &self.model_content
887    }
888
889    pub fn error_message(&self) -> Option<&str> {
890        self.error.as_deref()
891    }
892
893    pub fn images(&self) -> Option<Vec<String>> {
894        let images: Vec<String> = self
895            .artifacts
896            .iter()
897            .filter_map(|artifact| match artifact {
898                ToolArtifact::Image { data } => Some(data.clone()),
899                _ => None,
900            })
901            .collect();
902        if images.is_empty() {
903            None
904        } else {
905            Some(images)
906        }
907    }
908
909    /// Convert to a textual representation suitable for embedding in
910    /// the follow-up `tool` role message. Cancellation produces a
911    /// placeholder so the model sees "this was skipped" rather than
912    /// the history becoming malformed.
913    pub fn as_tool_message_content(&self) -> String {
914        self.model_content.clone()
915    }
916}
917
918/// Live activity for one in-flight tool call (today: a subagent child).
919/// `activity` is a short stable label ("read_file…", "thinking"); `tokens`
920/// is the child's cumulative output-token estimate, throttled at the source.
921#[derive(Debug, Clone, Default, PartialEq, Eq)]
922pub struct LiveToolStatus {
923    pub activity: String,
924    pub tokens: usize,
925}
926
927/// One plugin-contributed slash command (a markdown prompt from an enabled
928/// plugin's `manifest.prompts`). Plain data — parsing/IO happens in
929/// `app::plugin_assets`; the reducer only expands and submits.
930#[derive(Debug, Clone, PartialEq, Eq)]
931pub struct PluginCommand {
932    /// Command name without the leading `/` (validated `[a-z0-9-]+`).
933    pub name: String,
934    /// One-line description for the palette and `/help`.
935    pub description: String,
936    /// The prompt body. `$ARGUMENTS` is replaced with the typed args;
937    /// without the token, non-empty args append as a final paragraph.
938    pub body: String,
939    /// Owning plugin name, shown as `(plugin:<name>)` in the palette.
940    pub plugin: String,
941}
942
943impl PluginCommand {
944    /// Expand the body with typed arguments: replace-all of `$ARGUMENTS`
945    /// when the token is present, else append the args as a new paragraph
946    /// when non-empty. Pure.
947    pub fn expand(&self, args: &str) -> String {
948        let args = args.trim();
949        if self.body.contains("$ARGUMENTS") {
950            return self.body.replace("$ARGUMENTS", args);
951        }
952        if args.is_empty() {
953            self.body.clone()
954        } else {
955            format!("{}\n\n{}", self.body, args)
956        }
957    }
958}
959
960/// All UI-only state. Things in `UiState` never affect what gets sent
961/// to the model — only what the user sees.
962#[derive(Debug, Clone, Default)]
963pub struct UiState {
964    pub mode: UiMode,
965    /// Active color theme. Seeded from `config.ui.theme` in `State::new`;
966    /// `/theme` switches it live (and persists via `Cmd::PersistUiTheme`).
967    /// The render layer memoizes the resolved `Theme` off this value.
968    pub theme: crate::app::ThemeChoice,
969    /// `NO_COLOR` was set (present and non-empty) at startup. Injected by the
970    /// run loop after `State::new` — the reducer never reads the environment.
971    /// While true the render layer draws `Theme::plain()` regardless of
972    /// `theme`, and `/theme` notes that colors are disabled.
973    pub no_color: bool,
974    pub input_buffer: String,
975    /// Byte position within `input_buffer`. The reducer normalizes to
976    /// a UTF-8 char boundary on every mutation via
977    /// `floor_char_boundary`, so widgets can slice safely.
978    pub input_cursor: usize,
979    /// Pending image pastes for the next user message. Each is mirrored by an
980    /// inline `[Image #N]` token in `input_buffer`; the token is the source of
981    /// truth at submit time (see `image_token` + `handle_submit_prompt`).
982    pub attachments: Vec<Attachment>,
983    /// In-flight `Cmd::ReadClipboard` reads (Ctrl+V) whose result
984    /// (`Msg::ClipboardRead`) hasn't arrived yet. A counter, not a bool, so a
985    /// burst of rapid Ctrl+V presses all drain before a held submit fires.
986    /// Incremented where `Cmd::ReadClipboard` is pushed; decremented in
987    /// `handle_clipboard_read`.
988    pub clipboard_reads_pending: u32,
989    /// Set when Enter is pressed while `clipboard_reads_pending > 0`: the submit
990    /// is held until the read drains so a fast paste-then-Enter still includes
991    /// the pasted image instead of racing past it. `handle_clipboard_read`
992    /// re-runs the submit once the last pending read lands.
993    pub submit_after_clipboard: bool,
994    /// When `Some(i)`, the palette has a highlighted row. `None` =
995    /// closed / not showing.
996    pub palette_cursor: Option<usize>,
997    /// Cached project file list for the @-mention picker (relative paths,
998    /// dirs with a trailing `/`). `None` until the first walk completes;
999    /// stale-while-revalidate — every picker OPEN refreshes it.
1000    pub project_files: Option<Vec<String>>,
1001    /// A `Cmd::ListProjectFiles` walk is in flight (dedupe: opening the
1002    /// picker again while loading must not spawn a second walk).
1003    pub project_files_loading: bool,
1004    /// Current fuzzy matches for the active @-token, best first (top 50).
1005    /// Recomputed in the reducer on every text mutation — not per-frame in
1006    /// render — because fuzzy-ranking 20k paths at 60 Hz would be wasteful.
1007    pub file_picker_matches: Vec<String>,
1008    /// Highlighted row in `file_picker_matches`. `None` = picker closed.
1009    pub file_picker_cursor: Option<usize>,
1010    /// The user Esc'd the picker for the CURRENT token; cleared on the next
1011    /// text mutation so typing reopens it.
1012    pub file_picker_dismissed: bool,
1013    /// Messages the user typed while a turn was in flight, FIFO. Mid-run
1014    /// steering drains the WHOLE queue at each tool boundary (committed as
1015    /// user messages before the follow-up model call); a message queued
1016    /// mid-stream with no later tool boundary drains one-at-a-time at turn
1017    /// end instead. Each entry carries the attachment ids that were present
1018    /// when the user submitted it, so delivery sends the images that
1019    /// belonged to *that* message.
1020    pub queued_messages: VecDeque<QueuedMessage>,
1021    /// Last terminal title dispatched via `Cmd::SetTerminalTitle`.
1022    /// Arms that change `session.conversation.title` consult this
1023    /// and emit a fresh `SetTerminalTitle` only on diff.
1024    pub last_title_dispatched: Option<String>,
1025    /// Follow-up `Msg`s the reducer has queued for re-entry. The
1026    /// outer `update()` drains this after each single-step call so
1027    /// a handler can emit a synthetic event (e.g. Enter-on-slash
1028    /// queuing `Msg::Slash(cmd)`) without self-invoking the
1029    /// reducer. Bounded drain depth guards against runaway loops.
1030    pub pending_msgs: VecDeque<Msg>,
1031    /// Live activity per in-flight tool call, keyed by the call id.
1032    /// Fed by `Msg::ToolProgress` (today: subagent activity — the child's
1033    /// current tool / coarse phase plus a throttled token count) and rendered
1034    /// by the agent panel + status line next to the tool label. Entries are
1035    /// removed on that call's `ToolFinished` and the map is cleared when the
1036    /// turn ends or cancels; call ids are session-unique, so a stale entry
1037    /// can never attach to a later call.
1038    pub live_tool_status: HashMap<ToolCallId, LiveToolStatus>,
1039    /// Up-arrow history navigation cursor into
1040    /// `session.conversation.input_history`. `None` = not
1041    /// navigating (input_buffer is whatever the user typed).
1042    /// `Some(i)` = currently displaying history entry at index `i`
1043    /// from the END (0 = newest).
1044    pub input_history_cursor: Option<usize>,
1045    /// Whatever the user had typed before hitting Up. Preserved so
1046    /// stepping past the newest history entry with Down restores
1047    /// the partial input unchanged. Cleared on any non-nav key.
1048    pub history_draft: String,
1049    /// Running accumulator for mouse-wheel scroll events (F13). The
1050    /// reducer adds the delta here on `Msg::MouseScroll`; the render
1051    /// layer compares against its last-seen snapshot and applies the
1052    /// diff to the chat pane's `ChatState`. This keeps the reducer
1053    /// pure — it doesn't touch render-layer state, it just publishes
1054    /// an intent. `i32` wraps at ~2 billion scrolls (never).
1055    pub mouse_scroll_accum: i32,
1056    /// Monotonic "jump to bottom" counter (keyboard `End`). Same
1057    /// publish-then-diff pattern as `mouse_scroll_accum`: the reducer bumps it,
1058    /// the render layer diffs it against its last-seen value and calls
1059    /// `ChatState::resume_auto_scroll` — keeping the reducer pure.
1060    pub scroll_to_bottom_seq: u32,
1061    /// Monotonic "repaint everything" counter. Same publish-then-diff pattern
1062    /// as `scroll_to_bottom_seq`: the reducer bumps it, the run loop diffs it
1063    /// against its last-seen value and calls `Terminal::clear()` before the
1064    /// next draw. Needed because ratatui diff-renders against its back buffer:
1065    /// bytes some OTHER process wrote to the tty (a child that opened
1066    /// `/dev/tty`, a stray `printf` from another terminal) are invisible to
1067    /// that buffer and would otherwise persist as ghost cells. Bumped when a
1068    /// shell command finishes and on Ctrl+L.
1069    pub full_redraw_seq: u32,
1070    /// Ctrl+C exit arming (press-twice-to-exit). `Some(deadline)` after a
1071    /// first Ctrl+C: a second press at or before the deadline exits; any
1072    /// other key disarms; past the deadline the next Ctrl+C re-arms. Expiry
1073    /// is lazy — compared against `state.now`, so the render hint vanishes on
1074    /// the next tick with no state change. Ctrl+D on empty input and `/quit`
1075    /// still exit immediately.
1076    pub exit_armed_until: Option<DateTime<Local>>,
1077    /// Double-Esc rewind arming. `Some(t)` after an idle Esc; a second Esc
1078    /// within `ESC_REWIND_WINDOW_MS` of `t` opens the rewind picker. Any
1079    /// other key disarms; expiry is lazy against `state.now` like
1080    /// `exit_armed_until` (the hint vanishes on the next tick). Busy Esc
1081    /// never arms — it stays the cancel gesture.
1082    pub esc_armed_at: Option<DateTime<Local>>,
1083    /// Whether the terminal window has LOST focus (from terminal focus
1084    /// reporting via `Msg::FocusChanged`). Defaults `false` (assume attended, so
1085    /// terminals without focus reporting never ding); the attention bell fires
1086    /// only while this is `true`.
1087    pub terminal_unfocused: bool,
1088    /// Whether committed reasoning/thinking blocks are expanded in
1089    /// the chat transcript. Hidden by default to keep the TUI focused
1090    /// on user-facing work while retaining provider-required history.
1091    pub show_reasoning: bool,
1092    /// Whether the task checklist under the status line is collapsed to its
1093    /// one-line form (Ctrl+T toggles). Named for the non-default state so
1094    /// `derive(Default)` yields expanded, session-scoped, never persisted.
1095    pub tasks_collapsed: bool,
1096}
1097
1098impl UiState {
1099    /// The @-mention token under the cursor, when the picker may show:
1100    /// not user-dismissed, and not while the buffer is a slash command
1101    /// (the slash palette owns that surface).
1102    pub fn active_file_token(&self) -> Option<crate::domain::file_mention::AtToken> {
1103        if self.file_picker_dismissed || self.input_buffer.starts_with('/') {
1104            return None;
1105        }
1106        crate::domain::file_mention::active_at_token(&self.input_buffer, self.input_cursor)
1107    }
1108
1109    /// Whether the @-mention file picker is currently open.
1110    pub fn file_picker_open(&self) -> bool {
1111        self.active_file_token().is_some()
1112    }
1113}
1114
1115/// Top-level UI mode. Like `TurnState` this is a sum type instead of a
1116/// zoo of independent bools. `EditingInput` is the default.
1117#[derive(Debug, Clone, PartialEq, Eq, Default)]
1118pub enum UiMode {
1119    #[default]
1120    EditingInput,
1121    /// `/load` — list of saved conversations visible. `candidates`
1122    /// holds what the effect handler returned; `cursor` is the
1123    /// highlighted row.
1124    ConversationList {
1125        candidates: Vec<ConversationSummary>,
1126        cursor: usize,
1127    },
1128    /// `/model` — list of available models visible.
1129    ModelList,
1130    /// Double-Esc rewind: pick an earlier user message to fork the session
1131    /// at. Candidates are user-role Normal messages, newest first. Selecting
1132    /// one forks into a NEW session (original preserved, lineage stamped)
1133    /// with the composer pre-filled.
1134    /// The `/plan config` settings picker: per-category permission levels,
1135    /// model/reasoning overrides, approval behavior. `cursor` is the
1136    /// highlighted row.
1137    PlanConfig { cursor: usize },
1138    RewindPicker {
1139        candidates: Vec<RewindCandidate>,
1140        cursor: usize,
1141    },
1142}
1143
1144/// One rewind target: a user message's position in the conversation plus a
1145/// one-line excerpt for the picker row. Never rides in a `Msg` (the whole
1146/// flow is Key-driven), so no serde — record/replay work unchanged.
1147#[derive(Debug, Clone, PartialEq, Eq)]
1148pub struct RewindCandidate {
1149    /// Index into `conversation.messages` of the user message; the fork
1150    /// keeps `messages[..index]` and pre-fills the composer with this one.
1151    pub message_index: usize,
1152    /// First line of the message, clipped for the picker row.
1153    pub excerpt: String,
1154}
1155
1156/// Summary row for the conversation picker. Produced by
1157/// `Cmd::ListConversations` → `Msg::ConversationsListed`.
1158#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1159pub struct ConversationSummary {
1160    pub id: String,
1161    pub title: String,
1162    pub message_count: usize,
1163    pub updated_at: String,
1164}
1165
1166/// One pasted image, ready to send. Kept in the reducer state — not on
1167/// disk — because the image hasn't been confirmed for a message yet.
1168#[derive(Debug, Clone)]
1169pub struct Attachment {
1170    pub id: u64,
1171    /// Global, conversation-wide image number — the `N` shown in the inline
1172    /// `[Image #N]` token and, once sent, in the committed message. Stable for
1173    /// the life of the image; distinct from `id`, which only scopes attachment
1174    /// ownership within a submit.
1175    pub number: u64,
1176    pub base64_data: String,
1177    /// Temp file path (written by the effect runner when the paste
1178    /// event comes in, so the TUI can show a preview).
1179    pub temp_path: PathBuf,
1180    pub size_bytes: usize,
1181    pub format: String,
1182}
1183
1184/// A user message queued while a turn was in flight, with the attachment
1185/// ids that were present at submit time. Capturing the ids here (instead
1186/// of re-reading live `ui.attachments` at drain time) ensures the
1187/// auto-submit consumes the images the user attached to *this* message.
1188#[derive(Debug, Clone)]
1189pub struct QueuedMessage {
1190    pub text: String,
1191    pub attachment_ids: Vec<u64>,
1192}
1193
1194/// MCP server lifecycle state. Mutation is driven by `Msg::McpServer*`
1195/// events emitted from `effect::mcp` when a server starts, advertises
1196/// tools, or exits.
1197#[derive(Debug, Clone, Default)]
1198pub struct McpState {
1199    pub servers: HashMap<String, McpServerEntry>,
1200    /// Deferred MCP tools promoted to direct advertisement by a
1201    /// `tool_search` call this session (sanitized full names). A
1202    /// `BTreeSet` keeps the advertised tool order byte-stable across
1203    /// requests for prompt-cache warmth (#F68). Transient: cleared by
1204    /// conversation switch/`/clear` along with the rest of the session.
1205    pub promoted: std::collections::BTreeSet<String>,
1206}
1207
1208#[derive(Debug, Clone)]
1209pub struct McpServerEntry {
1210    pub config: McpServerConfig,
1211    pub status: McpServerStatus,
1212    /// Tools advertised by the server. Populated on the
1213    /// `McpServerReady` event; reducer exposes these to the model
1214    /// when building the tool list for the next request.
1215    pub tools: Vec<McpToolSpec>,
1216}
1217
1218#[derive(Debug, Clone, PartialEq, Eq)]
1219pub enum McpServerStatus {
1220    /// `initialize` request dispatched, not yet acknowledged.
1221    Starting,
1222    Ready,
1223    Errored {
1224        reason: String,
1225    },
1226    Stopped,
1227}
1228
1229/// Subset of the MCP `ToolDefinition` carried in reducer state. `name` is
1230/// the FULL sanitized advertised name (`mcp__<server>__<tool>`, provider-safe
1231/// charset and length — see `crate::mcp::sanitize`); `raw_name` is the bare
1232/// tool name exactly as the server advertised it, used for user-facing
1233/// display and for `enabled_tools`/`disabled_tools` filtering.
1234#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1235pub struct McpToolSpec {
1236    pub name: String,
1237    /// Bare tool name as the server advertised it (pre-sanitization).
1238    #[serde(default)]
1239    pub raw_name: String,
1240    pub description: String,
1241    pub input_schema: serde_json::Value,
1242}
1243
1244/// A pending user confirmation (modal). Examples: confirming `/clear`,
1245/// confirming overwrite of an existing file on `/save <name>`.
1246#[derive(Debug, Clone)]
1247pub struct Confirmation {
1248    pub prompt: String,
1249    pub accept_msg_token: ConfirmationTarget,
1250}
1251
1252/// What to do when the user confirms. The reducer translates
1253/// `Msg::ConfirmAccepted` into a secondary dispatch based on this.
1254#[derive(Debug, Clone)]
1255pub enum ConfirmationTarget {
1256    ClearConversation,
1257}
1258
1259/// One tool action awaiting inline approval. Built by the policy gate and
1260/// delivered via `Msg::ApprovalRequested`; rendered as a modal. The `prompt`
1261/// body is pre-formatted by the gate (command / path / summary, plus any
1262/// Auto-review reason) so the render layer stays dumb.
1263#[derive(Debug, Clone)]
1264pub struct PendingApproval {
1265    pub turn: TurnId,
1266    pub call_id: ToolCallId,
1267    pub tool: String,
1268    /// `RiskClass::as_str()` — shown on the title line.
1269    pub risk: String,
1270    pub kind: ApprovalKind,
1271    /// Pre-formatted body (the command/path being run + any classifier reason).
1272    pub prompt: String,
1273    /// What "don't ask again" (option 2) will allowlist, shown in the prompt.
1274    pub allowlist_scope: String,
1275    /// Highlighted option for arrow-key navigation: 0 = Yes, 1 = Yes-always,
1276    /// 2 = No. Number keys (1/2/3) still resolve directly regardless of this.
1277    pub selected_option: usize,
1278}
1279
1280/// The user's answer to an approval prompt.
1281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1282pub enum ApprovalChoice {
1283    Approve,
1284    ApproveAlways,
1285    Deny,
1286}
1287
1288/// Category of the gated action — drives the prompt's label. Mirrors the
1289/// runtime `ToolCategory` but lives in `domain` so the pure reducer needn't
1290/// depend on `providers`.
1291#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1292pub enum ApprovalKind {
1293    Shell,
1294    FileMutation,
1295    Web,
1296    Mcp,
1297    Subagent,
1298    ComputerUse,
1299    Classify,
1300}
1301
1302/// Severity carried on `Msg::CompactionFailed`. The compaction-failed handler
1303/// uses it to distinguish a benign no-op (`Info`, e.g. too little history to
1304/// compact) from a real failure worth surfacing.
1305#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1306pub enum StatusKind {
1307    Info,
1308    Warn,
1309    Error,
1310}
1311
1312/// All ID allocators for the session. Grouped so the reducer can
1313/// request any of them through a single `&mut state.ids`.
1314#[derive(Debug, Clone, Copy, Default)]
1315pub struct IdAllocatorBundle {
1316    pub turn: IdAllocator,
1317    pub tool_call: IdAllocator,
1318    /// Global, conversation-wide image counter. Every pasted image draws its
1319    /// stable `[Image #N]` display number from here, so the number stays with
1320    /// that image across the whole chat (and across `--resume`, which reseeds it
1321    /// past the highest persisted number in `seed_conversation`).
1322    pub image: IdAllocator,
1323}
1324
1325impl IdAllocatorBundle {
1326    pub fn fresh_turn(&mut self) -> TurnId {
1327        TurnId(self.turn.next())
1328    }
1329
1330    pub fn fresh_tool_call(&mut self) -> ToolCallId {
1331        ToolCallId(self.tool_call.next())
1332    }
1333
1334    pub fn fresh_image(&mut self) -> u64 {
1335        self.image.next()
1336    }
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341    use super::*;
1342
1343    fn mock_state() -> State {
1344        State::new(
1345            Config::default(),
1346            PathBuf::from("/tmp/project"),
1347            "ollama/test".to_string(),
1348            chrono::Local::now(),
1349        )
1350    }
1351
1352    #[test]
1353    fn fresh_state_is_idle() {
1354        let s = mock_state();
1355        assert!(matches!(s.turn, TurnState::Idle));
1356        assert!(!s.is_busy());
1357        assert!(s.current_turn_id().is_none());
1358    }
1359
1360    #[test]
1361    fn snapshot_and_seed_round_trip_restores_meters_and_safety() {
1362        // Move the live session state away from its `State::new` defaults, then
1363        // snapshot it into a conversation and seed it back into a fresh state —
1364        // this is exactly the save→resume path.
1365        let mut src = mock_state();
1366        src.session.safety_mode = SafetyMode::FullAccess;
1367        src.session.cumulative_token_usage = TokenUsageTotals {
1368            prompt_tokens: 4321,
1369            ..Default::default()
1370        };
1371        src.session.last_token_usage = Some(TokenUsageTotals {
1372            prompt_tokens: 100,
1373            ..Default::default()
1374        });
1375        src.session.context_usage = Some(ContextUsageSnapshot::new(
1376            8000,
1377            Some(128_000),
1378            TokenUsageSource::Estimate,
1379            8000,
1380            0,
1381            0,
1382            0,
1383            0,
1384            None,
1385        ));
1386
1387        let snapshot = src.session.snapshot_conversation();
1388
1389        let mut restored = mock_state();
1390        assert_eq!(
1391            restored.session.safety_mode,
1392            SafetyMode::Ask,
1393            "config default"
1394        );
1395        assert_eq!(restored.session.cumulative_token_usage.total_tokens(), 0);
1396
1397        restored.seed_conversation(snapshot);
1398        assert_eq!(restored.session.safety_mode, SafetyMode::FullAccess);
1399        assert_eq!(restored.session.cumulative_token_usage.total_tokens(), 4321);
1400        assert_eq!(
1401            restored.session.last_token_usage.unwrap().total_tokens(),
1402            100
1403        );
1404        assert_eq!(restored.session.context_usage.unwrap().used_tokens, 8000);
1405    }
1406
1407    #[test]
1408    fn seed_from_pre_persistence_file_keeps_config_default_safety() {
1409        // A conversation saved before these fields existed has `safety_mode:
1410        // None`; seeding it must NOT clobber the config-default mode that
1411        // `State::new` already set.
1412        let history = ConversationHistory::new(
1413            "/tmp/p".to_string(),
1414            "ollama/test".to_string(),
1415            chrono::Local::now(),
1416        );
1417        assert_eq!(history.safety_mode, None);
1418        let mut restored = mock_state();
1419        restored.session.safety_mode = SafetyMode::Auto; // stand in for a config default
1420        restored.seed_conversation(history);
1421        assert_eq!(
1422            restored.session.safety_mode,
1423            SafetyMode::Auto,
1424            "a None saved mode must not override the config default"
1425        );
1426    }
1427
1428    #[test]
1429    fn turn_state_accepts_matches_id() {
1430        let s = TurnState::Generating {
1431            id: TurnId(7),
1432            started: SystemTime::now(),
1433            partial_text: String::new(),
1434            partial_reasoning: String::new(),
1435            tokens: 0,
1436            phase: GenPhase::Sending,
1437            provider_continuation: None,
1438            pending_tool_calls: Vec::new(),
1439            continuation: false,
1440        };
1441        assert!(s.accepts(TurnId(7)));
1442        assert!(!s.accepts(TurnId(6)));
1443        assert!(!s.accepts(TurnId(8)));
1444    }
1445
1446    #[test]
1447    fn idle_rejects_all_turn_ids() {
1448        let s = TurnState::Idle;
1449        assert!(!s.accepts(TurnId(1)));
1450        assert!(!s.accepts(TurnId(999)));
1451    }
1452
1453    #[test]
1454    fn fresh_id_allocators_monotonic() {
1455        let mut bundle = IdAllocatorBundle::default();
1456        assert_eq!(bundle.fresh_turn(), TurnId(1));
1457        assert_eq!(bundle.fresh_turn(), TurnId(2));
1458        assert_eq!(bundle.fresh_tool_call(), ToolCallId(1));
1459        // Cross-allocator independence — fresh turns don't consume
1460        // tool call IDs.
1461    }
1462
1463    #[test]
1464    fn tool_outcome_cancelled_content_is_placeholder() {
1465        let o = ToolOutcome::cancelled();
1466        assert!(o.was_cancelled());
1467        let content = o.as_tool_message_content();
1468        assert!(content.contains("cancelled"));
1469    }
1470
1471    #[test]
1472    fn tool_outcome_finished_returns_output_verbatim() {
1473        let o = ToolOutcome::success("hello world", "hello world", 0.1);
1474        assert_eq!(o.as_tool_message_content(), "hello world");
1475        assert!(!o.was_cancelled());
1476    }
1477
1478    #[test]
1479    fn session_append_records_message() {
1480        let mut s = mock_state();
1481        s.session.append(ChatMessage::user("hi"), s.now);
1482        assert_eq!(s.session.messages().len(), 1);
1483        assert_eq!(s.session.messages()[0].content, "hi");
1484    }
1485}