mermaid-cli 0.17.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Every input to the reducer.
//!
//! `Msg` is an exhaustive sum over three categories:
//!
//!   1. **User intent** — key presses, pastes, slash commands, submit,
//!      cancel, quit. Originates from `app::event_source`.
//!   2. **Effect results** — stream chunks, tool outcomes, MCP
//!      lifecycle, save/load completion. Originates from
//!      `effect::EffectRunner` when a spawned task finishes a unit of
//!      work.
//!   3. **Housekeeping** — `Tick` (timer-driven redraw),
//!      `InstructionsChanged` (mtime watcher).
//!
//! Every effect-result variant carries a `TurnId`. The reducer's first
//! gate on any such message is `if state.turn.accepts(msg.turn_id())`
//! — messages for a cancelled / superseded turn are dropped without
//! state change. This is the architectural guarantee that stale
//! streaming events can never corrupt the current turn.

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::app::McpServerConfig;
use crate::app::instructions::LoadedInstructions;
use crate::models::tool_call::ToolCall as ModelToolCall;
use crate::models::{
    FinishReason, ProviderContinuation, ReasoningChunk, ReasoningLevel, TokenUsage, UserFacingError,
};
use crate::runtime::{
    ApprovalRecord, CheckpointRecord, PluginInstallRecord, ProcessRecord, SafetyMode, TaskRecord,
    TaskTimelineEvent,
};

use super::ids::{ToolCallId, TurnId};
use super::question::Question;
use super::runtime::RuntimeSignal;
use super::state::ContextUsageSnapshot;
use super::state::StatusKind;
use super::state::{ApprovalKind, ConversationSummary, McpToolSpec, ToolOutcome};
use super::{CompactionResult, CompactionTrigger};

