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::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 `TuiEngine::cancel_session`
63 /// (DOC-50 §5 Slice 5) rather than only clearing local UI state, per the
64 /// thin-client axiom (C-2).
65 Cancel,
66 /// The engine's `handle_input` returned `Ok(false)` (DOC-50 §5 Slice 5) —
67 /// synthesized by `crate::run::run`'s dispatch step, never by a key press
68 /// directly (Ctrl-D sets `ReplApp::quit` straight from the reducer since
69 /// it needs no round-trip through the engine). Exists because the
70 /// dispatch step only holds `&mut M` synchronously inside `apply`; the
71 /// spawned `handle_input` task that later learns "the engine wants to
72 /// quit" can reach the model only by pushing an event back onto the
73 /// shared channel, same as every other engine-originated signal here.
74 Quit,
75 /// A submitted turn's `TuiEngine::handle_input` call has returned, and
76 /// `crate::run::dispatch_pending` determined no terminal signal
77 /// (`AssistantOutput { done: true, .. }` or `Quit`) was ever relayed for
78 /// it — synthesized as a safety net, never by a key press or a
79 /// `TuiEngine` implementation directly.
80 ///
81 /// Why: `ReplApp::busy` is cleared ONLY by a terminal
82 /// `AssistantOutput`/`Quit` reaching the reducer — but three real,
83 /// spec-required `CodeEngine` paths return `Ok(true)` from
84 /// `handle_input` without ever sending one (`/workstream list`/
85 /// `activate`, which only push `StatusMessage`/`WorkstreamUpdated`; a
86 /// reconnect-exhausted `pump_session_events` return; a daemon-initiated
87 /// `SessionCancelled` that only pushes a `StatusMessage`). Combined with
88 /// Slice 5's busy-gating (`ReplApp::submit_line` refuses a second turn
89 /// while `busy`), any such path left `busy` stuck `true` forever —
90 /// input permanently bricked, recoverable only by the accident of
91 /// Ctrl-C's `on_cancelled` reset. This variant is the fix: a dedicated,
92 /// minimal reset that touches ONLY `busy`/`streaming_idx`, deliberately
93 /// NOT reusing an empty `AssistantOutput { done: true, .. }` for this
94 /// (that would push a stray blank chat entry via the `None`-
95 /// `streaming_idx` branch of `apply_assistant_output` — corrupting
96 /// scrollback to fix a different bug).
97 ///
98 /// **Carries its own `generation`** (the turn number `crate::run::
99 /// dispatch_pending` assigned it) so the reducer — not the spawned
100 /// completion task — decides whether it's still relevant. A prior
101 /// revision had the spawned task load-and-compare the live generation
102 /// counter itself before deciding whether to send this event at all;
103 /// that compare-then-send was a genuine TOCTOU race under
104 /// multi-threaded tokio (a cancel + new submit could both run in the
105 /// gap between the load and the send), letting a stale terminal signal
106 /// from turn N clear `busy`/`streaming_idx` for a genuinely in-flight
107 /// turn N+2. Fixed by construction: the completion task now always
108 /// sends this event (stamped with its own generation, no load-then-
109 /// branch), and the reducer — which runs serially on the same task that
110 /// bumps the generation counter, so no cross-thread race is possible —
111 /// applies it only if `generation` still matches
112 /// `ReplApp::current_generation`.
113 /// What: engine implementations should never construct this directly;
114 /// it exists purely as `crate::run::dispatch_pending`'s per-turn
115 /// completion safety net (see that function's doc comment).
116 TurnFinished { generation: u64 },
117
118 // ── Engine-origin (produced by `TuiEngine` implementations) ────────
119 /// A chunk of streamed assistant output. `done` marks the final chunk of
120 /// a response so the scrollback can stop showing a "thinking" indicator;
121 /// `is_error` marks the text as an error message rather than a normal
122 /// response (mirrors tagent's `LlmResponse { text, is_error }`).
123 AssistantOutput {
124 chunk: String,
125 done: bool,
126 is_error: bool,
127 },
128 /// A tool was invoked by the backend agent. `result` is `None` while the
129 /// call is in flight and `Some(..)` once it completes. Rendering (text
130 /// vs. fancy card) is a Slice 8 (#TBD, Phase 2) concern; the event shape
131 /// is defined now so `TuiEngine` implementations don't need a breaking
132 /// change later.
133 ///
134 /// `id` correlates a call's start (`result: None`) with its completion
135 /// (`result: Some(..)`) — two separate `ToolInvocation` events sharing
136 /// the same `id`. Required because `tool_name` alone can't disambiguate
137 /// repeated or parallel calls to the same tool (e.g. two concurrent
138 /// `fs.read` calls); the engine adapter mints this id (a UUID or a
139 /// backend-supplied call id, whichever it has) and must reuse it across
140 /// the start/complete pair.
141 ToolInvocation {
142 id: String,
143 tool_name: String,
144 args: serde_json::Value,
145 result: Option<String>,
146 },
147 /// A one-line status message (e.g. "cancelled", "Switched to: izzie").
148 StatusMessage(String),
149 /// Clear the scrollback buffer. Emitted by the shared `/clear` built-in
150 /// slash command (DOC-50 §5 Slice 7) rather than handled ad hoc by each
151 /// engine, so `TuiEngine` implementations never touch scrollback state
152 /// directly.
153 ClearScrollback,
154 /// Engine-supplied statusline segments replacing the current set
155 /// (session id, model, project, workstream, …). See
156 /// [`StatuslineSegment`] (`crate::model`) for the full, Slice-1.5
157 /// segment taxonomy.
158 StatuslineUpdate(Vec<StatuslineSegment>),
159 /// The active workstream's summary changed (initial load or refetch
160 /// after an activation change).
161 WorkstreamUpdated(WorkstreamSummary),
162 /// The daemon activated a different workstream (DOC-48 §5.3
163 /// `WorkstreamActivationChanged`), pushed via
164 /// `TuiEngine::subscribe_workstream_events`. `prior_id` is `None` on the
165 /// very first activation observed in this session. `new_active_id` is
166 /// `None` when the active workstream was deactivated and none is now
167 /// active (DOC-48 §4.2/§4.3) — a real, daemon-published state, not an
168 /// absence of data; distinct from `prior_id: None`, which means "no
169 /// activation happened before this one."
170 ///
171 /// Field names are chosen to match the DOC-48 §5.3 SSE wire event
172 /// exactly (`new_active_id`, `prior_id`) — NOT DOC-50 §5 Slice 6's prose
173 /// (`new_id`), which drifted from the actual wire schema. Since engine
174 /// adapters deserialize this from JSON (Slice 3/6), a Rust/wire name
175 /// mismatch here would not be caught at compile time, only at runtime
176 /// deserialization — so the Rust field is kept byte-identical to the
177 /// wire field on purpose, including its optionality: the wire event
178 /// (`crate::events::Event::WorkstreamActivationChanged` in
179 /// `trusty-code`) declares `new_active_id: Option<String>` for exactly
180 /// this reason, and this variant now mirrors that shape rather than
181 /// forcing a lossy `StatusMessage` fallback for the `None` case.
182 WorkstreamActivationChanged {
183 new_active_id: Option<String>,
184 prior_id: Option<String>,
185 },
186 /// The backend connection was lost (daemon restart, SSE stream closed,
187 /// HTTP timeout/502/503). The TUI shows a "Connection lost" status;
188 /// input remains live and the next `handle_input`/
189 /// `subscribe_workstream_events` call attempts to reconnect (DOC-50
190 /// §2.4).
191 ConnectionLost { reason: String },
192}
193
194/// Minimal, `crossterm`-independent representation of a single key press.
195///
196/// Why: `ReplEvent` must not force a `crossterm` dependency onto every
197/// `TuiEngine` consumer (only the Slice 2 terminal layer needs to know a
198/// terminal library exists at all). This type is the boundary: Slice 2
199/// translates `crossterm::event::KeyEvent` into `KeyInput` once, at the
200/// key-reader task.
201/// What: `code` identifies the key; `modifiers` are the held modifier keys.
202/// Deliberately small — only what tagent's existing line editor
203/// (`crates/trusty-agents/src/repl/tui/keys.rs`) actually switches on
204/// (Ctrl-a/e/u/c/d, arrows, Enter, Backspace, printable chars).
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub struct KeyInput {
207 pub code: KeyCode,
208 pub modifiers: KeyModifiers,
209}
210
211/// The identity of a key, independent of any terminal library's own enum.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum KeyCode {
214 Char(char),
215 Enter,
216 Backspace,
217 Delete,
218 Tab,
219 Esc,
220 Left,
221 Right,
222 Up,
223 Down,
224 Home,
225 End,
226 PageUp,
227 PageDown,
228 /// A key not yet mapped to a named variant above. Slice 2 can extend
229 /// this enum as the line editor grows new bindings; keeping this
230 /// fallback avoids a breaking change for every new key tagent's editor
231 /// happens to read.
232 Other,
233}
234
235/// Modifier keys held alongside a [`KeyCode`].
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
237pub struct KeyModifiers {
238 pub ctrl: bool,
239 pub alt: bool,
240 pub shift: bool,
241}
242
243/// A minimal summary of a workstream (DOC-48 §2.1), enough for the status
244/// line and `/workstream list` output.
245///
246/// Why: `ReplEvent::WorkstreamUpdated` needs a payload; the full
247/// `Workstream` type lives in trusty-code/trusty-agents-common and must not
248/// become a `trusty-code-tui` dependency (that would invert DOC-50 §2.2's
249/// dependency direction — `trusty-code-tui` depends on nothing product-specific).
250/// What: `id` and `name` are the two fields DOC-50 §5 Slice 6's status-line
251/// example ("WS: Token rotation (a1b2c3d4)") actually needs.
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253pub struct WorkstreamSummary {
254 pub id: String,
255 pub name: String,
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 /// `ReplEvent` must round-trip through `Clone`/`PartialEq` for the
263 /// event-loop tests Slice 2+ will add (asserting "this event was
264 /// pushed"); a `Debug`/`Clone`/`PartialEq` derive failing to compile on
265 /// any variant would be a stub with unusable payload types.
266 #[test]
267 fn repl_event_variants_are_cloneable_and_comparable() {
268 let a = ReplEvent::StatusMessage("hello".to_string());
269 let b = a.clone();
270 assert_eq!(a, b);
271
272 let ws = ReplEvent::WorkstreamUpdated(WorkstreamSummary {
273 id: "a1b2c3d4".to_string(),
274 name: "Token rotation".to_string(),
275 });
276 assert_eq!(ws.clone(), ws);
277 }
278
279 /// Two `ToolInvocation` events sharing the same `id` (a pending call and
280 /// its completion) must be distinguishable ONLY by `result`, not by
281 /// `id` — that's the whole point of adding the correlation id (Slice 8's
282 /// "pending → complete" tool cards match on it, not on `tool_name`,
283 /// which breaks for repeated/parallel calls to the same tool).
284 #[test]
285 fn tool_invocation_start_and_complete_share_a_correlation_id() {
286 let start = ReplEvent::ToolInvocation {
287 id: "call-1".to_string(),
288 tool_name: "fs.read".to_string(),
289 args: serde_json::json!({"path": "a.txt"}),
290 result: None,
291 };
292 let complete = ReplEvent::ToolInvocation {
293 id: "call-1".to_string(),
294 tool_name: "fs.read".to_string(),
295 args: serde_json::json!({"path": "a.txt"}),
296 result: Some("contents".to_string()),
297 };
298 assert_ne!(start, complete);
299 let ReplEvent::ToolInvocation { id: start_id, .. } = &start else {
300 unreachable!()
301 };
302 let ReplEvent::ToolInvocation {
303 id: complete_id, ..
304 } = &complete
305 else {
306 unreachable!()
307 };
308 assert_eq!(start_id, complete_id);
309 }
310
311 /// `/clear` (DOC-50 §5 Slice 7) emits `ClearScrollback` — a unit
312 /// variant, just confirming it exists and round-trips like any other.
313 #[test]
314 fn clear_scrollback_is_a_distinct_unit_variant() {
315 assert_eq!(ReplEvent::ClearScrollback, ReplEvent::ClearScrollback);
316 assert_ne!(ReplEvent::ClearScrollback, ReplEvent::Cancel);
317 }
318
319 /// `Quit` (DOC-50 §5 Slice 5) is a distinct unit variant, same as
320 /// `ClearScrollback` above — `crate::run::run`'s dispatch step sends it
321 /// when `TuiEngine::handle_input` returns `Ok(false)`.
322 #[test]
323 fn quit_is_a_distinct_unit_variant() {
324 assert_eq!(ReplEvent::Quit, ReplEvent::Quit);
325 assert_ne!(ReplEvent::Quit, ReplEvent::Cancel);
326 }
327
328 /// `TurnFinished` (the `dispatch_pending` completion safety net) carries
329 /// its own `generation` and compares by value, same as any other field.
330 #[test]
331 fn turn_finished_carries_and_compares_its_generation() {
332 assert_eq!(
333 ReplEvent::TurnFinished { generation: 1 },
334 ReplEvent::TurnFinished { generation: 1 }
335 );
336 assert_ne!(
337 ReplEvent::TurnFinished { generation: 1 },
338 ReplEvent::TurnFinished { generation: 2 }
339 );
340 assert_ne!(ReplEvent::TurnFinished { generation: 1 }, ReplEvent::Quit);
341 }
342
343 /// `WorkstreamActivationChanged`'s field is named `new_active_id` to
344 /// match the DOC-48 §5.3 SSE wire event exactly (not DOC-50 §5 Slice 6's
345 /// prose, which drifted to `new_id`) — a JSON field-name mismatch here
346 /// would only surface at deserialization time, not compile time, so
347 /// this test exists to keep the field name from silently drifting back.
348 #[test]
349 fn workstream_activation_changed_uses_wire_field_name() {
350 let ev = ReplEvent::WorkstreamActivationChanged {
351 new_active_id: Some("a1b2c3d4".to_string()),
352 prior_id: Some("00000000".to_string()),
353 };
354 let ReplEvent::WorkstreamActivationChanged {
355 new_active_id,
356 prior_id,
357 } = &ev
358 else {
359 unreachable!()
360 };
361 assert_eq!(new_active_id.as_deref(), Some("a1b2c3d4"));
362 assert_eq!(prior_id.as_deref(), Some("00000000"));
363 }
364
365 /// `new_active_id: None` must be representable and distinguishable from
366 /// `prior_id: None` — the whole point of this fix (issue tracked in the
367 /// commit landing this test): the daemon legitimately publishes
368 /// "deactivated, no replacement active" (DOC-48 §4.2/§4.3), and the
369 /// shared event must carry that without falling back to free text.
370 #[test]
371 fn workstream_activation_changed_represents_deactivation_with_no_replacement() {
372 let ev = ReplEvent::WorkstreamActivationChanged {
373 new_active_id: None,
374 prior_id: Some("a1b2c3d4".to_string()),
375 };
376 let ReplEvent::WorkstreamActivationChanged {
377 new_active_id,
378 prior_id,
379 } = &ev
380 else {
381 unreachable!()
382 };
383 assert_eq!(*new_active_id, None);
384 assert_eq!(prior_id.as_deref(), Some("a1b2c3d4"));
385 }
386
387 /// `KeyInput` default modifiers must be "nothing held" so a bare
388 /// `KeyCode` translation (Slice 2) doesn't need to construct
389 /// `KeyModifiers` by hand for the common case.
390 #[test]
391 fn key_modifiers_default_to_none_held() {
392 let m = KeyModifiers::default();
393 assert!(!m.ctrl && !m.alt && !m.shift);
394 }
395
396 /// `WorkstreamSummary` is the wire shape `ReplEvent::WorkstreamUpdated`
397 /// carries; a (de)serialization round-trip is the cheapest guarantee
398 /// that later HTTP-transported engines (CodeEngine) can carry it
399 /// without a custom `Serialize` impl. (`StatuslineSegment`/`PickerItem`/
400 /// `CommandDescriptor` round-trip tests moved to `crate::model` — Slice
401 /// 1.5 relocated those types there.)
402 #[test]
403 fn workstream_summary_round_trips_through_json() {
404 let ws = WorkstreamSummary {
405 id: "a1b2c3d4".to_string(),
406 name: "Token rotation".to_string(),
407 };
408 let json = serde_json::to_string(&ws).expect("serialize");
409 assert_eq!(ws, serde_json::from_str(&json).expect("deserialize"));
410 }
411}