ertangle-protocol 1.8.0

Wire protocol between the ertangle daemon, TUI and CLI
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
855
856
857
858
859
860
861
862
863
864
//! `ertangle-protocol` — daemon <-> client control interface.
//!
//! Transport: Unix domain socket, **newline-delimited JSON** (one message per line).
//! Semantics: client sends [`Request`], daemon replies with [`Frame`] (including event streams and snapshots).
//!
//! This crate contains only wire types and codecs, with no I/O, making it easy to swap in TCP / JSON-RPC later.

pub use ertangle_core::{ActiveTool, BgProc};
use ertangle_core::{
    AgentKind, ArtifactKind, Attachment, BusMessage, Decision, MsgId, MsgKind, PermissionPolicy,
    Record, Role, Seq, SessionId, State, Target, TaskId, TaskStatus, WorktreeInfo,
};
use serde::{Deserialize, Serialize};

fn default_true() -> bool {
    true
}

fn default_wait_timeout() -> u64 {
    30_000
}

/// Transport mode used by a session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum Transport {
    /// Use native structured protocol if available (ACP / stream-json / app-server), otherwise fall back to PTY.
    #[default]
    Auto,
    /// Force native structured protocol.
    #[serde(alias = "acp")]
    Structured,
    /// Force PTY passthrough (works for any CLI agent).
    Pty,
}

/// Parent session change during handoff.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParentChange {
    Keep,
    None,
    Session(SessionId),
}

/// Request to spawn a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpawnRequest {
    /// `None` = decided by daemon from role / parent session / defaults (see `Config::resolve_kind`).
    #[serde(default)]
    pub kind: Option<AgentKind>,
    /// Working directory; `None` = daemon default (usually the daemon's cwd).
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub role: Option<Role>,
    /// Initial prompt sent immediately after startup.
    #[serde(default)]
    pub prompt: Option<String>,
    /// Whether to create and work inside a git worktree.
    #[serde(default)]
    pub worktree: bool,
    #[serde(default)]
    pub transport: Transport,
    /// Unified permission policy.
    #[serde(default)]
    pub permission: Option<PermissionPolicy>,
    /// Spawning parent session (`None` if spawned by a human).
    #[serde(default)]
    pub parent: Option<SessionId>,
    /// Explicit model; falls back to `config.toml` if omitted.
    #[serde(default)]
    pub model: Option<String>,
    /// Reasoning effort (low / medium / high / xhigh / max); falls back to `config.toml` if omitted.
    #[serde(default)]
    pub effort: Option<String>,
    /// Attachments for the initial prompt.
    #[serde(default)]
    pub attachments: Vec<Attachment>,
    /// Reuse that session's working directory, branch, and repo (for handoff, without creating a new worktree).
    #[serde(default)]
    pub inherit_from: Option<SessionId>,
    /// One-off extra CLI arguments (appended after configured args).
    #[serde(default)]
    pub args: Vec<String>,
    /// Per-session cost limit in USD; falls back to `config.toml` if omitted.
    #[serde(default)]
    pub budget_usd: Option<f64>,
}

/// Strategy used when merging a worktree branch back into the main branch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum MergeStrategy {
    /// Standard merge preserving branch commit history (default).
    #[default]
    Merge,
    /// Squash all changes into a single commit on the main branch.
    Squash,
    /// Rebase the branch onto the main branch, then fast-forward main.
    Rebase,
}

impl std::fmt::Display for MergeStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Self::Merge => "merge",
            Self::Squash => "squash",
            Self::Rebase => "rebase",
        };
        f.write_str(name)
    }
}

impl std::str::FromStr for MergeStrategy {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "merge" => Ok(Self::Merge),
            "squash" => Ok(Self::Squash),
            "rebase" => Ok(Self::Rebase),
            _ => Err(format!("unknown merge strategy: {s} (merge/squash/rebase)")),
        }
    }
}