/// Single reducer input. Non-exhaustive is intentional: adding a new
/// variant is a deliberate act that forces every reducer arm to
/// consider it at compile time (the reducer's match is NOT
/// `_ =>` — see `reducer.rs`).
///
/// Serde derives exist for `--record` / `--replay`: every `Msg` the driver
/// feeds the reducer is serialized to one JSONL line, and replay folds the
/// deserialized stream back through `update()`. New variants round-trip
/// automatically via the externally-tagged representation — no per-variant
/// recording code to keep in sync.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum Msg {
    // ── User intent ─────────────────────────────────────────────────
    /// Raw key event from crossterm, after the event source has
    /// stripped mouse/resize/paste.
    Key(Key),
    /// A terminal bracketed paste (always text; see [`Paste`]).
    Paste(Paste),
    /// Async result of a `Cmd::ReadClipboard` (Ctrl+V) — image, text, empty, or
    /// error. Kept separate from [`Msg::Paste`] so the paste-race guard can
    /// track exactly these reads (see [`ClipboardRead`]).
    ClipboardRead(ClipboardRead),
    /// User hit Enter on a non-empty input. The event source has
    /// already stripped the slash-command routing.
    SubmitPrompt {
        text: String,
        /// Attachment IDs the reducer should consume from state.
        attachment_ids: Vec<u64>,
    },
    /// User ran a slash command (post-routing from `app::event_source`).
    Slash(SlashCmd),
    /// Esc or another explicit cancellation source during an active turn.
    CancelTurn,
    /// Confirmation modal answer.
    ConfirmAccepted,
    ConfirmDeclined,
    /// User wants to exit cleanly (Ctrl+D with empty input, or `/quit`).
    Quit,
    /// External process lifecycle signal. In raw-mode TUI sessions a
    /// typed Ctrl+C still arrives as `Msg::Key`; this variant covers
    /// OS-level SIGINT/SIGTERM/SIGHUP delivered from outside.
    RuntimeSignal(RuntimeSignal),

    // ── Streaming (from effect::model) ──────────────────────────────
    /// Chunk of assistant text. Append to `partial_text`.
    StreamText {
        turn: TurnId,
        chunk: String,
    },
    /// Chunk of reasoning / thinking content.
    StreamReasoning {
        turn: TurnId,
        chunk: ReasoningChunk,
    },
    /// Model emitted a tool call. Append to the outgoing call list;
    /// actual execution dispatches on `StreamDone`.
    StreamToolCall {
        turn: TurnId,
        call: ModelToolCall,
    },
    /// Effect runner estimated the fully-enriched request context
    /// after built-in and MCP tool schemas were attached.
    ContextUsageEstimated {
        turn: TurnId,
        snapshot: ContextUsageSnapshot,
    },
    /// Effect runner resolved the provider's context window. For Ollama,
    /// `model_max` is the probed architectural window and `effective` is the
    /// auto-fitted/overridden `num_ctx`. Model-level metadata (not turn-scoped);
    /// `model_id` is carried so a probe that lands after a `/model` switch can
    /// be dropped instead of overwriting the new model's window. Drives the
    /// `/context` display + quick-fix.
    ProviderContextResolved {
        model_id: String,
        model_max: Option<usize>,
        effective: Option<usize>,
        source: Option<crate::models::adapters::ollama_sizing::NumCtxSource>,
        /// The model's per-response output ceiling when the provider exposes
        /// one (`/models` metadata / documented table). `#[serde(default)]` so
        /// recordings from before this field replay unchanged.
        #[serde(default)]
        max_output: Option<usize>,
    },
    /// Effect runner verified the loaded model's memory placement after a turn
    /// (Ollama `/api/ps`). `size_vram_bytes < total_bytes` ⇒ the model spilled
    /// to CPU/RAM (slow). Model-level metadata (not turn-scoped); `model_id` is
    /// carried so a probe that lands after a `/model` switch can be dropped.
    /// Drives the offload warning + `/context` placement line.
    OllamaPlacementResolved {
        model_id: String,
        size_vram_bytes: u64,
        total_bytes: u64,
        /// Auto-converge target: largest `num_ctx` that would fit when the model
        /// spilled, or `None` if it fits / can't be helped by shrinking.
        suggested_num_ctx: Option<u32>,
    },
    /// Effect runner probed whether the active model can see images (Ollama
    /// `/api/show` `capabilities`). Model-level metadata (not turn-scoped);
    /// `model_id` is carried so a probe that lands after a `/model` switch is
    /// dropped. `warn` (set at the trigger site — an image paste, a `/model`
    /// switch with an image staged, or a send carrying images) gates the
    /// one-shot no-vision-model notice; the capability snapshot refreshes
    /// regardless. `supports_vision` is `None` when unknown (non-Ollama, or the
    /// probe failed) → never warn.
    ProviderVisionResolved {
        model_id: String,
        supports_vision: Option<bool>,
        warn: bool,
    },
    /// The effect runner's estimate of the built-in tool-schema token cost
    /// it appends to every request during dispatch. Not turn-scoped — the
    /// reducer stores it on `runtime` so `/context` can fold it into its
    /// MCP-only estimate and agree with what dispatch actually decides.
    BuiltinToolSchemaTokens(usize),
    /// Context compaction completed and produced a replacement
    /// model-visible history.
    CompactionFinished {
        turn: TurnId,
        result: CompactionResult,
    },
    /// Context compaction failed or no-oped. Manual failures end the
    /// compaction turn; auto failures may leave generation running.
    CompactionFailed {
        turn: TurnId,
        trigger: CompactionTrigger,
        message: String,
        kind: StatusKind,
    },
    /// Stream complete. Carries final token count and opaque provider state
    /// that must round-trip on the next request.
    StreamDone {
        turn: TurnId,
        usage: Option<TokenUsage>,
        provider_continuation: Option<ProviderContinuation>,
        /// Why the model stopped (truncation / content block / normal), when
        /// the provider reported it. Drives the truncation status note.
        stop_reason: Option<FinishReason>,
    },
    /// Upstream returned a recoverable or terminal error. Reducer
    /// commits an error line and returns to `Idle` (or surfaces a
    /// retry affordance, if `recoverable`).
    UpstreamError {
        turn: TurnId,
        error: UserFacingError,
    },
    /// Terminal event for a cancelled turn. Emitted by the effect
    /// runner's `drop_scope` once every child task in the turn's
    /// `TurnScope` has unwound. Reducer transitions
    /// `Cancelling(id) → Idle` when it arrives.
    ///
    /// Without this, the reducer relies on the (wrong) side-channel of
    /// `UpstreamError` arriving from a cancelled provider call to exit
    /// `Cancelling`. If the provider task is aborted before it can
    /// emit an error, the state would stick in `Cancelling` forever.
    TurnCancelled(TurnId),

    // ── Tools (from effect::tool) ───────────────────────────────────
    /// Tool was picked up by the executor — useful for "spinner
    /// started" UI transitions.
    ToolStarted {
        turn: TurnId,
        call_id: ToolCallId,
    },
    /// Mid-flight progress (streaming subprocess output, byte-count
    /// updates, multimodal artifacts, nested subagent activity).
    /// Reducer pattern-matches the variant and routes accordingly:
    /// text variants update the status line; `Artifact` with an
    /// `image/*` mime attaches to the in-flight assistant message;
    /// `Subagent*` variants render as indented status.
    ToolProgress {
        turn: TurnId,
        call_id: ToolCallId,
        event: crate::providers::ProgressEvent,
    },
    /// Tool finished (one of Finished / Error / Cancelled).
    ToolFinished {
        turn: TurnId,
        call_id: ToolCallId,
        outcome: ToolOutcome,
    },
    /// A gated tool is awaiting the user's inline approval (interactive
    /// `ask` mode / Auto-mode escalation). The reducer enqueues a modal; the
    /// answer flows back as `Cmd::ResolveApproval`. The tool task is parked
    /// until then, so the turn naturally pauses (its outcome slot stays
    /// `None`).
    ApprovalRequested {
        turn: TurnId,
        call_id: ToolCallId,
        tool: String,
        risk: String,
        kind: ApprovalKind,
        prompt: String,
        allowlist_scope: String,
    },
    /// The `ask_user_question` tool is asking the user a batch of questions. The
    /// reducer stores a `PendingQuestionSet` and renders a selectable modal; the
    /// answer flows back as `Cmd::ResolveQuestion`. The tool task is parked until
    /// then, so the turn naturally pauses (its outcome slot stays `None`).
    QuestionAsked {
        turn: TurnId,
        call_id: ToolCallId,
        questions: Vec<Question>,
    },
    /// The `TaskBroker` published a full checklist snapshot after a task tool
    /// (or `/tasks` edit) mutated the store. Fire-and-forget — the broker
    /// already holds the new truth; the reducer replaces `conversation.tasks`
    /// and diffs old vs new for `task_completed` hook dispatch. Snapshot (not
    /// a diff) so this arm is a plain replace and can never desync. Not
    /// turn-scoped: `/tasks` edits arrive outside any turn, and gating would
    /// only let the render copy drift from the broker's truth.
    TasksUpdated {
        store: crate::domain::tasks::TaskStore,
    },
    /// A one-line checklist notice for the model's next request (user
    /// `/todos` edit, vetoed completion). Buffered on
    /// `state.pending_task_notices`; the reducer never turn-gates it.
    TaskNotice {
        text: String,
    },

    // ── MCP (from effect::mcp) ──────────────────────────────────────
    /// `initialize` succeeded; server is ready to dispatch tools.
    McpServerReady {
        name: String,
        tools: Vec<McpToolSpec>,
    },
    /// Server startup failed OR the child exited with non-zero.
    McpServerErrored {
        name: String,
        reason: String,
    },
    McpServerStopped {
        name: String,
    },

    /// Context strings returned by `before_tool_use` plugin hooks
    /// (`additionalContext`). The reducer buffers them (capped) and the next
    /// dispatched model request carries them in the instructions channel,
    /// consumed exactly once. Turn-scoped so a stale hook's context can't
    /// leak into a later run.
    HookContext {
        turn: TurnId,
        texts: Vec<String>,
    },

    // ── Persistence (from effect::persistence) ──────────────────────
    /// `MERMAID.md` loaded / changed / removed since last check.
    InstructionsChanged(Option<LoadedInstructions>),
    /// Memory files loaded / changed / removed since last check.
    MemoryChanged(Option<crate::app::memory::LoadedMemory>),
    /// `save_conversation` finished.
    SessionSaved,
    /// `/load <id>` — a saved conversation has been read off disk.
    ConversationLoaded(crate::session::ConversationHistory),
    /// Response to `Cmd::ListConversations`. Populates the `/load`
    /// picker's candidate list.
    ConversationsListed(Vec<ConversationSummary>),
    /// Response to `Cmd::ListProjectFiles`: relative project paths for the
    /// @-mention picker (gitignore-aware walk, capped, sorted; directories
    /// carry a trailing `/`).
    ProjectFilesListed(Vec<String>),
    /// Response to `Cmd::EnsureScratchpad`: the per-session scratch directory
    /// exists on disk at `path`. Carries the conversation id it was minted
    /// for so the reducer can drop a stale ready that raced a `/clear` or
    /// `/load` — it stamps `Session::scratchpad` only when the id still
    /// matches the live conversation.
    ScratchpadReady {
        session_id: String,
        path: PathBuf,
    },
    /// Response to `/tasks`.
    RuntimeTasksListed(Vec<TaskRecord>),
    /// Response to `/task <id>`.
    RuntimeTaskLoaded {
        task: Option<TaskRecord>,
        events: Vec<TaskTimelineEvent>,
    },
    /// Response to `/processes`.
    RuntimeProcessesListed(Vec<ProcessRecord>),
    /// Generic daemon/runtime text response.
    RuntimeText(String),
    RuntimeApprovalsListed(Vec<ApprovalRecord>),
    RuntimeCheckpointsListed(Vec<CheckpointRecord>),
    /// Reply to `Cmd::ListForkCheckpoints`: file checkpoints anchored past a
    /// rewind's fork point (oldest first). The reducer emits a system notice
    /// naming the oldest so the user can `/restore` files the discarded
    /// timeline changed; empty means no notice.
    ForkCheckpointsFound(Vec<CheckpointRecord>),
    RuntimePluginsListed(Vec<PluginInstallRecord>),

    // ── Misc model operations ───────────────────────────────────────
    /// `/model <name>` finished pulling (Ollama only).
    ModelPullFinished {
        model: String,
    },
    /// Streaming stdout line from an `ollama pull` subprocess.
    /// Reducer forwards to the status line for the user to watch.
    ModelPullProgress(String),

    // ── Housekeeping ────────────────────────────────────────────────
    /// 1/60s timer tick. Used for spinner animation + elapsed-time
    /// display. Reducer only advances derived fields.
    Tick,
    /// Terminal was resized. Reducer normally no-ops; render consumes.
    Resize {
        width: u16,
        height: u16,
    },

    // ── Status feedback from async effects ─────────────────────────
    /// Generic user-visible feedback from an async effect handler, routed into
    /// the chat transcript. Lets effects surface a result (clipboard read,
    /// config saved, plugin install, …) without a bespoke Msg per effect.
    TransientStatus {
        text: String,
    },

    /// The `$EDITOR` compose round-trip finished (Ctrl+O / `/editor`). The
    /// run loop suspends the TUI, launches the editor, and pushes this with
    /// the edited draft — so the recording captures the RESULT and `--replay`
    /// never launches an editor. `Some(text)` replaces the input buffer
    /// (empty = deliberate clear); `None` = no-op (defensive).
    EditorReturned {
        text: Option<String>,
    },

    // ── Background subagents (Ctrl+B detach) ───────────────────────
    /// A subagent was detached from its turn via Ctrl+B and keeps running
    /// in its own task. Adds a row to the live agent panel registry.
    BackgroundAgentStarted {
        agent_id: String,
        description: String,
    },
    /// Throttled live activity from a detached subagent (same discipline as
    /// `ProgressEvent::Subagent*` — never per stream chunk).
    BackgroundAgentProgress {
        agent_id: String,
        activity: String,
        tokens: usize,
    },
    /// A detached subagent finished. Removes its panel row, folds the child's
    /// spend into the session totals, and delivers the report to the model
    /// via the queued-message path.
    BackgroundAgentFinished {
        agent_id: String,
        description: String,
        report: String,
        success: bool,
        /// The drive ended because its cancel token fired (`/agents kill`,
        /// the `agent` tool's kill action). A cancelled child gets a system
        /// note but NO queued report — the killer already knows.
        #[serde(default)]
        cancelled: bool,
        /// Provider-reported usage for the child's whole drive (None when the
        /// provider reported nothing — the display falls back to `tokens`).
        usage: Option<TokenUsage>,
        /// Display token count (usage total, or the live estimate).
        tokens: usize,
        duration_secs: u64,
    },

    // ── Mouse (F13) ─────────────────────────────────────────────────
    /// Mouse-wheel scroll in the chat pane. Positive delta = scroll
    /// toward older messages (up), negative = toward newer (down). The
    /// reducer accumulates into `ui.mouse_scroll_accum`; the render layer
    /// diffs it and applies the delta to the ChatWidget's scroll offset.
    MouseScroll {
        delta: i16,
    },
    /// The terminal window gained (`true`) or lost (`false`) focus, from
    /// terminal focus reporting. The reducer records it in
    /// `ui.terminal_unfocused` to gate the attention bell.
    FocusChanged(bool),
    /// Ctrl+Click on an image thumbnail in the chat pane. The
    /// coordinates are absolute screen row/col; the render cache's
    /// `ChatState::find_image_at_screen_pos` maps them to a
    /// `(message_index, image_index)` pair. The main loop handles the
    /// lookup before forwarding this message to the reducer, so by
    /// the time the reducer sees it, the target has already been
    /// resolved into a base64 payload and this Msg carries the
    /// already-decoded image. The reducer just emits
    /// `Cmd::WriteImageToTemp` + `Cmd::OpenInSystem`.
    OpenImageAt {
        message_index: usize,
        image_index: usize,
        /// The clicked image's stable global `[Image #N]` number, when known.
        /// Preferred over the positional pair: the display transcript can be
        /// stitched (continuation merge, hidden nudges), so display indices
        /// need not match committed history. `default` so pre-stitch
        /// recordings replay.
        #[serde(default)]
        image_number: Option<u64>,
    },
    /// Copy the current chat text selection to the system clipboard. The main
    /// loop reads the selected text from the render layer (`rstate.chat`) and
    /// emits this, so the side effect flows through `update()` — and is recorded
    /// for replay — instead of being dispatched out-of-band (#18).
    CopySelection(String),
}

