Skip to main content

ertangle_protocol/
lib.rs

1//! `ertangle-protocol` — daemon <-> client control interface.
2//!
3//! Transport: Unix domain socket, **newline-delimited JSON** (one message per line).
4//! Semantics: client sends [`Request`], daemon replies with [`Frame`] (including event streams and snapshots).
5//!
6//! This crate contains only wire types and codecs, with no I/O, making it easy to swap in TCP / JSON-RPC later.
7
8pub use ertangle_core::{ActiveTool, BgProc};
9use ertangle_core::{
10    AgentKind, ArtifactKind, Attachment, BusMessage, Decision, MsgId, MsgKind, PermissionPolicy,
11    Record, Role, Seq, SessionId, State, Target, TaskId, TaskStatus, WorktreeInfo,
12};
13use serde::{Deserialize, Serialize};
14
15fn default_true() -> bool {
16    true
17}
18
19fn default_wait_timeout() -> u64 {
20    30_000
21}
22
23/// Transport mode used by a session.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
25#[serde(rename_all = "snake_case")]
26pub enum Transport {
27    /// Use native structured protocol if available (ACP / stream-json / app-server), otherwise fall back to PTY.
28    #[default]
29    Auto,
30    /// Force native structured protocol.
31    #[serde(alias = "acp")]
32    Structured,
33    /// Force PTY passthrough (works for any CLI agent).
34    Pty,
35}
36
37/// Parent session change during handoff.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum ParentChange {
41    Keep,
42    None,
43    Session(SessionId),
44}
45
46/// Request to spawn a session.
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct SpawnRequest {
49    /// `None` = decided by daemon from role / parent session / defaults (see `Config::resolve_kind`).
50    #[serde(default)]
51    pub kind: Option<AgentKind>,
52    /// Working directory; `None` = daemon default (usually the daemon's cwd).
53    #[serde(default)]
54    pub cwd: Option<String>,
55    #[serde(default)]
56    pub label: Option<String>,
57    #[serde(default)]
58    pub role: Option<Role>,
59    /// Initial prompt sent immediately after startup.
60    #[serde(default)]
61    pub prompt: Option<String>,
62    /// Whether to create and work inside a git worktree.
63    #[serde(default)]
64    pub worktree: bool,
65    #[serde(default)]
66    pub transport: Transport,
67    /// Unified permission policy.
68    #[serde(default)]
69    pub permission: Option<PermissionPolicy>,
70    /// Spawning parent session (`None` if spawned by a human).
71    #[serde(default)]
72    pub parent: Option<SessionId>,
73    /// Explicit model; falls back to `config.toml` if omitted.
74    #[serde(default)]
75    pub model: Option<String>,
76    /// Reasoning effort (low / medium / high / xhigh / max); falls back to `config.toml` if omitted.
77    #[serde(default)]
78    pub effort: Option<String>,
79    /// Attachments for the initial prompt.
80    #[serde(default)]
81    pub attachments: Vec<Attachment>,
82    /// Reuse that session's working directory, branch, and repo (for handoff, without creating a new worktree).
83    #[serde(default)]
84    pub inherit_from: Option<SessionId>,
85    /// One-off extra CLI arguments (appended after configured args).
86    #[serde(default)]
87    pub args: Vec<String>,
88    /// Per-session cost limit in USD; falls back to `config.toml` if omitted.
89    #[serde(default)]
90    pub budget_usd: Option<f64>,
91}
92
93/// Strategy used when merging a worktree branch back into the main branch.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
95#[serde(rename_all = "snake_case")]
96pub enum MergeStrategy {
97    /// Standard merge preserving branch commit history (default).
98    #[default]
99    Merge,
100    /// Squash all changes into a single commit on the main branch.
101    Squash,
102    /// Rebase the branch onto the main branch, then fast-forward main.
103    Rebase,
104}
105
106impl std::fmt::Display for MergeStrategy {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        let name = match self {
109            Self::Merge => "merge",
110            Self::Squash => "squash",
111            Self::Rebase => "rebase",
112        };
113        f.write_str(name)
114    }
115}
116
117impl std::str::FromStr for MergeStrategy {
118    type Err = String;
119
120    fn from_str(s: &str) -> Result<Self, Self::Err> {
121        match s.trim().to_ascii_lowercase().as_str() {
122            "merge" => Ok(Self::Merge),
123            "squash" => Ok(Self::Squash),
124            "rebase" => Ok(Self::Rebase),
125            _ => Err(format!("unknown merge strategy: {s} (merge/squash/rebase)")),
126        }
127    }
128}
129
130/// client -> daemon.
131#[derive(Debug, Clone, Serialize, Deserialize)]
132#[serde(tag = "op", rename_all = "snake_case")]
133pub enum Request {
134    /// Greet and (optionally) replay events after `since`; remote connections may include `token`.
135    Hello {
136        client: String,
137        #[serde(default)]
138        since: Option<Seq>,
139        #[serde(default)]
140        token: Option<String>,
141        /// Daemon epoch reported on the client's previous connection; if mismatched, daemon ignores `since` and sends a full snapshot.
142        #[serde(default)]
143        epoch: Option<String>,
144    },
145    /// Request a full state snapshot.
146    Snapshot,
147    Spawn(SpawnRequest),
148    /// Send a prompt / user input to a session.
149    Prompt {
150        session: SessionId,
151        text: String,
152        /// Attachments (files, images).
153        #[serde(default)]
154        attachments: Vec<Attachment>,
155        /// If `true`: enqueue when the session is busy or the queue is non-empty, and send sequentially when idle.
156        #[serde(default)]
157        queue: bool,
158    },
159    /// Execute a shell command in the session's working directory (bypassing the agent), writing output to the transcript.
160    Exec {
161        session: SessionId,
162        command: String,
163    },
164    /// Clear a session's pending prompt queue.
165    QueueClear {
166        session: SessionId,
167    },
168    /// Pop (remove) the last entry from a session's pending prompt queue, returning its raw text via `Frame::Ok { note }`.
169    QueuePop {
170        session: SessionId,
171    },
172    /// Interrupt the current turn (without killing the process).
173    Cancel {
174        session: SessionId,
175    },
176    /// Remove an ended session from the list; for worktree branches behaves like gc (unmerged or uncommitted changes require `force`).
177    SessionRemove {
178        session: SessionId,
179        #[serde(default)]
180        force: bool,
181    },
182    /// Hand off a session's work to another agent: generates a handoff brief and reuses the same working directory.
183    Handoff {
184        session: SessionId,
185        kind: AgentKind,
186        #[serde(default)]
187        model: Option<String>,
188        #[serde(default)]
189        effort: Option<String>,
190        /// Extra instructions for the incoming agent.
191        #[serde(default)]
192        note: Option<String>,
193        #[serde(default)]
194        role: Option<Role>,
195        #[serde(default)]
196        parent: Option<ParentChange>,
197        #[serde(default)]
198        force: bool,
199    },
200    /// End the session and kill its process.
201    Kill {
202        session: SessionId,
203    },
204    /// Terminate background child processes of a session (`pid: None` cleans up all).
205    KillBgProc {
206        session: SessionId,
207        #[serde(default)]
208        pid: Option<u32>,
209        #[serde(default)]
210        force: bool,
211    },
212    /// Resume an ended session: reconnect to the original conversation using the agent's native conversation id (keeping the ertangle session id).
213    Resume {
214        session: SessionId,
215        /// Prompt sent immediately after resuming succeeds.
216        #[serde(default)]
217        prompt: Option<String>,
218    },
219    /// Reset context while keeping identity: kill the agent process and restart with a fresh conversation
220    /// (preserving ertangle session id, label, parent/child links, worktree, inbox, and tasks). Rejected while busy unless `force` interrupts first.
221    Clear {
222        session: SessionId,
223        #[serde(default)]
224        force: bool,
225    },
226    /// Pause an idle session's child process (SIGSTOP).
227    Sleep {
228        session: SessionId,
229    },
230    /// Wake a sleeping session's child process (SIGCONT).
231    Wake {
232        session: SessionId,
233    },
234    /// Switch a session's model and/or effort at runtime (takes effect on the next turn).
235    SessionConfig {
236        session: SessionId,
237        #[serde(default)]
238        model: Option<String>,
239        #[serde(default)]
240        effort: Option<String>,
241    },
242    /// Set or raise a session's cost limit (USD) and clear `over_budget`.
243    SessionBudget {
244        session: SessionId,
245        budget_usd: f64,
246    },
247    /// Agent (via MCP `ertangle_approve`) requests approval and waits for the decision.
248    McpPermission {
249        session: SessionId,
250        #[serde(alias = "tool")]
251        title: String,
252        #[serde(alias = "input")]
253        detail: String,
254    },
255    /// Agent (via MCP `ertangle_approve`) requests approval and waits for the decision; `Ok` note is `allow` or `deny`.
256    ApprovalAsk {
257        session: SessionId,
258        tool: String,
259        /// Tool input (JSON string).
260        input: String,
261    },
262    /// Reply to an approval request.
263    Permission {
264        session: SessionId,
265        req: String,
266        decision: Decision,
267    },
268    /// Agent asks a question through MCP `ertangle_question` and waits for the user's answer.
269    McpQuestion {
270        session: SessionId,
271        question: String,
272        #[serde(default)]
273        header: Option<String>,
274        #[serde(default)]
275        options: Vec<String>,
276        #[serde(default)]
277        multi_select: bool,
278    },
279    /// Reply to an interactive question.
280    AnswerQuestion {
281        session: SessionId,
282        id: String,
283        #[serde(default)]
284        answers: Vec<String>,
285    },
286    /// Send a message onto the bus (inter-agent communication).
287    BusSend {
288        #[serde(default)]
289        from: Option<SessionId>,
290        to: Target,
291        #[serde(default)]
292        kind: MsgKind,
293        body: String,
294        #[serde(default)]
295        reply_to: Option<MsgId>,
296    },
297    /// Read a session's inbox (by default unread only, advancing the cursor).
298    BusInbox {
299        session: SessionId,
300        #[serde(default = "default_true")]
301        unread_only: bool,
302    },
303    /// Block waiting for the next message in the inbox (optionally filtered by sender or `reply_to`).
304    BusWait {
305        session: SessionId,
306        #[serde(default)]
307        from: Option<SessionId>,
308        #[serde(default)]
309        reply_to: Option<MsgId>,
310        #[serde(default = "default_wait_timeout")]
311        timeout_ms: u64,
312    },
313    TaskCreate {
314        title: String,
315        #[serde(default)]
316        detail: String,
317        #[serde(default)]
318        assignee: Option<SessionId>,
319        #[serde(default)]
320        created_by: Option<SessionId>,
321        #[serde(default)]
322        depends_on: Vec<TaskId>,
323        #[serde(default)]
324        project_root: Option<String>,
325    },
326    TaskUpdate {
327        id: TaskId,
328        #[serde(default)]
329        status: Option<TaskStatus>,
330        #[serde(default)]
331        assignee: Option<SessionId>,
332        #[serde(default)]
333        detail: Option<String>,
334    },
335    TaskDelete {
336        id: TaskId,
337    },
338    /// Rename a session's display `label`.
339    SessionLabel {
340        session: SessionId,
341        label: String,
342    },
343    /// Update a session's short status string (corresponds to `ertangle_status`).
344    SessionNote {
345        session: SessionId,
346        note: String,
347    },
348    /// Share an artifact (file, branch, or diff).
349    ArtifactShare {
350        session: SessionId,
351        #[serde(default)]
352        kind: ArtifactKind,
353        path: String,
354        #[serde(default)]
355        note: String,
356    },
357    /// List all managed worktrees.
358    WorktreeList,
359    /// Get `git diff` of a session's workspace (including untracked file summary).
360    WorktreeDiff {
361        session: SessionId,
362        /// Return only changed file paths and line counts (`+N -M`), without unified diff hunks.
363        #[serde(default)]
364        stat_only: bool,
365        /// Inspect only files matching the specified relative paths or prefixes.
366        #[serde(default)]
367        paths: Vec<String>,
368        /// Maximum number of diff lines to return (truncates with an omission notice if exceeded).
369        #[serde(default)]
370        max_lines: Option<usize>,
371        /// Automatically fold large lockfiles / generated files (`package-lock.json`, `*.Designer.cs`, etc.) into a single-line summary.
372        #[serde(default)]
373        fold_generated: bool,
374    },
375    /// Revert (discard) a single hunk or entire file change in a session's workspace.
376    WorktreeDiscard {
377        session: SessionId,
378        file: String,
379        #[serde(default)]
380        patch: Option<String>,
381    },
382    /// Merge a session's worktree branch back into the main workspace.
383    WorktreeMerge {
384        session: SessionId,
385        #[serde(default)]
386        dry_run: bool,
387        #[serde(default)]
388        resolve: bool,
389        /// Merge strategy; falls back to daemon's global `[git] merge_strategy` (default `merge`) if omitted.
390        #[serde(default)]
391        strategy: Option<MergeStrategy>,
392    },
393    /// Create a Pull Request for a session's branch (via `gh`).
394    WorktreePr {
395        session: SessionId,
396        title: String,
397        #[serde(default)]
398        body: String,
399    },
400    /// Clean up worktrees of ended sessions (or the specified `session` if given).
401    WorktreeGc {
402        #[serde(default)]
403        session: Option<SessionId>,
404        /// Also remove worktrees with unmerged or uncommitted changes.
405        #[serde(default)]
406        force: bool,
407    },
408    /// Archive every ended session that is merged or has no worktree, removing merged
409    /// worktrees safely. Live sessions and unmerged work are never touched.
410    Prune {
411        /// Restrict to sessions of this project root (absolute path); `None` = all.
412        #[serde(default)]
413        project: Option<String>,
414    },
415    /// Leave a review comment on a session's diff line and send it back to the agent to fix.
416    ReviewComment {
417        session: SessionId,
418        location: String,
419        comment: String,
420    },
421    /// Control or query Web UI support.
422    WebControl {
423        #[serde(default)]
424        enabled: Option<bool>,
425        #[serde(default)]
426        addr: Option<String>,
427    },
428    /// Toggle OS-level keep-awake at runtime (applied immediately by TUI settings).
429    KeepAwake {
430        enabled: bool,
431    },
432    /// List available models for an agent (built-in for Claude; queried from CLI for others, up to a few seconds).
433    ListModels {
434        /// Agent kind (`claude`, `codex`, `opencode`, `antigravity`).
435        kind: String,
436    },
437    /// Request the daemon to shut down.
438    Shutdown,
439    /// Request the daemon to restart with the same binary (re-exec); running sessions resume automatically.
440    Restart,
441}
442
443/// daemon -> client.
444#[derive(Debug, Clone, Serialize, Deserialize)]
445#[serde(tag = "ev", rename_all = "snake_case")]
446pub enum Frame {
447    /// Connection established.
448    Ready {
449        pid: u32,
450        version: String,
451        /// Daemon startup generation id; clients discard local state if the log was replaced or deleted.
452        #[serde(default)]
453        epoch: String,
454    },
455    /// Full state (on initial connection or when Snapshot is requested).
456    Snapshot {
457        state: Box<State>,
458    },
459    /// Single event.
460    Record {
461        record: Box<Record>,
462    },
463    /// Inbox or wait result.
464    Messages {
465        messages: Vec<BusMessage>,
466        #[serde(default)]
467        timed_out: bool,
468    },
469    /// `git diff` of a session's workspace.
470    Diff {
471        session: SessionId,
472        #[serde(default)]
473        branch: Option<String>,
474        cwd: String,
475        diff: String,
476    },
477    /// List of all managed worktrees.
478    Worktrees {
479        worktrees: Vec<WorktreeInfo>,
480    },
481    /// Approval decision reply (for MCP `ertangle_approve` or client).
482    PermissionDecision {
483        decision: Decision,
484    },
485    /// Interactive question answer (for MCP `ertangle_question` or a client).
486    QuestionAnswer {
487        answers: Vec<String>,
488    },
489    /// Operation succeeded (with optional note).
490    Ok {
491        #[serde(default)]
492        note: Option<String>,
493    },
494    Error {
495        message: String,
496    },
497    /// Reply to `ListModels`: empty `id` means "use config default".
498    Models {
499        kind: String,
500        models: Vec<ModelInfo>,
501        /// Problem encountered while querying CLI (e.g., not logged in); list may be incomplete when set.
502        #[serde(default, skip_serializing_if = "Option::is_none")]
503        problem: Option<String>,
504    },
505}
506
507/// An available model option.
508#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
509pub struct ModelInfo {
510    pub id: String,
511    pub label: String,
512}
513
514impl Frame {
515    pub fn ok() -> Self {
516        Frame::Ok { note: None }
517    }
518    pub fn ok_note(note: impl Into<String>) -> Self {
519        Frame::Ok {
520            note: Some(note.into()),
521        }
522    }
523    pub fn error(message: impl Into<String>) -> Self {
524        Frame::Error {
525            message: message.into(),
526        }
527    }
528}
529
530/// Encode a message as a single JSON line (with trailing `\n`).
531pub fn encode_line<T: Serialize>(value: &T) -> std::io::Result<String> {
532    let mut s = serde_json::to_string(value)?;
533    s.push('\n');
534    Ok(s)
535}
536
537/// Decode a single JSON line.
538pub fn decode_line<T: for<'de> Deserialize<'de>>(line: &str) -> serde_json::Result<T> {
539    serde_json::from_str(line)
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    #[test]
547    fn restart_request_serde_roundtrip() {
548        let json = serde_json::to_string(&Request::Restart).unwrap();
549        assert_eq!(json, r#"{"op":"restart"}"#);
550        assert!(matches!(
551            serde_json::from_str::<Request>(&json).unwrap(),
552            Request::Restart
553        ));
554    }
555
556    #[test]
557    fn clear_request_serde_defaults_force_false() {
558        let req: Request = serde_json::from_str(r#"{"op":"clear","session":"ses_1"}"#).unwrap();
559        assert!(matches!(
560            req,
561            Request::Clear { ref session, force: false } if session == "ses_1"
562        ));
563    }
564
565    #[test]
566    fn exec_request_serde_roundtrip() {
567        let line = encode_line(&Request::Exec {
568            session: "ses_1".into(),
569            command: "echo \"hello world\"".into(),
570        })
571        .unwrap();
572        assert_eq!(
573            line.trim(),
574            r#"{"op":"exec","session":"ses_1","command":"echo \"hello world\""}"#
575        );
576        let back: Request = decode_line(line.trim()).unwrap();
577        let Request::Exec { session, command } = back else {
578            panic!("expected Exec")
579        };
580        assert_eq!(session, "ses_1");
581        assert_eq!(command, "echo \"hello world\"");
582    }
583
584    #[test]
585    fn merge_strategy_parses_and_request_defaults_to_none() {
586        assert_eq!(
587            "merge".parse::<MergeStrategy>().unwrap(),
588            MergeStrategy::Merge
589        );
590        assert_eq!(
591            "SQUASH".parse::<MergeStrategy>().unwrap(),
592            MergeStrategy::Squash
593        );
594        assert_eq!(
595            "rebase".parse::<MergeStrategy>().unwrap(),
596            MergeStrategy::Rebase
597        );
598        assert!("bogus".parse::<MergeStrategy>().is_err());
599        assert_eq!(MergeStrategy::default(), MergeStrategy::Merge);
600        assert_eq!(MergeStrategy::Squash.to_string(), "squash");
601
602        let line = encode_line(&Request::WorktreeMerge {
603            session: "s1".into(),
604            dry_run: false,
605            resolve: false,
606            strategy: Some(MergeStrategy::Rebase),
607        })
608        .unwrap();
609        let back: Request = decode_line(line.trim()).unwrap();
610        let Request::WorktreeMerge { strategy, .. } = back else {
611            panic!("expected WorktreeMerge")
612        };
613        assert_eq!(strategy, Some(MergeStrategy::Rebase));
614
615        let legacy = r#"{"op":"worktree_merge","session":"s1"}"#;
616        let back: Request = decode_line(legacy).unwrap();
617        let Request::WorktreeMerge { strategy, .. } = back else {
618            panic!("expected WorktreeMerge")
619        };
620        assert_eq!(strategy, None);
621    }
622
623    #[test]
624    fn keep_awake_request_serde_roundtrip() {
625        let line = encode_line(&Request::KeepAwake { enabled: true }).unwrap();
626        assert_eq!(line.trim(), r#"{"op":"keep_awake","enabled":true}"#);
627        let back: Request = decode_line(line.trim()).unwrap();
628        let Request::KeepAwake { enabled } = back else {
629            panic!("expected KeepAwake")
630        };
631        assert!(enabled);
632    }
633
634    #[test]
635    fn request_roundtrip() {
636        let req = Request::Spawn(SpawnRequest {
637            kind: Some(AgentKind::OpenCode),
638            cwd: Some("/tmp".into()),
639            label: Some("worker".into()),
640            role: Some(Role::Worker),
641            prompt: Some("hi".into()),
642            worktree: false,
643            transport: Transport::Auto,
644            permission: None,
645            parent: None,
646            model: None,
647            effort: None,
648            attachments: vec![],
649            inherit_from: None,
650            args: vec![],
651            budget_usd: None,
652        });
653        let line = encode_line(&req).unwrap();
654        assert!(line.ends_with('\n'));
655        let back: Request = decode_line(line.trim()).unwrap();
656        match back {
657            Request::Spawn(s) => assert_eq!(s.kind, Some(AgentKind::OpenCode)),
658            _ => panic!("wrong variant"),
659        }
660    }
661
662    #[test]
663    fn frame_tag_is_ev() {
664        let f = Frame::ok_note("done");
665        let v: serde_json::Value =
666            serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();
667        assert_eq!(v["ev"], "ok");
668    }
669
670    #[test]
671    fn transport_accepts_acp_alias() {
672        let t: Transport = serde_json::from_str("\"acp\"").unwrap();
673        assert_eq!(t, Transport::Structured);
674        let t: Transport = serde_json::from_str("\"structured\"").unwrap();
675        assert_eq!(t, Transport::Structured);
676        assert_eq!(
677            serde_json::to_string(&Transport::Structured).unwrap(),
678            "\"structured\""
679        );
680    }
681
682    #[test]
683    fn old_spawn_json_without_model_still_parses() {
684        let req: Request = serde_json::from_str(r#"{"op":"spawn","kind":"claude_code"}"#).unwrap();
685        let Request::Spawn(s) = req else { panic!() };
686        assert!(
687            s.model.is_none() && s.args.is_empty() && s.budget_usd.is_none() && s.role.is_none()
688        );
689    }
690
691    #[test]
692    fn handoff_json_roundtrip_and_defaults() {
693        let req: Request =
694            serde_json::from_str(r#"{"op":"handoff","session":"s1","kind":"claude_code"}"#)
695                .unwrap();
696        let Request::Handoff {
697            session,
698            role,
699            parent,
700            force,
701            ..
702        } = req
703        else {
704            panic!()
705        };
706        assert_eq!(session, "s1");
707        assert!(role.is_none());
708        assert!(parent.is_none());
709        assert!(!force);
710
711        let req_with_fields = Request::Handoff {
712            session: "s1".into(),
713            kind: AgentKind::ClaudeCode,
714            model: Some("opus".into()),
715            effort: None,
716            note: None,
717            role: Some(Role::Coordinator),
718            parent: Some(ParentChange::None),
719            force: true,
720        };
721        let line = encode_line(&req_with_fields).unwrap();
722        let back: Request = decode_line(line.trim()).unwrap();
723        let Request::Handoff {
724            role,
725            parent,
726            force,
727            ..
728        } = back
729        else {
730            panic!()
731        };
732        assert_eq!(role, Some(Role::Coordinator));
733        assert_eq!(parent, Some(ParentChange::None));
734        assert!(force);
735    }
736
737    #[test]
738    fn web_answer_question_wire_shape() {
739        let req: Request = decode_line(
740            r#"{"op":"answer_question","session":"ses_1","id":"qst_1","answers":["Option A"]}"#,
741        )
742        .unwrap();
743        let Request::AnswerQuestion {
744            session,
745            id,
746            answers,
747        } = req
748        else {
749            panic!("expected AnswerQuestion")
750        };
751        assert_eq!(session, "ses_1");
752        assert_eq!(id, "qst_1");
753        assert_eq!(answers, vec!["Option A"]);
754    }
755
756    #[test]
757    fn question_protocol_roundtrip() {
758        let req = Request::AnswerQuestion {
759            session: "ses_1".into(),
760            id: "qst_1".into(),
761            answers: vec!["Option A".into(), "Option B".into()],
762        };
763        let line = encode_line(&req).unwrap();
764        let back: Request = decode_line(line.trim()).unwrap();
765        let Request::AnswerQuestion {
766            session,
767            id,
768            answers,
769        } = back
770        else {
771            panic!()
772        };
773        assert_eq!(session, "ses_1");
774        assert_eq!(id, "qst_1");
775        assert_eq!(answers, vec!["Option A", "Option B"]);
776
777        let frame = Frame::QuestionAnswer {
778            answers: vec!["Accepted".into()],
779        };
780        let f_line = encode_line(&frame).unwrap();
781        let f_back: Frame = decode_line(f_line.trim()).unwrap();
782        let Frame::QuestionAnswer { answers: f_ans } = f_back else {
783            panic!()
784        };
785        assert_eq!(f_ans, vec!["Accepted"]);
786    }
787
788    #[test]
789    fn web_spawn_handoff_permission_and_task_wire_shapes() {
790        // Web UI sends kind: "claude", optional null prompt/role, and PascalCase/alias enum strings.
791        let req: Request = decode_line(
792            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"}"#,
793        )
794        .unwrap();
795        let Request::Spawn(sp) = req else {
796            panic!("expected Spawn")
797        };
798        assert_eq!(sp.kind, Some(AgentKind::ClaudeCode));
799        assert!(sp.prompt.is_none());
800        assert!(sp.role.is_none());
801
802        let req_oc: Request = decode_line(
803            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"}"#,
804        )
805        .unwrap();
806        let Request::Spawn(sp_oc) = req_oc else {
807            panic!("expected Spawn")
808        };
809        assert_eq!(sp_oc.kind, Some(AgentKind::OpenCode));
810
811        let req_open_code: Request = decode_line(
812            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"}"#,
813        )
814        .unwrap();
815        let Request::Spawn(sp_open_code) = req_open_code else {
816            panic!("expected Spawn")
817        };
818        assert_eq!(sp_open_code.kind, Some(AgentKind::OpenCode));
819
820        let handoff: Request =
821            decode_line(r#"{"op":"handoff","session":"ses_1","kind":"claude","note":null}"#)
822                .unwrap();
823        let Request::Handoff { kind, .. } = handoff else {
824            panic!("expected Handoff")
825        };
826        assert_eq!(kind, AgentKind::ClaudeCode);
827
828        for (raw, expected) in [
829            ("allow", Decision::Allow),
830            ("Allow", Decision::Allow),
831            ("allow_always", Decision::AllowAlways),
832            ("Always", Decision::AllowAlways),
833            ("deny", Decision::Deny),
834            ("Deny", Decision::Deny),
835        ] {
836            let perm: Request = decode_line(&format!(
837                r#"{{"op":"permission","session":"ses_1","req":"perm_1","decision":"{raw}"}}"#
838            ))
839            .unwrap();
840            let Request::Permission { decision, .. } = perm else {
841                panic!("expected Permission")
842            };
843            assert_eq!(decision, expected);
844        }
845
846        for (raw, expected) in [
847            ("todo", TaskStatus::Todo),
848            ("Todo", TaskStatus::Todo),
849            ("doing", TaskStatus::Doing),
850            ("Doing", TaskStatus::Doing),
851            ("done", TaskStatus::Done),
852            ("Done", TaskStatus::Done),
853        ] {
854            let tu: Request = decode_line(&format!(
855                r#"{{"op":"task_update","id":"task_1","status":"{raw}"}}"#
856            ))
857            .unwrap();
858            let Request::TaskUpdate { status, .. } = tu else {
859                panic!("expected TaskUpdate")
860            };
861            assert_eq!(status, Some(expected));
862        }
863    }
864}