capo-agent 0.8.0

Coding-agent library built on motosan-agent-loop. Composable, embeddable.
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
#![cfg_attr(test, allow(clippy::expect_used))]

use motosan_agent_tool::ToolResult;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Clone, Serialize)]
pub enum ProgressChunk {
    Stdout(Vec<u8>),
    Stderr(Vec<u8>),
    Status(String),
}

impl From<crate::tools::ToolProgressChunk> for ProgressChunk {
    fn from(c: crate::tools::ToolProgressChunk) -> Self {
        use crate::tools::ToolProgressChunk as TPC;
        match c {
            TPC::Stdout(b) => Self::Stdout(b),
            TPC::Stderr(b) => Self::Stderr(b),
            TPC::Status(s) => Self::Status(s),
        }
    }
}

/// User's answer to a `PermissionRequested` prompt, carried back from the
/// front-end to the binary so the binary can update the session cache.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PermissionResolution {
    pub tool: String,
    pub args: serde_json::Value,
    pub choice: PermissionChoice,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionChoice {
    AllowOnce,
    AllowSession,
    Deny,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
pub enum Command {
    SendUserMessage {
        text: String,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        attachments: Vec<crate::user_message::Attachment>,
    },
    CancelAgent,
    Quit,
    ResolvePermission(PermissionResolution),
    /// `!cmd` / `!!cmd` — run a shell command typed directly by the user.
    /// `send_to_llm` is true for `!cmd` (output becomes a user message),
    /// false for `!!cmd` (output shown in the transcript only).
    RunInlineBash {
        command: String,
        send_to_llm: bool,
    },
    /// Manual context compaction, triggered by the `/compact` slash command.
    Compact,
    /// Apply a `Settings` struct in-memory and rebuild the live session
    /// with new settings, then atomically persist to settings.toml on
    /// success. Used by the TUI `/settings` editor. **Rebuild-first**:
    /// if the rebuild fails (e.g. provider lacks auth), disk is NOT
    /// touched — the user's live session stays consistent with disk.
    /// See spec §4.3 and §4.4.
    ApplySettings {
        settings: crate::settings::Settings,
    },
    /// Re-read ~/.capo/agent/settings.toml and rebuild the live session
    /// with whatever settings are on disk. Used by external RPC clients
    /// that have edited the file themselves. Failure leaves disk and
    /// live session divergent — caller's responsibility. See spec §4.4.
    ReloadSettings,
    /// `/new` — replace the live session with a fresh empty one.
    NewSession,
    /// `/clone` — copy the current session to a new independent file and
    /// switch to it. Handled by `forward_commands`.
    CloneSession,
    /// `--rpc` read query: reply with the session's `Vec<Message>`
    /// history via `UiEvent::MessagesSnapshot`. No effect on the agent.
    GetMessages,
    /// `--rpc` read query: reply with a small status snapshot via
    /// `UiEvent::StateSnapshot`. No effect on the agent.
    GetState,
    /// `--rpc` read query: reply with the registered extensions + load
    /// diagnostics via `UiEvent::ExtensionList`. No agent effect.
    ListExtensions,
    /// Invoke an extension-registered slash command.
    /// Emitted by the TUI's slash palette when the user selects a command
    /// owned by an extension (not a built-in).
    InvokeExtensionCommand {
        name: String,
        args: String,
    },
    /// `/model` — rebuild the live session under a different model.
    SwitchModel(crate::model::ModelId),
    /// `/resume` — replace the live session with a stored one, by id.
    LoadSession(String),
    /// `/fork` — continue from an earlier entry, creating a branch.
    ForkFrom {
        from: String,
        message: String,
    },
}

impl PartialEq for Command {
    fn eq(&self, other: &Self) -> bool {
        use Command as C;
        match (self, other) {
            (
                C::SendUserMessage {
                    text: left_text,
                    attachments: left_attachments,
                },
                C::SendUserMessage {
                    text: right_text,
                    attachments: right_attachments,
                },
            ) => left_text == right_text && left_attachments == right_attachments,
            (C::CancelAgent, C::CancelAgent)
            | (C::Quit, C::Quit)
            | (C::Compact, C::Compact)
            | (C::ReloadSettings, C::ReloadSettings)
            | (C::NewSession, C::NewSession)
            | (C::CloneSession, C::CloneSession)
            | (C::GetMessages, C::GetMessages)
            | (C::GetState, C::GetState)
            | (C::ListExtensions, C::ListExtensions) => true,
            (C::ResolvePermission(left), C::ResolvePermission(right)) => left == right,
            (
                C::RunInlineBash {
                    command: left_command,
                    send_to_llm: left_send_to_llm,
                },
                C::RunInlineBash {
                    command: right_command,
                    send_to_llm: right_send_to_llm,
                },
            ) => left_command == right_command && left_send_to_llm == right_send_to_llm,
            (C::ApplySettings { settings: left }, C::ApplySettings { settings: right }) => {
                settings_command_eq(left, right)
            }
            (
                C::InvokeExtensionCommand {
                    name: left_name,
                    args: left_args,
                },
                C::InvokeExtensionCommand {
                    name: right_name,
                    args: right_args,
                },
            ) => left_name == right_name && left_args == right_args,
            (C::SwitchModel(left), C::SwitchModel(right)) => left == right,
            (C::LoadSession(left), C::LoadSession(right)) => left == right,
            (
                C::ForkFrom {
                    from: left_from,
                    message: left_message,
                },
                C::ForkFrom {
                    from: right_from,
                    message: right_message,
                },
            ) => left_from == right_from && left_message == right_message,
            _ => false,
        }
    }
}

impl Eq for Command {}

fn settings_command_eq(
    left: &crate::settings::Settings,
    right: &crate::settings::Settings,
) -> bool {
    left.model == right.model
        && left.anthropic == right.anthropic
        && left.ui == right.ui
        && left.session.autosave == right.session.autosave
        && left.session.compact_at_context_pct.to_bits()
            == right.session.compact_at_context_pct.to_bits()
        && left.session.max_context_tokens == right.session.max_context_tokens
        && left.session.keep_turns == right.session.keep_turns
        && left.logging == right.logging
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ExtensionInfo {
    pub name: String,
    pub hooks: Vec<String>,
    pub commands: Vec<String>,
    /// `true` if the extension's binary exists and is executable at the
    /// configured path. `false` if a load-time diagnostic blocked it.
    pub healthy: bool,
    /// Load-time diagnostic if `!healthy`. `None` otherwise.
    pub diagnostic: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
pub enum UiEvent {
    AgentTurnStarted,
    AgentThinking,
    AgentTextDelta(String),
    AgentMessageComplete(String),
    ToolCallStarted {
        id: String,
        name: String,
        args: Value,
    },
    ToolCallProgress {
        id: String,
        chunk: ProgressChunk,
    },
    ToolCallCompleted {
        id: String,
        result: UiToolResult,
    },
    AgentTurnComplete,
    /// Token-count summary emitted after each LLM chat call. Cumulative
    /// fields carry the running total for this session. Per-turn deltas
    /// (`input_tokens` / `output_tokens`) are the increment from THIS
    /// turn — 0 if the provider didn't surface counts (CLI shells may
    /// not). See spec §3.1.
    TurnStats {
        input_tokens: u64,
        output_tokens: u64,
        cumulative_input: u64,
        cumulative_output: u64,
        model: String,
    },
    PermissionRequested {
        tool: String,
        args: serde_json::Value,
        #[serde(skip)]
        resolver: tokio::sync::oneshot::Sender<crate::permissions::Decision>,
    },
    /// Output of a `!!cmd` inline-bash run, for transcript display.
    InlineBashOutput {
        command: String,
        output: String,
    },
    /// The session was replaced (`/new` cleared it, or `/resume` loaded a
    /// stored one). Carries the new transcript so the TUI can rebuild
    /// `state.messages`. Empty Vec = a fresh session.
    SessionReplaced(Vec<motosan_agent_loop::Message>),
    /// The active model changed successfully.
    ModelSwitched(crate::model::ModelId),
    /// Refreshed `/fork` candidate list (active-branch user messages,
    /// newest first) — `(EntryId, preview)` pairs. The binary emits this
    /// at startup and after every turn so the picker is never stale.
    ForkCandidates(Vec<(String, String)>),
    /// Refreshed session branch tree — the binary emits this at startup
    /// and after every turn so the `/tree` view is never stale.
    BranchTree(
        #[serde(serialize_with = "crate::protocol::serialize_branch_tree")]
        motosan_agent_loop::BranchTree,
    ),
    /// Reply to `Command::GetMessages` — the session's persisted message
    /// history. RPC clients use this to snapshot transcript state.
    MessagesSnapshot(Vec<motosan_agent_loop::Message>),
    /// Reply to `Command::GetState` — a small status snapshot for RPC
    /// clients (the TUI holds these in `AppState` so does not need it).
    StateSnapshot {
        session_id: String,
        model: String,
        active_turn: bool,
    },
    /// Reply to `Command::ListExtensions` — the registered extensions
    /// + per-extension health status.
    ExtensionList {
        extensions: Vec<ExtensionInfo>,
    },
    /// Snapshot of the current settings. Emitted by the binary at
    /// startup and after every successful `ApplySettings` / `ReloadSettings`
    /// so the TUI can update `state.settings_snapshot`. RPC clients
    /// can also consume this to observe live settings changes.
    SettingsSnapshot {
        settings: crate::settings::Settings,
    },
    Error(String),
    /// Emitted when an attachment in a `UserMessage` failed validation
    /// (path missing, unsupported extension, oversize, unreadable). No turn
    /// is started; the agent stays in `Idle`. See spec §3 / §4.4.
    AttachmentError {
        kind: crate::user_message::AttachmentErrorKind,
        message: String,
    },
    /// An extension cancelled a `before_user_message` or
    /// `session_before_switch` hook. The TUI rolls back any optimistic
    /// transcript push (via `state.pending_turn_submit`) and restores
    /// the composer buffer. See spec §4.4.
    ExtensionCancelled {
        extension_name: String,
        reason: Option<String>,
    },
    /// Surface a transcript notice from an extension `reply` action,
    /// `/image` errors, or other non-fatal informational events.
    Notice {
        title: String,
        body: String,
    },
}

#[derive(Debug, Clone, Serialize)]
pub struct UiToolResult {
    pub is_error: bool,
    pub text: String,
}

impl From<&ToolResult> for UiToolResult {
    fn from(r: &ToolResult) -> Self {
        Self {
            is_error: r.is_error,
            text: format!("{r:?}"),
        }
    }
}

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

    #[test]
    fn attachment_error_event_serializes_with_kind_and_message() {
        use crate::user_message::AttachmentErrorKind;

        let ev = UiEvent::AttachmentError {
            kind: AttachmentErrorKind::NotFound,
            message: "image not found: /tmp/foo.png".into(),
        };
        let json = serde_json::to_string(&ev).expect("serialize");
        // UiEvent uses tag = "type", content = "payload", rename_all = "snake_case"
        assert_eq!(
            json,
            r#"{"type":"attachment_error","payload":{"kind":"not_found","message":"image not found: /tmp/foo.png"}}"#
        );
    }

    #[test]
    fn compact_command_is_constructible() {
        let c = Command::Compact;
        assert_eq!(c, Command::Compact);
        assert!(format!("{c:?}").contains("Compact"));
    }

    #[test]
    fn d2_command_and_event_variants_construct() {
        let _ = Command::NewSession;
        let _ = Command::SwitchModel(crate::model::ModelId::from("m"));
        let _ = Command::LoadSession("sess-id".into());
        let e = UiEvent::SessionReplaced(Vec::new());
        assert!(format!("{e:?}").contains("SessionReplaced"));
        let e = UiEvent::ModelSwitched(crate::model::ModelId::from("m"));
        assert!(format!("{e:?}").contains("ModelSwitched"));
    }

    #[test]
    fn clone_session_command_constructs() {
        let c = Command::CloneSession;
        assert!(format!("{c:?}").contains("CloneSession"));
    }

    #[test]
    fn read_query_commands_round_trip() {
        for c in [Command::GetMessages, Command::GetState] {
            let line = serde_json::to_string(&c).expect("serialize");
            assert!(line.contains("\"type\":"), "{line}");
            let back: Command = serde_json::from_str(&line).expect("deserialize");
            assert_eq!(c, back);
        }
        // Unit variants serialize as bare `{"type":"…"}`.
        assert_eq!(
            serde_json::to_string(&Command::GetMessages).expect("ser"),
            r#"{"type":"get_messages"}"#
        );
    }

    #[test]
    fn fork_protocol_variants_construct() {
        let c = Command::ForkFrom {
            from: "e1".into(),
            message: "hi".into(),
        };
        assert!(format!("{c:?}").contains("ForkFrom"));
        let e = UiEvent::ForkCandidates(vec![("e1".into(), "first".into())]);
        assert!(format!("{e:?}").contains("ForkCandidates"));
    }

    #[test]
    fn branch_tree_event_constructs() {
        let tree = motosan_agent_loop::BranchTree {
            nodes: Vec::new(),
            root: None,
            active_leaf: None,
        };
        let e = UiEvent::BranchTree(tree);
        assert!(format!("{e:?}").contains("BranchTree"));
    }

    #[test]
    fn run_inline_bash_command_is_constructible() {
        let c = Command::RunInlineBash {
            command: "ls".into(),
            send_to_llm: true,
        };
        assert!(format!("{c:?}").contains("RunInlineBash"));
    }

    #[test]
    fn permission_protocol_variants_are_constructible() {
        let command = Command::ResolvePermission(PermissionResolution {
            tool: "bash".into(),
            args: serde_json::json!({"command": "echo hi"}),
            choice: PermissionChoice::AllowSession,
        });
        assert!(format!("{command:?}").contains("ResolvePermission"));
        assert!(format!("{command:?}").contains("AllowSession"));

        let (resolver, _rx) = tokio::sync::oneshot::channel::<crate::permissions::Decision>();
        let event = UiEvent::PermissionRequested {
            tool: "bash".into(),
            args: serde_json::json!({"command": "echo hi"}),
            resolver,
        };
        assert!(format!("{event:?}").contains("PermissionRequested"));
    }

    #[test]
    fn command_round_trips_through_json() {
        let cases = vec![
            Command::SendUserMessage {
                text: "hi".into(),
                attachments: Vec::new(),
            },
            Command::CancelAgent,
            Command::Quit,
            Command::Compact,
            Command::NewSession,
            Command::CloneSession,
            Command::RunInlineBash {
                command: "ls".into(),
                send_to_llm: true,
            },
            Command::SwitchModel(crate::model::ModelId::from("claude-opus-4-7")),
            Command::LoadSession("sess-1".into()),
            Command::ForkFrom {
                from: "e1".into(),
                message: "hi".into(),
            },
            Command::ResolvePermission(PermissionResolution {
                tool: "bash".into(),
                args: serde_json::json!({"command": "echo hi"}),
                choice: PermissionChoice::AllowSession,
            }),
        ];
        for c in cases {
            let line = serde_json::to_string(&c).expect("serialize");
            assert!(line.contains("\"type\":"), "missing type tag: {line}");
            let back: Command = serde_json::from_str(&line).expect("deserialize");
            assert_eq!(c, back, "round-trip mismatch for {line}");
        }
    }

    #[test]
    fn command_send_user_message_round_trip() {
        let line = serde_json::to_string(&Command::SendUserMessage {
            text: "hi".into(),
            attachments: Vec::new(),
        })
        .expect("serialize");
        assert_eq!(
            line,
            r#"{"type":"send_user_message","payload":{"text":"hi"}}"#
        );
        let back: Command = serde_json::from_str(&line).expect("deserialize");
        assert_eq!(
            back,
            Command::SendUserMessage {
                text: "hi".into(),
                attachments: Vec::new(),
            }
        );
    }

    #[test]
    fn command_send_user_message_with_attachment_round_trip() {
        let cmd = Command::SendUserMessage {
            text: "look".into(),
            attachments: vec![crate::user_message::Attachment::Image {
                path: std::path::PathBuf::from("/tmp/foo.png"),
            }],
        };
        let line = serde_json::to_string(&cmd).expect("serialize");
        assert_eq!(
            line,
            r#"{"type":"send_user_message","payload":{"text":"look","attachments":[{"type":"image","path":"/tmp/foo.png"}]}}"#
        );
        let back: Command = serde_json::from_str(&line).expect("deserialize");
        assert_eq!(back, cmd);
    }

    #[test]
    fn unit_command_uses_adjacent_tagging() {
        let unit = serde_json::to_string(&Command::CancelAgent).expect("serialize");
        assert_eq!(unit, r#"{"type":"cancel_agent"}"#);
    }

    #[test]
    fn command_invoke_extension_command_serde_round_trip() {
        let cmd = Command::InvokeExtensionCommand {
            name: "todo".into(),
            args: "add buy milk".into(),
        };
        let json = serde_json::to_string(&cmd).expect("ok");
        assert_eq!(
            json,
            r#"{"type":"invoke_extension_command","payload":{"name":"todo","args":"add buy milk"}}"#
        );
        let back: Command = serde_json::from_str(&json).expect("ok");
        assert_eq!(back, cmd);
    }

    #[test]
    fn ui_event_extension_cancelled_serializes() {
        let ev = UiEvent::ExtensionCancelled {
            extension_name: "dirty-repo-guard".into(),
            reason: Some("uncommitted changes".into()),
        };
        let json = serde_json::to_string(&ev).expect("ok");
        assert!(json.contains(r#""type":"extension_cancelled""#));
        assert!(json.contains(r#""extension_name":"dirty-repo-guard""#));
        assert!(json.contains(r#""reason":"uncommitted changes""#));
    }

    #[test]
    fn ui_event_notice_serializes() {
        let ev = UiEvent::Notice {
            title: "/todo".into(),
            body: "reply from fixture".into(),
        };
        let json = serde_json::to_string(&ev).expect("ok");
        assert!(json.contains(r#""type":"notice""#));
        assert!(json.contains(r#""title":"/todo""#));
        assert!(json.contains(r#""body":"reply from fixture""#));
    }

    #[test]
    fn ui_event_turn_stats_round_trips() {
        let ev = UiEvent::TurnStats {
            input_tokens: 1203,
            output_tokens: 412,
            cumulative_input: 12543,
            cumulative_output: 5231,
            model: "claude-opus-4-7".into(),
        };
        let line = serde_json::to_string(&ev).expect("serialize");
        assert_eq!(
            line,
            r#"{"type":"turn_stats","payload":{"input_tokens":1203,"output_tokens":412,"cumulative_input":12543,"cumulative_output":5231,"model":"claude-opus-4-7"}}"#
        );
    }

    #[test]
    fn command_still_exposes_eq_for_downstream_matchers() {
        fn assert_eq_impl<T: Eq>() {}
        assert_eq_impl::<Command>();
    }

    #[test]
    fn command_apply_settings_round_trips() {
        use crate::settings::Settings;
        let cmd = Command::ApplySettings {
            settings: Settings::default(),
        };
        let line = serde_json::to_string(&cmd).expect("serialize");
        // Smoke: payload contains a structured Settings object (not a string)
        assert!(line.contains(r#""type":"apply_settings""#));
        assert!(line.contains(r#""payload":{"#));
        assert!(line.contains(r#""model":"#));
        let back: Command = serde_json::from_str(&line).expect("deserialize");
        assert_eq!(back, cmd);
    }

    #[test]
    fn command_reload_settings_round_trips() {
        let cmd = Command::ReloadSettings;
        let line = serde_json::to_string(&cmd).expect("serialize");
        assert_eq!(line, r#"{"type":"reload_settings"}"#);
        let back: Command = serde_json::from_str(&line).expect("deserialize");
        assert_eq!(back, cmd);
    }

    #[test]
    fn ui_event_settings_snapshot_serializes() {
        use crate::settings::Settings;
        let ev = UiEvent::SettingsSnapshot {
            settings: Settings::default(),
        };
        let line = serde_json::to_string(&ev).expect("serialize");
        assert!(line.contains(r#""type":"settings_snapshot""#));
        assert!(line.contains(r#""payload":{"#));
        assert!(line.contains(r#""model":"#));
    }

    #[test]
    fn snapshot_events_serialize_with_type_tag() {
        let m = UiEvent::MessagesSnapshot(Vec::new());
        let line = serde_json::to_string(&m).expect("serialize");
        assert!(line.contains(r#""type":"messages_snapshot""#), "{line}");

        let s = UiEvent::StateSnapshot {
            session_id: "sess-1".into(),
            model: "claude-opus-4-7".into(),
            active_turn: false,
        };
        let line = serde_json::to_string(&s).expect("serialize");
        assert!(line.contains(r#""type":"state_snapshot""#), "{line}");
        assert!(line.contains(r#""session_id":"sess-1""#), "{line}");
        assert!(line.contains(r#""active_turn":false"#), "{line}");
    }

    #[test]
    fn ui_events_serialize_with_type_tag() {
        let events = vec![
            UiEvent::AgentTurnStarted,
            UiEvent::AgentThinking,
            UiEvent::AgentTextDelta("hi".into()),
            UiEvent::AgentMessageComplete("done".into()),
            UiEvent::AgentTurnComplete,
            UiEvent::InlineBashOutput {
                command: "ls".into(),
                output: "x".into(),
            },
            UiEvent::Notice {
                title: "note".into(),
                body: "body".into(),
            },
            UiEvent::SessionReplaced(Vec::new()),
            UiEvent::ModelSwitched(crate::model::ModelId::from("m")),
            UiEvent::ForkCandidates(vec![("e1".into(), "first".into())]),
            UiEvent::Error("bad".into()),
            UiEvent::ToolCallStarted {
                id: "t1".into(),
                name: "bash".into(),
                args: serde_json::json!("ls"),
            },
            UiEvent::ToolCallProgress {
                id: "t1".into(),
                chunk: ProgressChunk::Status("running".into()),
            },
            UiEvent::ToolCallCompleted {
                id: "t1".into(),
                result: UiToolResult {
                    is_error: false,
                    text: "ok".into(),
                },
            },
        ];
        for e in &events {
            let line = serde_json::to_string(e).expect("serialize");
            assert!(line.contains("\"type\":"), "missing type tag: {line}");
        }
    }

    #[test]
    fn permission_requested_serializes_without_the_resolver() {
        let (resolver, _rx) = tokio::sync::oneshot::channel::<crate::permissions::Decision>();
        let e = UiEvent::PermissionRequested {
            tool: "bash".into(),
            args: serde_json::json!({"command": "echo hi"}),
            resolver,
        };
        let line = serde_json::to_string(&e).expect("serialize");
        assert!(line.contains(r#""type":"permission_requested""#), "{line}");
        assert!(!line.contains("resolver"), "resolver leaked: {line}");
    }

    #[test]
    fn branch_tree_event_serializes_via_mapping() {
        let tree = motosan_agent_loop::BranchTree {
            nodes: vec![motosan_agent_loop::BranchNode {
                id: "n0".into(),
                parent: None,
                children: vec![],
                label: "root".into(),
            }],
            root: Some(0),
            active_leaf: Some(0),
        };
        let line = serde_json::to_string(&UiEvent::BranchTree(tree)).expect("serialize");
        assert!(line.contains(r#""type":"branch_tree""#), "{line}");
        assert!(line.contains(r#""label":"root""#), "{line}");
    }

    #[test]
    fn command_list_extensions_serde_round_trip() {
        let cmd = Command::ListExtensions;
        let line = serde_json::to_string(&cmd).expect("serialize");
        assert_eq!(line, r#"{"type":"list_extensions"}"#);
        let back: Command = serde_json::from_str(&line).expect("deserialize");
        assert_eq!(back, cmd);
    }

    #[test]
    fn ui_event_extension_list_serializes() {
        let ev = UiEvent::ExtensionList {
            extensions: vec![ExtensionInfo {
                name: "dirty".into(),
                hooks: vec!["session_before_switch".into()],
                commands: Vec::new(),
                healthy: true,
                diagnostic: None,
            }],
        };
        let line = serde_json::to_string(&ev).expect("serialize");
        assert!(line.contains(r#""type":"extension_list""#));
        assert!(line.contains(r#""name":"dirty""#));
    }
}