/// Bare key event — deliberately smaller than crossterm's `KeyEvent`
/// so the reducer doesn't depend on crossterm. The app event source
/// does the conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Key {
    pub code: KeyCode,
    pub modifiers: KeyMods,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyCode {
    Char(char),
    Enter,
    Escape,
    Backspace,
    Delete,
    Tab,
    BackTab,
    Left,
    Right,
    Up,
    Down,
    Home,
    End,
    PageUp,
    PageDown,
    F(u8),
    /// Anything we don't care about (media keys, etc.).
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct KeyMods {
    pub ctrl: bool,
    pub alt: bool,
    pub shift: bool,
}

impl KeyMods {
    pub const NONE: Self = Self {
        ctrl: false,
        alt: false,
        shift: false,
    };

    pub const fn ctrl() -> Self {
        Self {
            ctrl: true,
            ..Self::NONE
        }
    }

    pub const fn alt() -> Self {
        Self {
            alt: true,
            ..Self::NONE
        }
    }

    pub fn is_empty(self) -> bool {
        !self.ctrl && !self.alt && !self.shift
    }
}

/// Terminal paste payload. Always text: crossterm bracketed paste (and the
/// Windows key-burst coalescer) only ever deliver text. Clipboard reads via
/// Ctrl+V — which can be images — arrive separately as [`Msg::ClipboardRead`]
/// so the paste-race guard can tell the two apart.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Paste {
    Text(String),
}

