Skip to main content

trusty_code_tui/
event.rs

1//! The shared event vocabulary: [`ReplEvent`] and its small payload types.
2//!
3//! Why: both `TuiEngine` implementations (tagent's `AgentEngine`, tcode's
4//! `CodeEngine`) and the shared event loop (Slice 2+) need one common
5//! language for "things that happened" — a key press, a chunk of streamed
6//! assistant output, a tool call, a workstream change. `ReplEvent` is that
7//! language; generalizing it from tagent's existing (tagent-specific)
8//! `ReplEvent` in `crates/trusty-agents/src/repl/tui/types.rs` is the whole
9//! point of the extraction (DOC-50 §2.3, §3.2).
10//!
11//! What: this module defines the enum and the handful of payload types it
12//! needs. It intentionally does NOT depend on `crossterm` — [`KeyInput`] is
13//! trusty-code-tui's own minimal key representation; Slice 2 (#3414) adds the
14//! crossterm-backed terminal layer that translates real `crossterm::event::KeyEvent`
15//! values into this type at the boundary, keeping `ReplEvent` itself
16//! terminal-library-agnostic.
17//!
18//! # Spec References
19//! - [`SPEC-TTUI-03~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-03~draft) — Slice 1 `ReplEvent` deliverable (§5, Slice 1).
20//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — per-variant slice ownership (Slices 5/6/8/9).
21
22use crate::model::{CancelReply, PendingPermission, StatuslineSegment};
23use serde::{Deserialize, Serialize};
24
25/// Every event that can flow through the shared TUI's event channel.
26///
27/// Why: one `mpsc::UnboundedSender<ReplEvent>` is threaded through the whole
28/// stack (engine adapters, the key-reader task, the render loop), mirroring
29/// tagent's proven design in `crates/trusty-agents/src/repl/tui/run.rs`. A
30/// single enum keeps that channel typed and keeps `TuiEngine` implementors
31/// from needing bespoke channels per concern.
32/// What: variants are grouped below by who produces them. Terminal-origin
33/// variants (`Key`, `Resize`, `Scroll`) are produced by the Slice 2 terminal
34/// layer; engine-origin variants (`AssistantOutput` and later) are produced
35/// by `TuiEngine` implementations; `Submit` is synthesized by the shared
36/// event loop itself (echoed input, picker selection, etc. — see tagent's
37/// `process_event` for the precedent). The enum is exhaustive per DOC-50 §5
38/// Slice 1's acceptance criterion ("`ReplEvent` enum covers all expected
39/// event types"); new variants are additive as later slices land (tool
40/// cards in Slice 8, permission prompts in Slice 9).
41///
42/// # Spec References
43/// - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft)
44#[derive(Debug, Clone, PartialEq)]
45pub enum ReplEvent {
46    // ── Terminal-origin (Slice 2, #3414, wires the producer) ──────────
47    /// Raw keyboard input from the terminal's key-reader task.
48    Key(KeyInput),
49    /// The terminal was resized to `(cols, rows)`.
50    Resize(u16, u16),
51    /// Mouse-wheel scroll delta. Negative scrolls toward older history
52    /// (up), positive toward newer (down) — same convention as tagent's
53    /// `ReplEvent::Scroll`.
54    Scroll(isize),
55
56    // ── User-input dispatch (shared event loop) ────────────────────────
57    /// A line was submitted for the engine to process — either typed and
58    /// confirmed with Enter, or synthesized (e.g. a picker selection
59    /// resolving to a slash command). Consumed by `TuiEngine::handle_input`.
60    Submit(String),
61    /// The user requested cancellation of the in-flight request (Ctrl-C).
62    /// The shared event loop relays this to
63    /// `TuiEngine::cancel_session_reply` (DOC-50 §5 Slice 5) rather than only
64    /// clearing local UI state, per the thin-client axiom (C-2).
65    Cancel,
66    /// The reply to that relay landed (#8207) — synthesized by
67    /// `crate::run::dispatch_pending`'s spawned cancel task, never by a key
68    /// press or a `TuiEngine` implementation directly.
69    ///
70    /// Why: the cancel RPC runs on its own task so a slow backend cannot freeze
71    /// the render loop, and a spawned task cannot reach `&mut ReplApp` — so the
72    /// answer comes back as an event, like every other backend-originated
73    /// signal here. It exists at all because the TUI must not say "cancelled"
74    /// on request: until this event arrives the run may still be going, and
75    /// accepting a prompt in that window is what produced #8207's
76    /// `-32003 already has a task running`.
77    /// What: the payload names which of the three outcomes came back — see
78    /// [`CancelReply`]. A reply arriving when no cancel is outstanding is
79    /// ignored by the reducer (`crate::app::reduce`), so a straggler from an
80    /// already-settled cancel cannot clobber a newer turn's state.
81    CancelSettled(CancelReply),
82    /// The engine's `handle_input` returned `Ok(false)` (DOC-50 §5 Slice 5) —
83    /// synthesized by `crate::run::run`'s dispatch step, never by a key press
84    /// directly (Ctrl-D sets `ReplApp::quit` straight from the reducer since
85    /// it needs no round-trip through the engine). Exists because the
86    /// dispatch step only holds `&mut M` synchronously inside `apply`; the
87    /// spawned `handle_input` task that later learns "the engine wants to
88    /// quit" can reach the model only by pushing an event back onto the
89    /// shared channel, same as every other engine-originated signal here.
90    Quit,
91    /// A submitted turn's `TuiEngine::handle_input` call has returned, and
92    /// `crate::run::dispatch_pending` determined no terminal signal
93    /// (`AssistantOutput { done: true, .. }` or `Quit`) was ever relayed for
94    /// it — synthesized as a safety net, never by a key press or a
95    /// `TuiEngine` implementation directly.
96    ///
97    /// Why: `ReplApp::busy` is cleared ONLY by a terminal
98    /// `AssistantOutput`/`Quit` reaching the reducer — but three real,
99    /// spec-required `CodeEngine` paths return `Ok(true)` from
100    /// `handle_input` without ever sending one (`/workstream list`/
101    /// `activate`, which only push `StatusMessage`/`WorkstreamUpdated`; a
102    /// reconnect-exhausted `pump_session_events` return; a daemon-initiated
103    /// `SessionCancelled` that only pushes a `StatusMessage`). Combined with
104    /// Slice 5's busy-gating (`ReplApp::submit_line` refuses a second turn
105    /// while `busy`), any such path left `busy` stuck `true` forever —
106    /// input permanently bricked, recoverable only by the accident of
107    /// Ctrl-C's own reset. This variant is the fix: a dedicated,
108    /// minimal reset that touches ONLY `busy`/`streaming_idx`, deliberately
109    /// NOT reusing an empty `AssistantOutput { done: true, .. }` for this
110    /// (that would push a stray blank chat entry via the `None`-
111    /// `streaming_idx` branch of `apply_assistant_output` — corrupting
112    /// scrollback to fix a different bug).
113    ///
114    /// **Carries its own `generation`** (the turn number `crate::run::
115    /// dispatch_pending` assigned it) so the reducer — not the spawned
116    /// completion task — decides whether it's still relevant. A prior
117    /// revision had the spawned task load-and-compare the live generation
118    /// counter itself before deciding whether to send this event at all;
119    /// that compare-then-send was a genuine TOCTOU race under
120    /// multi-threaded tokio (a cancel + new submit could both run in the
121    /// gap between the load and the send), letting a stale terminal signal
122    /// from turn N clear `busy`/`streaming_idx` for a genuinely in-flight
123    /// turn N+2. Fixed by construction: the completion task now always
124    /// sends this event (stamped with its own generation, no load-then-
125    /// branch), and the reducer — which runs serially on the same task that
126    /// bumps the generation counter, so no cross-thread race is possible —
127    /// applies it only if `generation` still matches
128    /// `ReplApp::current_generation`.
129    /// What: engine implementations should never construct this directly;
130    /// it exists purely as `crate::run::dispatch_pending`'s per-turn
131    /// completion safety net (see that function's doc comment).
132    TurnFinished { generation: u64 },
133
134    // ── Engine-origin (produced by `TuiEngine` implementations) ────────
135    /// A chunk of streamed assistant output. `done` marks the final chunk of
136    /// a response so the scrollback can stop showing a "thinking" indicator;
137    /// `is_error` marks the text as an error message rather than a normal
138    /// response (mirrors tagent's `LlmResponse { text, is_error }`).
139    AssistantOutput {
140        chunk: String,
141        done: bool,
142        is_error: bool,
143    },
144    /// A tool was invoked by the backend agent. `result` is `None` while the
145    /// call is in flight and `Some(..)` once it completes. Rendering (text
146    /// vs. fancy card) is a Slice 8 (#TBD, Phase 2) concern; the event shape
147    /// is defined now so `TuiEngine` implementations don't need a breaking
148    /// change later.
149    ///
150    /// `id` correlates a call's start (`result: None`) with its completion
151    /// (`result: Some(..)`) — two separate `ToolInvocation` events sharing
152    /// the same `id`. Required because `tool_name` alone can't disambiguate
153    /// repeated or parallel calls to the same tool (e.g. two concurrent
154    /// `fs.read` calls); the engine adapter mints this id (a UUID or a
155    /// backend-supplied call id, whichever it has) and must reuse it across
156    /// the start/complete pair.
157    ///
158    /// `agent_id` (#7940) is the opaque id of the agent that dispatched the
159    /// call, matching [`Self::DelegationStarted`]'s `agent_id` when the
160    /// caller is a delegated sub-agent. Empty when the engine has no
161    /// attribution to offer. It is what lets the reducer render a delegated
162    /// agent's tool calls INSIDE that agent's block rather than at the top
163    /// level beside the primary agent's own.
164    ///
165    /// `failed` (#4596) is the backend's own verdict on the call, carried as
166    /// data. Producers also write a human marker into `result` (trusty-code
167    /// sends `FAILED: …` / `ERROR: …`), but that text is for the reader —
168    /// rewording it must never change how the TUI renders the card, which is
169    /// why the fact travels in its own field. Meaningless while `result` is
170    /// `None`: a call that has not finished has not failed, so a start event
171    /// sets `false`. Set `true` ONLY on a completion the backend reported as
172    /// unsuccessful.
173    ToolInvocation {
174        id: String,
175        agent_id: String,
176        tool_name: String,
177        args: serde_json::Value,
178        result: Option<String>,
179        failed: bool,
180    },
181    /// A chunk of streamed output attributed to a specific agent turn
182    /// (#7940).
183    ///
184    /// Why: [`Self::AssistantOutput`] carries no attribution and the reducer
185    /// accumulates it into ONE unkeyed in-progress bubble, so a primary
186    /// agent and a delegated sub-agent streaming at the same time interleave
187    /// their words into a single chat entry. This variant carries the
188    /// `(agent_id, turn_id)` pair the reducer keys a separate bubble on, so
189    /// concurrent streams stay separate by construction.
190    /// What: `agent_id` is the opaque per-spawn agent id; `turn_id` is the
191    /// producer's own per-turn id. Append every chunk sharing one
192    /// `(agent_id, turn_id)` key in arrival order; `done: true` closes that
193    /// bubble and no further chunk for the key will arrive. Unlike
194    /// `AssistantOutput`, this variant never clears the model's `busy` flag:
195    /// one agent's turn ending is not the human turn ending.
196    AgentOutput {
197        agent_id: String,
198        turn_id: String,
199        chunk: String,
200        done: bool,
201    },
202    /// A delegated sub-agent started working on a task (#7940).
203    ///
204    /// Why: delegation is invisible in the scrollback without it — the
205    /// sub-agent's output and tool calls arrive indistinguishable from the
206    /// primary agent's. This opens a rendered block the sub-agent's activity
207    /// hangs under.
208    /// What: `agent_id` is an opaque, producer-minted id, unique per spawn
209    /// (`agent` alone cannot separate two concurrent delegations of the same
210    /// kind). It MAY be empty when the producer announces an intent to
211    /// delegate before the sub-agent exists; a later `DelegationStarted`
212    /// naming the same `agent` with a non-empty `agent_id` adopts the
213    /// already-open block rather than opening a second one. `task` is a
214    /// short human summary of what was delegated.
215    DelegationStarted {
216        agent_id: String,
217        agent: String,
218        task: String,
219    },
220    /// A delegated sub-agent's run ended (#7940) — closes the block
221    /// [`Self::DelegationStarted`] opened, keyed by the same `agent_id`.
222    DelegationFinished {
223        agent_id: String,
224        agent: String,
225        outcome: DelegationOutcome,
226    },
227    /// A tool call matched an `ask` permission rule and is SUSPENDED on the
228    /// backend until this client answers (#3422, wire event from #7948).
229    ///
230    /// Why: the backend has already stopped the call and is waiting; the TUI
231    /// has to say so and collect an answer, because silence resolves as a
232    /// deny after the backend's timeout. The reducer opens a modal prompt on
233    /// this event — see [`crate::app::ReplApp::pending_permission`].
234    /// What: `request_id` is the correlation key the answer goes back on
235    /// (NOT a tool-call id — the call has not run). `agent`/`agent_id` are
236    /// the same attribution pair [`Self::DelegationStarted`] carries, so a
237    /// prompt raised inside a delegation can name its sub-agent. `subject`
238    /// is what the tool would act on, ALREADY redacted and length-bounded by
239    /// the producer — this crate renders it verbatim and never re-derives it.
240    /// `rule` is the matching policy pattern, shown so the user can see why
241    /// they are being asked.
242    PermissionRequested {
243        request_id: String,
244        agent: String,
245        agent_id: String,
246        tool: String,
247        subject: String,
248        rule: String,
249    },
250    /// A suspended permission request reached a decision (#3422, wire event
251    /// from #7948) — the explicit close for the prompt
252    /// [`Self::PermissionRequested`] opened.
253    ///
254    /// Why: the backend decides, not the TUI (thin-client axiom, ADR-0063):
255    /// a request can resolve without this client answering at all (another
256    /// client answered, the backend timed out, a remembered grant or an
257    /// auto-allow mode covered it). This event — not the local key press —
258    /// is what puts the outcome in the scrollback.
259    /// What: `decision` and `source` are the producer's own words, rendered
260    /// verbatim; this crate parses neither. A `request_id` matching the open
261    /// prompt closes it, and one that does not is still recorded.
262    PermissionResolved {
263        request_id: String,
264        agent: String,
265        agent_id: String,
266        decision: String,
267        source: String,
268    },
269    /// Relaying an answer to `TuiEngine::respond_permission` FAILED (#3422)
270    /// — the suspended call never heard it.
271    ///
272    /// Why: the prompt closes the moment a key is pressed, before the RPC
273    /// even starts, so the keyboard is never held hostage by a slow backend.
274    /// That optimism is only safe if a failure is reversible: without this
275    /// event the operator loses the modal while the backend keeps holding
276    /// the call until it times out, with no way to answer again. This is the
277    /// undo.
278    /// What: carries the original request verbatim, so the reducer can
279    /// reopen exactly the prompt that was answered, plus the engine's own
280    /// error text for the retry line and the transcript. Emitted ONLY by
281    /// `crate::run::dispatch_pending`'s relay task, never by an engine.
282    PermissionAnswerFailed {
283        pending: PendingPermission,
284        error: String,
285    },
286    /// A one-line status message (e.g. "cancelled", "Switched to: izzie").
287    StatusMessage(String),
288    /// Engine-supplied startup splash lines, replacing the banner's generic
289    /// `{banner_title} v{version}` identity row (#8164).
290    ///
291    /// Why: the only launch facts this crate can name on its own are the ones
292    /// a product set on [`crate::app::ReplApp`] at construction. Everything an
293    /// operator actually needs at a glance — the daemon's build, the session
294    /// id, the project the session is homed in — is learned from the backend
295    /// during `TuiEngine::setup`, after the app was built. This is how those
296    /// reach the banner.
297    /// What: a pre-rendered, pre-ordered block of plain lines. This crate
298    /// composes none of it and parses none of it; the first line is rendered
299    /// as the header and the rest as body. An empty vector restores the
300    /// generic identity row.
301    SplashUpdated(Vec<String>),
302    /// Clear the scrollback buffer. Emitted by the shared `/clear` built-in
303    /// slash command (DOC-50 §5 Slice 7) rather than handled ad hoc by each
304    /// engine, so `TuiEngine` implementations never touch scrollback state
305    /// directly.
306    ClearScrollback,
307    /// Engine-supplied statusline segments replacing the current set
308    /// (session id, model, project, workstream, …). See
309    /// [`StatuslineSegment`] (`crate::model`) for the full, Slice-1.5
310    /// segment taxonomy.
311    StatuslineUpdate(Vec<StatuslineSegment>),
312    /// The active workstream's summary changed (initial load or refetch
313    /// after an activation change).
314    WorkstreamUpdated(WorkstreamSummary),
315    /// The daemon activated a different workstream (DOC-48 §5.3
316    /// `WorkstreamActivationChanged`), pushed via
317    /// `TuiEngine::subscribe_workstream_events`. `prior_id` is `None` on the
318    /// very first activation observed in this session. `new_active_id` is
319    /// `None` when the active workstream was deactivated and none is now
320    /// active (DOC-48 §4.2/§4.3) — a real, daemon-published state, not an
321    /// absence of data; distinct from `prior_id: None`, which means "no
322    /// activation happened before this one."
323    ///
324    /// Field names are chosen to match the DOC-48 §5.3 SSE wire event
325    /// exactly (`new_active_id`, `prior_id`) — NOT DOC-50 §5 Slice 6's prose
326    /// (`new_id`), which drifted from the actual wire schema. Since engine
327    /// adapters deserialize this from JSON (Slice 3/6), a Rust/wire name
328    /// mismatch here would not be caught at compile time, only at runtime
329    /// deserialization — so the Rust field is kept byte-identical to the
330    /// wire field on purpose, including its optionality: the wire event
331    /// (`crate::events::Event::WorkstreamActivationChanged` in
332    /// `trusty-code`) declares `new_active_id: Option<String>` for exactly
333    /// this reason, and this variant now mirrors that shape rather than
334    /// forcing a lossy `StatusMessage` fallback for the `None` case.
335    WorkstreamActivationChanged {
336        new_active_id: Option<String>,
337        prior_id: Option<String>,
338    },
339    /// The backend connection was lost (daemon restart, SSE stream closed,
340    /// HTTP timeout/502/503). The TUI shows a "Connection lost" status;
341    /// input remains live and the next `handle_input`/
342    /// `subscribe_workstream_events` call attempts to reconnect (DOC-50
343    /// §2.4).
344    ConnectionLost { reason: String },
345}
346
347/// How a delegated sub-agent's run ended (#7940) — the payload of
348/// [`ReplEvent::DelegationFinished`].
349///
350/// Why: the block footer has to say more than "over": an engineer that
351/// finished and one that blew up look identical otherwise, which is exactly
352/// the thing an operator watching a delegation needs to see at a glance.
353/// Two variants rather than a `Result<String, String>` so the rendered
354/// vocabulary is this crate's own and no caller has to decide what the `Ok`
355/// side of a `Result` means here.
356/// What: `Finished` carries the producer's own status label (e.g.
357/// `"success"`); `Failed` carries the error text.
358#[derive(Debug, Clone, PartialEq, Eq)]
359pub enum DelegationOutcome {
360    /// The sub-agent's loop returned normally; carries the producer's status
361    /// label.
362    Finished(String),
363    /// The sub-agent's loop failed; carries the error text.
364    Failed(String),
365}
366
367/// Minimal, `crossterm`-independent representation of a single key press.
368///
369/// Why: `ReplEvent` must not force a `crossterm` dependency onto every
370/// `TuiEngine` consumer (only the Slice 2 terminal layer needs to know a
371/// terminal library exists at all). This type is the boundary: Slice 2
372/// translates `crossterm::event::KeyEvent` into `KeyInput` once, at the
373/// key-reader task.
374/// What: `code` identifies the key; `modifiers` are the held modifier keys.
375/// Deliberately small — only what tagent's existing line editor
376/// (`crates/trusty-agents/src/repl/tui/keys.rs`) actually switches on
377/// (Ctrl-a/e/u/c/d, arrows, Enter, Backspace, printable chars).
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub struct KeyInput {
380    pub code: KeyCode,
381    pub modifiers: KeyModifiers,
382}
383
384/// The identity of a key, independent of any terminal library's own enum.
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub enum KeyCode {
387    Char(char),
388    Enter,
389    Backspace,
390    Delete,
391    Tab,
392    Esc,
393    Left,
394    Right,
395    Up,
396    Down,
397    Home,
398    End,
399    PageUp,
400    PageDown,
401    /// A key not yet mapped to a named variant above. Slice 2 can extend
402    /// this enum as the line editor grows new bindings; keeping this
403    /// fallback avoids a breaking change for every new key tagent's editor
404    /// happens to read.
405    Other,
406}
407
408/// Modifier keys held alongside a [`KeyCode`].
409#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
410pub struct KeyModifiers {
411    pub ctrl: bool,
412    pub alt: bool,
413    pub shift: bool,
414}
415
416/// A minimal summary of a workstream (DOC-48 §2.1), enough for the status
417/// line and `/workstream list` output.
418///
419/// Why: `ReplEvent::WorkstreamUpdated` needs a payload; the full
420/// `Workstream` type lives in trusty-code/trusty-agents-common and must not
421/// become a `trusty-code-tui` dependency (that would invert DOC-50 §2.2's
422/// dependency direction — `trusty-code-tui` depends on nothing product-specific).
423/// What: `id` and `name` are the two fields DOC-50 §5 Slice 6's status-line
424/// example ("WS: Token rotation (a1b2c3d4)") actually needs.
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
426pub struct WorkstreamSummary {
427    pub id: String,
428    pub name: String,
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    /// `ReplEvent` must round-trip through `Clone`/`PartialEq` for the
436    /// event-loop tests Slice 2+ will add (asserting "this event was
437    /// pushed"); a `Debug`/`Clone`/`PartialEq` derive failing to compile on
438    /// any variant would be a stub with unusable payload types.
439    #[test]
440    fn repl_event_variants_are_cloneable_and_comparable() {
441        let a = ReplEvent::StatusMessage("hello".to_string());
442        let b = a.clone();
443        assert_eq!(a, b);
444
445        let ws = ReplEvent::WorkstreamUpdated(WorkstreamSummary {
446            id: "a1b2c3d4".to_string(),
447            name: "Token rotation".to_string(),
448        });
449        assert_eq!(ws.clone(), ws);
450    }
451
452    /// Two `ToolInvocation` events sharing the same `id` (a pending call and
453    /// its completion) must be distinguishable ONLY by `result`, not by
454    /// `id` — that's the whole point of adding the correlation id (Slice 8's
455    /// "pending → complete" tool cards match on it, not on `tool_name`,
456    /// which breaks for repeated/parallel calls to the same tool).
457    #[test]
458    fn tool_invocation_start_and_complete_share_a_correlation_id() {
459        let start = ReplEvent::ToolInvocation {
460            id: "call-1".to_string(),
461            agent_id: String::new(),
462            tool_name: "fs.read".to_string(),
463            args: serde_json::json!({"path": "a.txt"}),
464            result: None,
465            failed: false,
466        };
467        let complete = ReplEvent::ToolInvocation {
468            id: "call-1".to_string(),
469            agent_id: String::new(),
470            tool_name: "fs.read".to_string(),
471            args: serde_json::json!({"path": "a.txt"}),
472            result: Some("contents".to_string()),
473            failed: false,
474        };
475        assert_ne!(start, complete);
476        let ReplEvent::ToolInvocation { id: start_id, .. } = &start else {
477            unreachable!()
478        };
479        let ReplEvent::ToolInvocation {
480            id: complete_id, ..
481        } = &complete
482        else {
483            unreachable!()
484        };
485        assert_eq!(start_id, complete_id);
486    }
487
488    /// `/clear` (DOC-50 §5 Slice 7) emits `ClearScrollback` — a unit
489    /// variant, just confirming it exists and round-trips like any other.
490    #[test]
491    fn clear_scrollback_is_a_distinct_unit_variant() {
492        assert_eq!(ReplEvent::ClearScrollback, ReplEvent::ClearScrollback);
493        assert_ne!(ReplEvent::ClearScrollback, ReplEvent::Cancel);
494    }
495
496    /// `Quit` (DOC-50 §5 Slice 5) is a distinct unit variant, same as
497    /// `ClearScrollback` above — `crate::run::run`'s dispatch step sends it
498    /// when `TuiEngine::handle_input` returns `Ok(false)`.
499    #[test]
500    fn quit_is_a_distinct_unit_variant() {
501        assert_eq!(ReplEvent::Quit, ReplEvent::Quit);
502        assert_ne!(ReplEvent::Quit, ReplEvent::Cancel);
503    }
504
505    /// `TurnFinished` (the `dispatch_pending` completion safety net) carries
506    /// its own `generation` and compares by value, same as any other field.
507    #[test]
508    fn turn_finished_carries_and_compares_its_generation() {
509        assert_eq!(
510            ReplEvent::TurnFinished { generation: 1 },
511            ReplEvent::TurnFinished { generation: 1 }
512        );
513        assert_ne!(
514            ReplEvent::TurnFinished { generation: 1 },
515            ReplEvent::TurnFinished { generation: 2 }
516        );
517        assert_ne!(ReplEvent::TurnFinished { generation: 1 }, ReplEvent::Quit);
518    }
519
520    /// `WorkstreamActivationChanged`'s field is named `new_active_id` to
521    /// match the DOC-48 §5.3 SSE wire event exactly (not DOC-50 §5 Slice 6's
522    /// prose, which drifted to `new_id`) — a JSON field-name mismatch here
523    /// would only surface at deserialization time, not compile time, so
524    /// this test exists to keep the field name from silently drifting back.
525    #[test]
526    fn workstream_activation_changed_uses_wire_field_name() {
527        let ev = ReplEvent::WorkstreamActivationChanged {
528            new_active_id: Some("a1b2c3d4".to_string()),
529            prior_id: Some("00000000".to_string()),
530        };
531        let ReplEvent::WorkstreamActivationChanged {
532            new_active_id,
533            prior_id,
534        } = &ev
535        else {
536            unreachable!()
537        };
538        assert_eq!(new_active_id.as_deref(), Some("a1b2c3d4"));
539        assert_eq!(prior_id.as_deref(), Some("00000000"));
540    }
541
542    /// `new_active_id: None` must be representable and distinguishable from
543    /// `prior_id: None` — the whole point of this fix (issue tracked in the
544    /// commit landing this test): the daemon legitimately publishes
545    /// "deactivated, no replacement active" (DOC-48 §4.2/§4.3), and the
546    /// shared event must carry that without falling back to free text.
547    #[test]
548    fn workstream_activation_changed_represents_deactivation_with_no_replacement() {
549        let ev = ReplEvent::WorkstreamActivationChanged {
550            new_active_id: None,
551            prior_id: Some("a1b2c3d4".to_string()),
552        };
553        let ReplEvent::WorkstreamActivationChanged {
554            new_active_id,
555            prior_id,
556        } = &ev
557        else {
558            unreachable!()
559        };
560        assert_eq!(*new_active_id, None);
561        assert_eq!(prior_id.as_deref(), Some("a1b2c3d4"));
562    }
563
564    /// `KeyInput` default modifiers must be "nothing held" so a bare
565    /// `KeyCode` translation (Slice 2) doesn't need to construct
566    /// `KeyModifiers` by hand for the common case.
567    #[test]
568    fn key_modifiers_default_to_none_held() {
569        let m = KeyModifiers::default();
570        assert!(!m.ctrl && !m.alt && !m.shift);
571    }
572
573    /// `WorkstreamSummary` is the wire shape `ReplEvent::WorkstreamUpdated`
574    /// carries; a (de)serialization round-trip is the cheapest guarantee
575    /// that later HTTP-transported engines (CodeEngine) can carry it
576    /// without a custom `Serialize` impl. (`StatuslineSegment`/`PickerItem`/
577    /// `CommandDescriptor` round-trip tests moved to `crate::model` — Slice
578    /// 1.5 relocated those types there.)
579    #[test]
580    fn workstream_summary_round_trips_through_json() {
581        let ws = WorkstreamSummary {
582            id: "a1b2c3d4".to_string(),
583            name: "Token rotation".to_string(),
584        };
585        let json = serde_json::to_string(&ws).expect("serialize");
586        assert_eq!(ws, serde_json::from_str(&json).expect("deserialize"));
587    }
588}