/// client -> daemon.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Request {
    /// Greet and (optionally) replay events after `since`; remote connections may include `token`.
    Hello {
        client: String,
        #[serde(default)]
        since: Option<Seq>,
        #[serde(default)]
        token: Option<String>,
        /// Daemon epoch reported on the client's previous connection; if mismatched, daemon ignores `since` and sends a full snapshot.
        #[serde(default)]
        epoch: Option<String>,
    },
    /// Request a full state snapshot.
    Snapshot,
    Spawn(SpawnRequest),
    /// Send a prompt / user input to a session.
    Prompt {
        session: SessionId,
        text: String,
        /// Attachments (files, images).
        #[serde(default)]
        attachments: Vec<Attachment>,
        /// If `true`: enqueue when the session is busy or the queue is non-empty, and send sequentially when idle.
        #[serde(default)]
        queue: bool,
    },
    /// Execute a shell command in the session's working directory (bypassing the agent), writing output to the transcript.
    Exec {
        session: SessionId,
        command: String,
    },
    /// Clear a session's pending prompt queue.
    QueueClear {
        session: SessionId,
    },
    /// Pop (remove) the last entry from a session's pending prompt queue, returning its raw text via `Frame::Ok { note }`.
    QueuePop {
        session: SessionId,
    },
    /// Interrupt the current turn (without killing the process).
    Cancel {
        session: SessionId,
    },
    /// Remove an ended session from the list; for worktree branches behaves like gc (unmerged or uncommitted changes require `force`).
    SessionRemove {
        session: SessionId,
        #[serde(default)]
        force: bool,
    },
    /// Hand off a session's work to another agent: generates a handoff brief and reuses the same working directory.
    Handoff {
        session: SessionId,
        kind: AgentKind,
        #[serde(default)]
        model: Option<String>,
        #[serde(default)]
        effort: Option<String>,
        /// Extra instructions for the incoming agent.
        #[serde(default)]
        note: Option<String>,
        #[serde(default)]
        role: Option<Role>,
        #[serde(default)]
        parent: Option<ParentChange>,
        #[serde(default)]
        force: bool,
    },
    /// End the session and kill its process.
    Kill {
        session: SessionId,
    },
    /// Terminate background child processes of a session (`pid: None` cleans up all).
    KillBgProc {
        session: SessionId,
        #[serde(default)]
        pid: Option<u32>,
        #[serde(default)]
        force: bool,
    },
    /// Resume an ended session: reconnect to the original conversation using the agent's native conversation id (keeping the ertangle session id).
    Resume {
        session: SessionId,
        /// Prompt sent immediately after resuming succeeds.
        #[serde(default)]
        prompt: Option<String>,
    },
    /// Reset context while keeping identity: kill the agent process and restart with a fresh conversation
    /// (preserving ertangle session id, label, parent/child links, worktree, inbox, and tasks). Rejected while busy unless `force` interrupts first.
    Clear {
        session: SessionId,
        #[serde(default)]
        force: bool,
    },
    /// Pause an idle session's child process (SIGSTOP).
    Sleep {
        session: SessionId,
    },
    /// Wake a sleeping session's child process (SIGCONT).
    Wake {
        session: SessionId,
    },
    /// Switch a session's model and/or effort at runtime (takes effect on the next turn).
    SessionConfig {
        session: SessionId,
        #[serde(default)]
        model: Option<String>,
        #[serde(default)]
        effort: Option<String>,
    },
    /// Set or raise a session's cost limit (USD) and clear `over_budget`.
    SessionBudget {
        session: SessionId,
        budget_usd: f64,
    },
    /// Agent (via MCP `ertangle_approve`) requests approval and waits for the decision.
    McpPermission {
        session: SessionId,
        #[serde(alias = "tool")]
        title: String,
        #[serde(alias = "input")]
        detail: String,
    },
    /// Agent (via MCP `ertangle_approve`) requests approval and waits for the decision; `Ok` note is `allow` or `deny`.
    ApprovalAsk {
        session: SessionId,
        tool: String,
        /// Tool input (JSON string).
        input: String,
    },
    /// Reply to an approval request.
    Permission {
        session: SessionId,
        req: String,
        decision: Decision,
    },
    /// Agent asks a question through MCP `ertangle_question` and waits for the user's answer.
    McpQuestion {
        session: SessionId,
        question: String,
        #[serde(default)]
        header: Option<String>,
        #[serde(default)]
        options: Vec<String>,
        #[serde(default)]
        multi_select: bool,
    },
    /// Reply to an interactive question.
    AnswerQuestion {
        session: SessionId,
        id: String,
        #[serde(default)]
        answers: Vec<String>,
    },
    /// Send a message onto the bus (inter-agent communication).
    BusSend {
        #[serde(default)]
        from: Option<SessionId>,
        to: Target,
        #[serde(default)]
        kind: MsgKind,
        body: String,
        #[serde(default)]
        reply_to: Option<MsgId>,
    },
    /// Read a session's inbox (by default unread only, advancing the cursor).
    BusInbox {
        session: SessionId,
        #[serde(default = "default_true")]
        unread_only: bool,
    },
    /// Block waiting for the next message in the inbox (optionally filtered by sender or `reply_to`).
    BusWait {
        session: SessionId,
        #[serde(default)]
        from: Option<SessionId>,
        #[serde(default)]
        reply_to: Option<MsgId>,
        #[serde(default = "default_wait_timeout")]
        timeout_ms: u64,
    },
    TaskCreate {
        title: String,
        #[serde(default)]
        detail: String,
        #[serde(default)]
        assignee: Option<SessionId>,
        #[serde(default)]
        created_by: Option<SessionId>,
        #[serde(default)]
        depends_on: Vec<TaskId>,
        #[serde(default)]
        project_root: Option<String>,
    },
    TaskUpdate {
        id: TaskId,
        #[serde(default)]
        status: Option<TaskStatus>,
        #[serde(default)]
        assignee: Option<SessionId>,
        #[serde(default)]
        detail: Option<String>,
    },
    TaskDelete {
        id: TaskId,
    },
    /// Rename a session's display `label`.
    SessionLabel {
        session: SessionId,
        label: String,
    },
    /// Update a session's short status string (corresponds to `ertangle_status`).
    SessionNote {
        session: SessionId,
        note: String,
    },
    /// Share an artifact (file, branch, or diff).
    ArtifactShare {
        session: SessionId,
        #[serde(default)]
        kind: ArtifactKind,
        path: String,
        #[serde(default)]
        note: String,
    },
    /// List all managed worktrees.
    WorktreeList,
    /// Get `git diff` of a session's workspace (including untracked file summary).
    WorktreeDiff {
        session: SessionId,
        /// Return only changed file paths and line counts (`+N -M`), without unified diff hunks.
        #[serde(default)]
        stat_only: bool,
        /// Inspect only files matching the specified relative paths or prefixes.
        #[serde(default)]
        paths: Vec<String>,
        /// Maximum number of diff lines to return (truncates with an omission notice if exceeded).
        #[serde(default)]
        max_lines: Option<usize>,
        /// Automatically fold large lockfiles / generated files (`package-lock.json`, `*.Designer.cs`, etc.) into a single-line summary.
        #[serde(default)]
        fold_generated: bool,
    },
    /// Revert (discard) a single hunk or entire file change in a session's workspace.
    WorktreeDiscard {
        session: SessionId,
        file: String,
        #[serde(default)]
        patch: Option<String>,
    },
    /// Merge a session's worktree branch back into the main workspace.
    WorktreeMerge {
        session: SessionId,
        #[serde(default)]
        dry_run: bool,
        #[serde(default)]
        resolve: bool,
        /// Merge strategy; falls back to daemon's global `[git] merge_strategy` (default `merge`) if omitted.
        #[serde(default)]
        strategy: Option<MergeStrategy>,
    },
    /// Create a Pull Request for a session's branch (via `gh`).
    WorktreePr {
        session: SessionId,
        title: String,
        #[serde(default)]
        body: String,
    },
    /// Clean up worktrees of ended sessions (or the specified `session` if given).
    WorktreeGc {
        #[serde(default)]
        session: Option<SessionId>,
        /// Also remove worktrees with unmerged or uncommitted changes.
        #[serde(default)]
        force: bool,
    },
    /// Archive every ended session that is merged or has no worktree, removing merged
    /// worktrees safely. Live sessions and unmerged work are never touched.
    Prune {
        /// Restrict to sessions of this project root (absolute path); `None` = all.
        #[serde(default)]
        project: Option<String>,
    },
    /// Leave a review comment on a session's diff line and send it back to the agent to fix.
    ReviewComment {
        session: SessionId,
        location: String,
        comment: String,
    },
    /// Control or query Web UI support.
    WebControl {
        #[serde(default)]
        enabled: Option<bool>,
        #[serde(default)]
        addr: Option<String>,
    },
    /// Toggle OS-level keep-awake at runtime (applied immediately by TUI settings).
    KeepAwake {
        enabled: bool,
    },
    /// List available models for an agent (built-in for Claude; queried from CLI for others, up to a few seconds).
    ListModels {
        /// Agent kind (`claude`, `codex`, `opencode`, `antigravity`).
        kind: String,
    },
    /// Request the daemon to shut down.
    Shutdown,
    /// Request the daemon to restart with the same binary (re-exec); running sessions resume automatically.
    Restart,
}