/// Result of a `Cmd::ReadClipboard` (Ctrl+V), delivered asynchronously by the
/// effect runner. Distinct from [`Paste`] (terminal bracketed paste) so the
/// reducer can decrement `clipboard_reads_pending` on exactly these — and only
/// these — messages, including the empty/error outcomes, which must still
/// release a submit that was held waiting on the read.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClipboardRead {
    /// A raster image. Bytes serialize as base64 so a recorded session replays
    /// pasted images bit-exactly without a numbers-array blowup in the JSONL.
    Image {
        #[serde(with = "crate::utils::serde_base64")]
        bytes: Vec<u8>,
        format: String,
    },
    /// Plain text on the clipboard.
    Text(String),
    /// The clipboard held nothing readable.
    Empty,
    /// The read failed (helper missing, timed out, etc.); the string is a
    /// user-facing reason.
    Error(String),
}

/// `/context` subcommands. No-arg shows the window; the rest tune the Ollama
/// context window (per-model, persisted), mirroring `/reasoning`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContextCmd {
    /// Show the current window + usage (no arg).
    Show,
    /// `/context <n>` — set a per-model `num_ctx` override.
    Set(u32),
    /// `/context auto` — clear the override, return to auto-fit.
    Auto,
    /// `/context max` — use the model's full advertised window.
    Max,
    /// `/context offload on|off` — toggle Ollama RAM offload.
    Offload(bool),
}

/// Slash commands — a typed surface over what the user typed as
/// `/<name> [args]`. Parsed in `app::event_source` against the single
/// `COMMAND_REGISTRY`; unknown commands produce `SlashCmd::Unknown`
/// so the reducer can issue a "no such command" status line.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SlashCmd {
    /// No arg → show current; `Some` → switch (and pull if needed).
    Model(Option<String>),
    Reasoning(Option<ReasoningLevel>),
    VisibleReasoning(Option<String>),
    /// No arg → show current safety mode; `Some` → switch it for this
    /// session (`Shift+Tab` cycles the same field). Session-scoped.
    Safety(Option<SafetyMode>),
    /// Plan mode: no arg / `on` → enter; `off` → leave; `show` → print the
    /// plan-file path; `config` → open the settings picker. `Alt+P` toggles
    /// the same state. Session-scoped.
    Plan(Option<String>),
    /// Open the settings picker (currently the plan-mode section; more
    /// sections join it as they exist).
    Config,
    Clear,
    Save(Option<String>),
    Load(Option<String>),
    List,
    Usage,
    /// The task checklist: no arg → show; `add <subject>` / `rm <id>` /
    /// `done <id>` / `clear` edit it (routed through the TaskBroker).
    Todos(Option<String>),
    /// Show the session scratch directory and a bounded listing of its
    /// contents (via `Cmd::ListScratchpad`).
    Scratchpad,
    Context(ContextCmd),
    Compact(Option<String>),
    /// List saved durable memories.
    Memory,
    /// Save free-text as a private memory.
    Remember(Option<String>),
    /// Delete a memory by name/id.
    Forget(Option<String>),
    /// Prune duplicate/obsolete memories via a one-shot model pass.
    ConsolidateMemory,
    Doctor,
    Tasks,
    Task(Option<String>),
    Pause(Option<String>),
    Resume(Option<String>),
    Cancel(Option<String>),
    Handoff(Option<String>),
    Report(Option<String>),
    Processes,
    /// No arg → list background agents; `Some("kill <id>"|"kill all")` →
    /// cancel them. Tail parsed in the reducer arm.
    Agents(Option<String>),
    Logs(Option<String>),
    Stop(Option<String>),
    Restart(Option<String>),
    Open(Option<String>),
    Ports,
    Approvals,
    Approve(Option<String>),
    Deny(Option<String>),
    Checkpoint(Option<String>),
    Checkpoints,
    Restore(Option<String>),
    ModelInfo(Option<String>),
    Plugins,
    CloudSetup,
    /// No arg → show current theme; `Some("dark"|"light")` → switch and
    /// persist. Anything else → usage.
    Theme(Option<String>),
    /// Compose the input draft in `$VISUAL`/`$EDITOR` (also Ctrl+O).
    Editor,
    Help,
    Quit,
    /// User typed something that isn't in the registry; carries the
    /// raw name for the error message.
    Unknown(String),
}