/// daemon -> client.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "ev", rename_all = "snake_case")]
pub enum Frame {
    /// Connection established.
    Ready {
        pid: u32,
        version: String,
        /// Daemon startup generation id; clients discard local state if the log was replaced or deleted.
        #[serde(default)]
        epoch: String,
    },
    /// Full state (on initial connection or when Snapshot is requested).
    Snapshot {
        state: Box<State>,
    },
    /// Single event.
    Record {
        record: Box<Record>,
    },
    /// Inbox or wait result.
    Messages {
        messages: Vec<BusMessage>,
        #[serde(default)]
        timed_out: bool,
    },
    /// `git diff` of a session's workspace.
    Diff {
        session: SessionId,
        #[serde(default)]
        branch: Option<String>,
        cwd: String,
        diff: String,
    },
    /// List of all managed worktrees.
    Worktrees {
        worktrees: Vec<WorktreeInfo>,
    },
    /// Approval decision reply (for MCP `ertangle_approve` or client).
    PermissionDecision {
        decision: Decision,
    },
    /// Interactive question answer (for MCP `ertangle_question` or a client).
    QuestionAnswer {
        answers: Vec<String>,
    },
    /// Operation succeeded (with optional note).
    Ok {
        #[serde(default)]
        note: Option<String>,
    },
    Error {
        message: String,
    },
    /// Reply to `ListModels`: empty `id` means "use config default".
    Models {
        kind: String,
        models: Vec<ModelInfo>,
        /// Problem encountered while querying CLI (e.g., not logged in); list may be incomplete when set.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        problem: Option<String>,
    },
}