impl Msg {
    /// Extract the `TurnId` for effect-result variants. Returns `None`
    /// for variants that aren't turn-scoped (user intent,
    /// housekeeping, MCP lifecycle). The reducer uses this to
    /// short-circuit stale events.
    pub fn turn_id(&self) -> Option<TurnId> {
        match self {
            Msg::StreamText { turn, .. }
            | Msg::StreamReasoning { turn, .. }
            | Msg::StreamToolCall { turn, .. }
            | Msg::ContextUsageEstimated { turn, .. }
            | Msg::CompactionFinished { turn, .. }
            | Msg::CompactionFailed { turn, .. }
            | Msg::StreamDone { turn, .. }
            | Msg::UpstreamError { turn, .. }
            | Msg::ToolStarted { turn, .. }
            | Msg::ToolProgress { turn, .. }
            | Msg::ToolFinished { turn, .. }
            | Msg::ApprovalRequested { turn, .. }
            | Msg::QuestionAsked { turn, .. }
            | Msg::HookContext { turn, .. } => Some(*turn),
            Msg::TurnCancelled(turn) => Some(*turn),
            _ => None,
        }
    }

    /// Classification for telemetry / replay tooling. Cheaper than a
    /// full `Debug` string and stable across refactors.
    pub fn kind(&self) -> MsgKind {
        match self {
            Msg::Key(_) => MsgKind::Key,
            Msg::Paste(_) => MsgKind::Paste,
            Msg::ClipboardRead(_) => MsgKind::ClipboardRead,
            Msg::SubmitPrompt { .. } => MsgKind::SubmitPrompt,
            Msg::Slash(_) => MsgKind::Slash,
            Msg::CancelTurn => MsgKind::CancelTurn,
            Msg::ConfirmAccepted | Msg::ConfirmDeclined => MsgKind::Confirm,
            Msg::Quit => MsgKind::Quit,
            Msg::RuntimeSignal(_) => MsgKind::RuntimeSignal,
            Msg::StreamText { .. } => MsgKind::StreamText,
            Msg::StreamReasoning { .. } => MsgKind::StreamReasoning,
            Msg::StreamToolCall { .. } => MsgKind::StreamToolCall,
            Msg::ContextUsageEstimated { .. } => MsgKind::ContextUsageEstimated,
            Msg::ProviderContextResolved { .. } => MsgKind::ProviderContextResolved,
            Msg::OllamaPlacementResolved { .. } => MsgKind::OllamaPlacementResolved,
            Msg::ProviderVisionResolved { .. } => MsgKind::ProviderVisionResolved,
            Msg::BuiltinToolSchemaTokens(_) => MsgKind::BuiltinToolSchemaTokens,
            Msg::CompactionFinished { .. } => MsgKind::CompactionFinished,
            Msg::CompactionFailed { .. } => MsgKind::CompactionFailed,
            Msg::StreamDone { .. } => MsgKind::StreamDone,
            Msg::UpstreamError { .. } => MsgKind::UpstreamError,
            Msg::ToolStarted { .. } => MsgKind::ToolStarted,
            Msg::ToolProgress { .. } => MsgKind::ToolProgress,
            Msg::ToolFinished { .. } => MsgKind::ToolFinished,
            Msg::ApprovalRequested { .. } => MsgKind::ApprovalRequested,
            Msg::QuestionAsked { .. } => MsgKind::QuestionAsked,
            Msg::TasksUpdated { .. } => MsgKind::TasksUpdated,
            Msg::TaskNotice { .. } => MsgKind::TaskNotice,
            Msg::TurnCancelled(_) => MsgKind::TurnCancelled,
            Msg::McpServerReady { .. }
            | Msg::McpServerErrored { .. }
            | Msg::McpServerStopped { .. } => MsgKind::Mcp,
            Msg::HookContext { .. } => MsgKind::HookContext,
            Msg::InstructionsChanged(_) => MsgKind::InstructionsChanged,
            Msg::MemoryChanged(_) => MsgKind::MemoryChanged,
            Msg::SessionSaved => MsgKind::SessionSaved,
            Msg::ConversationLoaded(_) => MsgKind::ConversationLoaded,
            Msg::ConversationsListed(_) => MsgKind::ConversationsListed,
            Msg::ProjectFilesListed(_) => MsgKind::ProjectFilesListed,
            Msg::ScratchpadReady { .. } => MsgKind::ScratchpadReady,
            Msg::RuntimeTasksListed(_)
            | Msg::RuntimeTaskLoaded { .. }
            | Msg::RuntimeProcessesListed(_)
            | Msg::RuntimeText(_)
            | Msg::RuntimeApprovalsListed(_)
            | Msg::RuntimeCheckpointsListed(_)
            | Msg::ForkCheckpointsFound(_)
            | Msg::RuntimePluginsListed(_) => MsgKind::RuntimeStore,
            Msg::ModelPullFinished { .. } => MsgKind::ModelPullFinished,
            Msg::ModelPullProgress(_) => MsgKind::ModelPullProgress,
            Msg::Tick => MsgKind::Tick,
            Msg::Resize { .. } => MsgKind::Resize,
            Msg::MouseScroll { .. } => MsgKind::MouseScroll,
            Msg::FocusChanged(_) => MsgKind::FocusChanged,
            Msg::OpenImageAt { .. } => MsgKind::OpenImageAt,
            Msg::TransientStatus { .. } => MsgKind::TransientStatus,
            Msg::EditorReturned { .. } => MsgKind::EditorReturned,
            Msg::BackgroundAgentStarted { .. }
            | Msg::BackgroundAgentProgress { .. }
            | Msg::BackgroundAgentFinished { .. } => MsgKind::BackgroundAgent,
            Msg::CopySelection(_) => MsgKind::CopySelection,
        }
    }
}

/// Compact kind tag for tracing / replay indexing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MsgKind {
    Key,
    Paste,
    ClipboardRead,
    SubmitPrompt,
    Slash,
    CancelTurn,
    Confirm,
    Quit,
    RuntimeSignal,
    StreamText,
    StreamReasoning,
    StreamToolCall,
    ContextUsageEstimated,
    ProviderContextResolved,
    OllamaPlacementResolved,
    ProviderVisionResolved,
    BuiltinToolSchemaTokens,
    CompactionFinished,
    CompactionFailed,
    StreamDone,
    UpstreamError,
    ToolStarted,
    ToolProgress,
    ToolFinished,
    ApprovalRequested,
    QuestionAsked,
    TasksUpdated,
    TaskNotice,
    TurnCancelled,
    Mcp,
    InstructionsChanged,
    HookContext,
    MemoryChanged,
    SessionSaved,
    ConversationLoaded,
    ConversationsListed,
    ProjectFilesListed,
    ScratchpadReady,
    RuntimeStore,
    ModelPullFinished,
    ModelPullProgress,
    Tick,
    Resize,
    MouseScroll,
    FocusChanged,
    BackgroundAgent,
    OpenImageAt,
    TransientStatus,
    EditorReturned,
    CopySelection,
}

/// Helper for `app::event_source` — pass through the MCP config that
/// effect::mcp needs to dispatch `InitMcpServers` as its first effect.
/// Not a `Msg` because it's startup-only.
#[derive(Debug, Clone)]
pub struct StartupConfig {
    pub mcp_servers: std::collections::HashMap<String, McpServerConfig>,
    pub cwd: PathBuf,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn turn_id_extracted_from_stream_messages() {
        let m = Msg::StreamText {
            turn: TurnId(7),
            chunk: "hi".to_string(),
        };
        assert_eq!(m.turn_id(), Some(TurnId(7)));
    }