/// An available model option.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelInfo {
    pub id: String,
    pub label: String,
}

impl Frame {
    pub fn ok() -> Self {
        Frame::Ok { note: None }
    }
    pub fn ok_note(note: impl Into<String>) -> Self {
        Frame::Ok {
            note: Some(note.into()),
        }
    }
    pub fn error(message: impl Into<String>) -> Self {
        Frame::Error {
            message: message.into(),
        }
    }
}

/// Encode a message as a single JSON line (with trailing `\n`).
pub fn encode_line<T: Serialize>(value: &T) -> std::io::Result<String> {
    let mut s = serde_json::to_string(value)?;
    s.push('\n');
    Ok(s)
}

/// Decode a single JSON line.
pub fn decode_line<T: for<'de> Deserialize<'de>>(line: &str) -> serde_json::Result<T> {
    serde_json::from_str(line)
}

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

    #[test]
    fn restart_request_serde_roundtrip() {
        let json = serde_json::to_string(&Request::Restart).unwrap();
        assert_eq!(json, r#"{"op":"restart"}"#);
        assert!(matches!(
            serde_json::from_str::<Request>(&json).unwrap(),
            Request::Restart
        ));
    }

    #[test]
    fn clear_request_serde_defaults_force_false() {
        let req: Request = serde_json::from_str(r#"{"op":"clear","session":"ses_1"}"#).unwrap();
        assert!(matches!(
            req,
            Request::Clear { ref session, force: false } if session == "ses_1"
        ));
    }

    #[test]
    fn exec_request_serde_roundtrip() {
        let line = encode_line(&Request::Exec {
            session: "ses_1".into(),
            command: "echo \"hello world\"".into(),
        })
        .unwrap();
        assert_eq!(
            line.trim(),
            r#"{"op":"exec","session":"ses_1","command":"echo \"hello world\""}"#
        );
        let back: Request = decode_line(line.trim()).unwrap();
        let Request::Exec { session, command } = back else {
            panic!("expected Exec")
        };
        assert_eq!(session, "ses_1");
        assert_eq!(command, "echo \"hello world\"");
    }

    #[test]
    fn merge_strategy_parses_and_request_defaults_to_none() {
        assert_eq!(
            "merge".parse::<MergeStrategy>().unwrap(),
            MergeStrategy::Merge
        );
        assert_eq!(
            "SQUASH".parse::<MergeStrategy>().unwrap(),
            MergeStrategy::Squash
        );
        assert_eq!(
            "rebase".parse::<MergeStrategy>().unwrap(),
            MergeStrategy::Rebase
        );
        assert!("bogus".parse::<MergeStrategy>().is_err());
        assert_eq!(MergeStrategy::default(), MergeStrategy::Merge);
        assert_eq!(MergeStrategy::Squash.to_string(), "squash");

        let line = encode_line(&Request::WorktreeMerge {
            session: "s1".into(),
            dry_run: false,
            resolve: false,
            strategy: Some(MergeStrategy::Rebase),
        })
        .unwrap();
        let back: Request = decode_line(line.trim()).unwrap();
        let Request::WorktreeMerge { strategy, .. } = back else {
            panic!("expected WorktreeMerge")
        };
        assert_eq!(strategy, Some(MergeStrategy::Rebase));

        let legacy = r#"{"op":"worktree_merge","session":"s1"}"#;
        let back: Request = decode_line(legacy).unwrap();
        let Request::WorktreeMerge { strategy, .. } = back else {
            panic!("expected WorktreeMerge")
        };
        assert_eq!(strategy, None);
    }

    #[test]
    fn keep_awake_request_serde_roundtrip() {
        let line = encode_line(&Request::KeepAwake { enabled: true }).unwrap();
        assert_eq!(line.trim(), r#"{"op":"keep_awake","enabled":true}"#);
        let back: Request = decode_line(line.trim()).unwrap();
        let Request::KeepAwake { enabled } = back else {
            panic!("expected KeepAwake")
        };
        assert!(enabled);
    }

    #[test]
    fn request_roundtrip() {
        let req = Request::Spawn(SpawnRequest {
            kind: Some(AgentKind::OpenCode),
            cwd: Some("/tmp".into()),
            label: Some("worker".into()),
            role: Some(Role::Worker),
            prompt: Some("hi".into()),
            worktree: false,
            transport: Transport::Auto,
            permission: None,
            parent: None,
            model: None,
            effort: None,
            attachments: vec![],
            inherit_from: None,
            args: vec![],
            budget_usd: None,
        });
        let line = encode_line(&req).unwrap();
        assert!(line.ends_with('\n'));
        let back: Request = decode_line(line.trim()).unwrap();
        match back {
            Request::Spawn(s) => assert_eq!(s.kind, Some(AgentKind::OpenCode)),
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn frame_tag_is_ev() {
        let f = Frame::ok_note("done");
        let v: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();
        assert_eq!(v["ev"], "ok");
    }

    #[test]
    fn transport_accepts_acp_alias() {
        let t: Transport = serde_json::from_str("\"acp\"").unwrap();
        assert_eq!(t, Transport::Structured);
        let t: Transport = serde_json::from_str("\"structured\"").unwrap();
        assert_eq!(t, Transport::Structured);
        assert_eq!(
            serde_json::to_string(&Transport::Structured).unwrap(),
            "\"structured\""
        );
    }

    #[test]
    fn old_spawn_json_without_model_still_parses() {
        let req: Request = serde_json::from_str(r#"{"op":"spawn","kind":"claude_code"}"#).unwrap();
        let Request::Spawn(s) = req else { panic!() };
        assert!(
            s.model.is_none() && s.args.is_empty() && s.budget_usd.is_none() && s.role.is_none()
        );
    }

    #[test]
    fn handoff_json_roundtrip_and_defaults() {
        let req: Request =
            serde_json::from_str(r#"{"op":"handoff","session":"s1","kind":"claude_code"}"#)
                .unwrap();
        let Request::Handoff {
            session,
            role,
            parent,
            force,
            ..
        } = req
        else {
            panic!()
        };
        assert_eq!(session, "s1");
        assert!(role.is_none());
        assert!(parent.is_none());
        assert!(!force);

        let req_with_fields = Request::Handoff {
            session: "s1".into(),
            kind: AgentKind::ClaudeCode,
            model: Some("opus".into()),
            effort: None,
            note: None,
            role: Some(Role::Coordinator),
            parent: Some(ParentChange::None),
            force: true,
        };
        let line = encode_line(&req_with_fields).unwrap();
        let back: Request = decode_line(line.trim()).unwrap();
        let Request::Handoff {
            role,
            parent,
            force,
            ..
        } = back
        else {
            panic!()
        };
        assert_eq!(role, Some(Role::Coordinator));
        assert_eq!(parent, Some(ParentChange::None));
        assert!(force);
    }

    #[test]
    fn web_answer_question_wire_shape() {
        let req: Request = decode_line(
            r#"{"op":"answer_question","session":"ses_1","id":"qst_1","answers":["Option A"]}"#,
        )
        .unwrap();
        let Request::AnswerQuestion {
            session,
            id,
            answers,
        } = req
        else {
            panic!("expected AnswerQuestion")
        };
        assert_eq!(session, "ses_1");
        assert_eq!(id, "qst_1");
        assert_eq!(answers, vec!["Option A"]);
    }

    #[test]
    fn question_protocol_roundtrip() {
        let req = Request::AnswerQuestion {
            session: "ses_1".into(),
            id: "qst_1".into(),
            answers: vec!["Option A".into(), "Option B".into()],
        };
        let line = encode_line(&req).unwrap();
        let back: Request = decode_line(line.trim()).unwrap();
        let Request::AnswerQuestion {
            session,
            id,
            answers,
        } = back
        else {
            panic!()
        };
        assert_eq!(session, "ses_1");
        assert_eq!(id, "qst_1");
        assert_eq!(answers, vec!["Option A", "Option B"]);

        let frame = Frame::QuestionAnswer {
            answers: vec!["Accepted".into()],
        };
        let f_line = encode_line(&frame).unwrap();
        let f_back: Frame = decode_line(f_line.trim()).unwrap();
        let Frame::QuestionAnswer { answers: f_ans } = f_back else {
            panic!()
        };
        assert_eq!(f_ans, vec!["Accepted"]);
    }

    #[test]
    fn web_spawn_handoff_permission_and_task_wire_shapes() {
        // Web UI sends kind: "claude", optional null prompt/role, and PascalCase/alias enum strings.
        let req: Request = decode_line(
            r#"{"op":"spawn","cwd":null,"kind":"claude","label":null,"model":null,"effort":null,"permission":"auto","budget_usd":null,"worktree":false,"prompt":null,"role":null,"transport":"auto"}"#,
        )
        .unwrap();
        let Request::Spawn(sp) = req else {
            panic!("expected Spawn")
        };
        assert_eq!(sp.kind, Some(AgentKind::ClaudeCode));
        assert!(sp.prompt.is_none());
        assert!(sp.role.is_none());

        let req_oc: Request = decode_line(
            r#"{"op":"spawn","cwd":null,"kind":"opencode","label":null,"model":null,"effort":null,"permission":"auto","budget_usd":null,"worktree":false,"prompt":null,"role":null,"transport":"auto"}"#,
        )
        .unwrap();
        let Request::Spawn(sp_oc) = req_oc else {
            panic!("expected Spawn")
        };
        assert_eq!(sp_oc.kind, Some(AgentKind::OpenCode));

        let req_open_code: Request = decode_line(
            r#"{"op":"spawn","cwd":null,"kind":"open_code","label":null,"model":null,"effort":null,"permission":"auto","budget_usd":null,"worktree":false,"prompt":null,"role":null,"transport":"auto"}"#,
        )
        .unwrap();
        let Request::Spawn(sp_open_code) = req_open_code else {
            panic!("expected Spawn")
        };
        assert_eq!(sp_open_code.kind, Some(AgentKind::OpenCode));

        let handoff: Request =
            decode_line(r#"{"op":"handoff","session":"ses_1","kind":"claude","note":null}"#)
                .unwrap();
        let Request::Handoff { kind, .. } = handoff else {
            panic!("expected Handoff")
        };
        assert_eq!(kind, AgentKind::ClaudeCode);

        for (raw, expected) in [
            ("allow", Decision::Allow),
            ("Allow", Decision::Allow),
            ("allow_always", Decision::AllowAlways),
            ("Always", Decision::AllowAlways),
            ("deny", Decision::Deny),
            ("Deny", Decision::Deny),
        ] {
            let perm: Request = decode_line(&format!(
                r#"{{"op":"permission","session":"ses_1","req":"perm_1","decision":"{raw}"}}"#
            ))
            .unwrap();
            let Request::Permission { decision, .. } = perm else {
                panic!("expected Permission")
            };
            assert_eq!(decision, expected);
        }

        for (raw, expected) in [
            ("todo", TaskStatus::Todo),
            ("Todo", TaskStatus::Todo),
            ("doing", TaskStatus::Doing),
            ("Doing", TaskStatus::Doing),
            ("done", TaskStatus::Done),
            ("Done", TaskStatus::Done),
        ] {
            let tu: Request = decode_line(&format!(
                r#"{{"op":"task_update","id":"task_1","status":"{raw}"}}"#
            ))
            .unwrap();
            let Request::TaskUpdate { status, .. } = tu else {
                panic!("expected TaskUpdate")
            };
            assert_eq!(status, Some(expected));
        }
    }
}