    #[test]
    fn turn_id_none_for_user_intent() {
        let m = Msg::CancelTurn;
        assert_eq!(m.turn_id(), None);
        let m = Msg::Quit;
        assert_eq!(m.turn_id(), None);
        let m = Msg::Tick;
        assert_eq!(m.turn_id(), None);
    }

    #[test]
    fn turn_id_none_for_mcp_lifecycle() {
        let m = Msg::McpServerReady {
            name: "s".to_string(),
            tools: vec![],
        };
        assert_eq!(m.turn_id(), None);
    }

    #[test]
    fn key_mods_builder_defaults_match_const() {
        assert_eq!(KeyMods::default(), KeyMods::NONE);
        assert!(KeyMods::ctrl().ctrl);
        assert!(!KeyMods::ctrl().alt);
        assert!(!KeyMods::ctrl().shift);
    }

    #[test]
    fn kind_stable_across_variants() {
        assert_eq!(Msg::Quit.kind(), MsgKind::Quit);
        assert_eq!(Msg::Tick.kind(), MsgKind::Tick);
        assert_eq!(
            Msg::StreamText {
                turn: TurnId(1),
                chunk: String::new()
            }
            .kind(),
            MsgKind::StreamText
        );
    }

    #[test]
    fn slash_cmd_carries_none_for_no_arg() {
        let c = SlashCmd::Model(None);
        assert_eq!(c, SlashCmd::Model(None));
        assert_ne!(c, SlashCmd::Model(Some("ollama/qwen3".to_string())));
    }
}