trusty_code_tui/run/mod.rs
1//! The shared render/event loop (Slice 2, #3414).
2//!
3//! Why: DOC-50 §2.2 puts the event loop itself in `trusty-code-tui` so tagent and
4//! tcode stop each owning a bespoke copy — this module is the shared engine
5//! that shape lives in, generalized from the proven design in
6//! `crates/trusty-agents/src/repl/tui/run.rs::event_loop` (100ms redraw tick,
7//! `tokio::select!` over the tick and the event channel, a dedicated OS
8//! thread for the key read so it never parks the tokio runtime).
9//!
10//! What: three pieces. [`spawn_key_reader`] is the OS thread that polls for
11//! crossterm events and forwards translated [`ReplEvent`]s (key presses via
12//! [`crate::keys::translate_key_event`], resizes, mouse-wheel scroll) onto an
13//! `mpsc` channel; it returns a [`KeyReaderGuard`] rather than a bare
14//! `JoinHandle` (see that type's doc comment for why). [`event_loop`] is the
15//! terminal-generic `tick`/`recv` select loop — generic over
16//! `ratatui::backend::Backend` (not just `CrosstermBackend`) specifically so
17//! it can be unit-tested against `ratatui::backend::TestBackend` without a
18//! real TTY. [`run`] is the opinionated top-level entry point that wires a
19//! [`TerminalGuard`], the key reader, and an `E: TuiEngine` together the way
20//! a real product binary actually wants to call this crate.
21//!
22//! Deliberately NOT decided here: what `M` (the render/reducer model) looks
23//! like inside a product. Slice 4 owns the shared chat/statusline/picker
24//! widgets and the concrete model they render from; this module only needs
25//! to know when to redraw (every tick or every event) and when to stop
26//! (`M::should_quit`). That is the full contract `apply`/`render`/[`TuiModel`]
27//! below capture — deliberately mirroring `crates/trusty-agents/src/repl/tui/run.rs::event_loop`'s
28//! `app: Arc<Mutex<ReplApp>>` + `draw(f, &snap)` + `process_event` shape,
29//! generalized to not require `Arc<Mutex<_>>` (the caller decides its own
30//! interior mutability, if any).
31//!
32//! A prior revision of [`run`] blocked `crossterm::event::read()` directly on
33//! the key-reader thread and shut it down with `drop(tx); thread.join()`.
34//! That hangs: `read()` only notices the channel closed on its NEXT `send()`,
35//! which can't happen until a key is actually pressed — and by the time `run`
36//! reaches shutdown, the user has usually just pressed the key that made
37//! `should_quit()` true, so the thread is parked in a SECOND, indefinite
38//! `read()`. Worse, the terminal restore ran after that join, so the
39//! terminal stayed frozen in raw/alt-screen mode with no feedback while
40//! hung. It also leaked the thread entirely on the `engine.setup`/
41//! `subscribe_workstream_events` error paths, which returned via `?` before
42//! ever reaching the join. [`KeyReaderGuard`] and the restructured [`run`]
43//! fix both: the thread polls with a bounded timeout and checks an atomic
44//! stop flag every poll, and terminal restoration happens unconditionally,
45//! before the (now-bounded) thread join, on every exit path.
46//!
47//! # Spec References
48//! - [`SPEC-TTUI-05~draft`](../../../docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 2 deliverable (§5, Slice 2): the event loop.
49
50use std::sync::atomic::{AtomicBool, Ordering};
51use std::sync::{Arc, Mutex as StdMutex};
52use std::time::Duration;
53
54use crossterm::event::{self, Event as CtEvent, KeyEventKind, MouseEvent, MouseEventKind};
55use ratatui::Terminal;
56use ratatui::backend::Backend;
57use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
58
59use crate::engine::TuiEngine;
60use crate::event::ReplEvent;
61use crate::keys::translate_key_event;
62use crate::terminal::TerminalGuard;
63
64/// How often [`event_loop`] redraws when no event arrives.
65///
66/// Why: matches the tick cadence in
67/// `crates/trusty-agents/src/repl/tui/run.rs::event_loop` — fast enough for a
68/// smoothly animating spinner/elapsed-time display, cheap enough (a full diff
69/// against an idle frame) not to burn meaningful CPU.
70pub const TICK: Duration = Duration::from_millis(100);
71
72/// How often the key-reader thread's `crossterm::event::poll` call returns so
73/// it can re-check [`KeyReaderGuard`]'s stop flag.
74///
75/// Why: this bounds `KeyReaderGuard::drop`'s join to roughly one interval
76/// after shutdown is requested, instead of the prior blocking-`read()`
77/// design's "whenever the user next happens to press a key" (see the module
78/// doc comment). Short enough that shutdown feels immediate; long enough not
79/// to busy-loop.
80const KEY_POLL_INTERVAL: Duration = Duration::from_millis(100);
81
82/// Mouse-wheel scroll delta per notch, matching tagent's existing convention
83/// (`crates/trusty-agents/src/repl/tui/run.rs`): negative scrolls toward
84/// older history, positive toward newer.
85const SCROLL_DELTA: isize = 3;
86
87/// A render/reducer model the shared [`event_loop`]/[`run`] can drive
88/// without knowing its concrete shape.
89///
90/// Why: [`event_loop`] needs exactly one piece of information it cannot get
91/// from `ReplEvent` alone — whether the model just decided to quit (e.g. the
92/// user typed `/quit`, hit `Ctrl-D`, or the engine returned `Ok(false)` from
93/// `handle_input`). [`run`] (Slice 5, DOC-50 §5) needs two more: whether
94/// `apply` just staged a line to submit or a cancel signal to relay, so it
95/// can dispatch both to `TuiEngine` without `event_loop` itself needing to
96/// know `TuiEngine` exists (keeping `event_loop` terminal-generic and
97/// testable against `TestBackend` with no engine at all — see that
98/// function's doc comment). Everything else about `M` stays opaque to this
99/// crate; Slice 4 defines the real model ([`crate::app::ReplApp`]).
100/// What: three methods, all defaulted so a minimal `TuiModel` (like this
101/// module's own test-only `CountingModel`) compiles unchanged — only
102/// `should_quit` is required to mean anything for [`event_loop`] alone to
103/// work; the pending-take methods only matter to callers that go through
104/// [`run`]'s engine-dispatch wrapper.
105/// Test: [`crate::app::ReplApp`]'s implementation is exercised via
106/// `crate::app::reduce::tests`; this module's own dispatch wiring is
107/// exercised in `tests::dispatch_pending` below.
108pub trait TuiModel {
109 /// Whether the render loop should exit after the current frame.
110 fn should_quit(&self) -> bool;
111
112 /// Take the line staged by `apply` for `TuiEngine::handle_input`, if any.
113 ///
114 /// Why: `apply` (a synchronous `FnMut(&mut M, ReplEvent)`) cannot itself
115 /// call an `async fn` on the engine, so it stages the line on `M`
116 /// instead (mirrors [`crate::app::ReplApp::pending_submit`]); [`run`]
117 /// drains it right after `apply` returns and dispatches it.
118 /// What: a drain-on-read `Option::take`-shaped accessor. Default `None`
119 /// — a model with nothing to submit (or one not wired through [`run`]
120 /// at all) needs no override.
121 fn take_pending_submit(&mut self) -> Option<String> {
122 None
123 }
124
125 /// Take-and-clear the cancel signal staged by `apply` (Ctrl-C, or Up-
126 /// arrow while busy), if any.
127 ///
128 /// Why: same shape as [`Self::take_pending_submit`], for
129 /// `TuiEngine::cancel_session` instead of `handle_input`.
130 /// What: default `false` — a model with no cancellation concept needs no
131 /// override.
132 fn take_pending_cancel(&mut self) -> bool {
133 false
134 }
135
136 /// Called by [`run`]'s dispatch step immediately after a drained cancel
137 /// signal, before the `cancel_session` call is even dispatched.
138 ///
139 /// Why: the actual `TuiEngine::cancel_session` RPC is async and runs on
140 /// a spawned task (so a slow/hung backend never freezes the render
141 /// loop), but the visible "busy" state should clear the moment the user
142 /// asked to cancel, not whenever the RPC eventually resolves — direct
143 /// parity with tagent's real cancel path
144 /// (`crates/trusty-agents/src/repl/tui/events.rs::process_event`), which
145 /// resets `thinking`/`busy_since` synchronously, before `h.abort()` even
146 /// runs. DOC-50 §5 Slice 5's "blocks user input until cancel completes"
147 /// is implemented literally, not reasoned away: `crate::app::ReplApp`'s
148 /// `submit_line` refuses a second turn while `busy` is `true`
149 /// ([`crate::app::ReplApp::submit_line`]'s doc comment), so this method
150 /// clearing `busy` is exactly the moment new input becomes acceptable
151 /// again — before that, Enter/Submit is a genuine no-op, not merely
152 /// cosmetically blocked. [`dispatch_pending`] separately bumps the
153 /// generation counter in the SAME cancel branch this method is called
154 /// from, so any output still in flight from the just-cancelled turn is
155 /// dropped rather than rendered once it eventually arrives (see that
156 /// function's doc comment for the generation mechanism).
157 /// What: default no-op — a model with no busy/streaming state to reset
158 /// needs no override.
159 fn on_cancelled(&mut self) {}
160
161 /// Record the generation number [`dispatch_pending`] just assigned to a
162 /// new turn (submit) or bumped past (cancel), so a later
163 /// `ReplEvent::TurnFinished { generation }` can compare against it.
164 ///
165 /// Why: a prior revision had `dispatch_pending`'s spawned completion
166 /// task load the live `AtomicU64` generation counter and compare it to
167 /// its own turn's number before deciding whether to send
168 /// `TurnFinished` — a genuine TOCTOU race under multi-threaded tokio
169 /// (a cancel and a new submit could both run in the gap between that
170 /// load and the send, so a stale terminal signal from turn N could
171 /// clear `busy`/`streaming_idx` for a genuinely in-flight turn N+2).
172 /// Fixed by construction instead of narrowing the window: this method
173 /// is called from `dispatch_pending` ONLY on the single serial
174 /// event-loop task (the same task `apply`/the reducer run on, and the
175 /// same task that owns the `AtomicU64` bump) — so a model tracking its
176 /// own copy of "the current generation" lets the REDUCER do the
177 /// comparison with no cross-thread race possible at all, rather than a
178 /// spawned task racing a shared counter.
179 /// What: default no-op — a model with no generation concept (or one not
180 /// wired through [`run`]) needs no override.
181 fn set_current_generation(&mut self, generation: u64) {
182 let _ = generation;
183 }
184}
185
186/// Pure classification of one crossterm `Event` into an optional [`ReplEvent`].
187///
188/// Why: pulled out of [`spawn_key_reader`]'s thread body specifically so it
189/// is unit-testable without a real TTY or `crossterm::event::read()` — the
190/// thread itself is a thin loop that calls this once per polled event.
191/// What: filters `Key` events to `Press`/`Repeat` only, dropping `Release`
192/// (some terminals — notably on Windows — emit key-release events crossterm
193/// surfaces there; tagent's precedent drops them so a single physical
194/// keystroke doesn't fire twice) and translating the rest via
195/// [`translate_key_event`]. `Resize` passes straight through. Mouse-wheel
196/// `ScrollUp`/`ScrollDown` map to [`ReplEvent::Scroll`]. Everything else
197/// (other mouse events, focus/paste events depending on which crossterm
198/// event kinds are enabled) yields `None`.
199/// Test: [`tests::classify_filters_key_release`],
200/// [`tests::classify_maps_key_press_and_repeat`],
201/// [`tests::classify_maps_resize`],
202/// [`tests::classify_maps_mouse_scroll_up_and_down`],
203/// [`tests::classify_ignores_other_mouse_events`].
204fn classify(ev: CtEvent) -> Option<ReplEvent> {
205 match ev {
206 CtEvent::Key(k) => {
207 if k.kind != KeyEventKind::Press && k.kind != KeyEventKind::Repeat {
208 None
209 } else {
210 Some(ReplEvent::Key(translate_key_event(k)))
211 }
212 }
213 CtEvent::Resize(cols, rows) => Some(ReplEvent::Resize(cols, rows)),
214 CtEvent::Mouse(MouseEvent {
215 kind: MouseEventKind::ScrollUp,
216 ..
217 }) => Some(ReplEvent::Scroll(-SCROLL_DELTA)),
218 CtEvent::Mouse(MouseEvent {
219 kind: MouseEventKind::ScrollDown,
220 ..
221 }) => Some(ReplEvent::Scroll(SCROLL_DELTA)),
222 _ => None,
223 }
224}
225
226/// RAII handle for the key-reader thread spawned by [`spawn_key_reader`].
227///
228/// Why: a bare `JoinHandle` let every fallible step between spawning the
229/// thread and the function's tail cleanup code leak it — `engine.setup`/
230/// `subscribe_workstream_events` returning via `?` skipped straight past the
231/// `drop(tx); thread.join()` lines that used to live at the end of [`run`].
232/// Wrapping the handle in a type whose `Drop` does that join means EVERY
233/// exit path — success, an early `?`, or an unwinding panic — cleans the
234/// thread up, the same guarantee [`TerminalGuard`] gives the terminal itself.
235/// What: holds the thread's `JoinHandle` plus an `Arc<AtomicBool>` stop flag
236/// the thread polls every [`KEY_POLL_INTERVAL`]. `Drop` sets the flag then
237/// joins — bounded to roughly one poll interval, not "whenever the user
238/// next presses a key" (the shutdown hang described in the module doc
239/// comment).
240/// Test: `tests::key_reader_guard_drop_completes_promptly_without_a_keypress`.
241pub struct KeyReaderGuard {
242 stop: Arc<AtomicBool>,
243 handle: Option<std::thread::JoinHandle<()>>,
244}
245
246impl Drop for KeyReaderGuard {
247 /// Why: see [`KeyReaderGuard`] — runs on every exit path, including a
248 /// panic unwind, which is the entire reason this type exists rather than
249 /// a bare `JoinHandle` cleaned up by hand at the end of `run`.
250 /// What: signals the stop flag, then joins — the thread notices within
251 /// one [`KEY_POLL_INTERVAL`] because its loop condition checks the flag
252 /// on every iteration, not just when a `send()` fails.
253 fn drop(&mut self) {
254 self.stop.store(true, Ordering::Relaxed);
255 if let Some(handle) = self.handle.take() {
256 let _ = handle.join();
257 }
258 }
259}
260
261/// Spawn the dedicated OS thread that polls for crossterm events and forwards
262/// translated events onto `tx`, returning a [`KeyReaderGuard`] that stops and
263/// joins it on drop.
264///
265/// Why: crossterm's blocking read is happiest on its own OS thread rather
266/// than parking a tokio worker — matches
267/// `crates/trusty-agents/src/repl/tui/run.rs`'s `key_thread`. Polling (rather
268/// than that precedent's blocking `read()`) is what makes shutdown bounded
269/// instead of tied to the next physical keystroke — see the module doc
270/// comment for the hang this replaces.
271/// What: loops `crossterm::event::poll(KEY_POLL_INTERVAL)` until the stop
272/// flag is set, `poll`/`read` errors (e.g. no input reader available, which
273/// is expected in a TTY-less sandbox and simply ends the loop), or `tx.send`
274/// fails (the receiver dropped). Each polled event is classified by
275/// [`classify`]; `None` results (filtered keys, unhandled mouse events) are
276/// silently dropped.
277/// Test: `tests::key_reader_guard_drop_completes_promptly_without_a_keypress`
278/// proves the returned guard's `Drop` doesn't block on a keystroke; the
279/// event-classification logic itself is covered directly via [`classify`]'s
280/// tests (no TTY needed for those).
281pub fn spawn_key_reader(tx: UnboundedSender<ReplEvent>) -> KeyReaderGuard {
282 let stop = Arc::new(AtomicBool::new(false));
283 let stop_for_thread = Arc::clone(&stop);
284 let handle = std::thread::spawn(move || {
285 while !stop_for_thread.load(Ordering::Relaxed) {
286 match event::poll(KEY_POLL_INTERVAL) {
287 Ok(true) => match event::read() {
288 Ok(ev) => {
289 if let Some(replay) = classify(ev)
290 && tx.send(replay).is_err()
291 {
292 break;
293 }
294 }
295 Err(_) => break,
296 },
297 Ok(false) => continue, // timed out — loop back and re-check `stop`
298 Err(_) => break,
299 }
300 }
301 });
302 KeyReaderGuard {
303 stop,
304 handle: Some(handle),
305 }
306}
307
308/// The terminal-generic tick/event select loop.
309///
310/// Why: split out from [`run`] specifically so it can be exercised in tests
311/// against `ratatui::backend::TestBackend` — `run` itself requires a real
312/// TTY (via [`TerminalGuard::enter`]) and so cannot run in CI/sandboxes.
313/// What: draws once immediately, then loops a biased `tokio::select!` between
314/// the [`TICK`] interval (redraw only) and `rx.recv()` (apply the event via
315/// `apply`, then redraw). Exits when `model.should_quit()` becomes true or
316/// `rx` closes (all senders dropped — mirrors
317/// `crates/trusty-agents/src/repl/tui/run.rs::event_loop`'s `None => return
318/// Ok(())`). Returns the final model so callers/tests can inspect it.
319/// Test: `tests::event_loop_applies_events_and_redraws`,
320/// `tests::event_loop_stops_when_model_requests_quit`,
321/// `tests::event_loop_stops_when_channel_closes`,
322/// `tests::event_loop_redraws_on_tick_even_without_events`.
323pub async fn event_loop<B, M>(
324 terminal: &mut Terminal<B>,
325 mut model: M,
326 mut rx: UnboundedReceiver<ReplEvent>,
327 mut apply: impl FnMut(&mut M, ReplEvent),
328 mut render: impl FnMut(&mut ratatui::Frame, &M),
329) -> anyhow::Result<M>
330where
331 B: Backend,
332 B::Error: std::error::Error + Send + Sync + 'static,
333 M: TuiModel,
334{
335 terminal.draw(|f| render(f, &model))?;
336
337 let mut tick = tokio::time::interval(TICK);
338 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
339
340 loop {
341 tokio::select! {
342 biased;
343 _ = tick.tick() => {
344 terminal.draw(|f| render(f, &model))?;
345 if model.should_quit() {
346 return Ok(model);
347 }
348 }
349 ev = rx.recv() => {
350 match ev {
351 Some(ev) => {
352 apply(&mut model, ev);
353 terminal.draw(|f| render(f, &model))?;
354 if model.should_quit() {
355 return Ok(model);
356 }
357 }
358 None => return Ok(model),
359 }
360 }
361 }
362 }
363}
364
365/// The top-level entry point: enter the terminal, spawn the key reader, run
366/// `engine.setup`/`subscribe_workstream_events`, drive [`event_loop`] to
367/// completion, then restore the terminal and call `engine.shutdown`.
368///
369/// Why: bundles the pieces every real product binary needs in the order
370/// tagent's `run_tui` already proves out, but routed through [`TerminalGuard`]
371/// and [`KeyReaderGuard`] so a panic OR an early `?` anywhere in
372/// `engine.setup`/`subscribe_workstream_events`/`apply`/`render` still
373/// restores the terminal and stops the key-reader thread — see the module
374/// doc comment for the hang and the leak this fixes relative to a prior
375/// revision.
376/// What: generic over `E: TuiEngine` (Slice 1's adapter trait) and `M:
377/// TuiModel` (this module's minimal render/reducer contract) so it drives
378/// either tagent's future adapter or tcode's. The fallible setup + the event
379/// loop itself run inside one `async` block so `run` always reaches its two
380/// explicit `drop()` calls afterward, in a fixed order, regardless of which
381/// step inside failed: `guard` (terminal restore) drops FIRST — never gated
382/// behind the thread join — then `key_guard` (bounded to roughly
383/// [`KEY_POLL_INTERVAL`]) drops second. `engine.shutdown`'s error is logged,
384/// not propagated, mirroring `TuiEngine::shutdown`'s own doc comment
385/// ("errors are logged, not fatal").
386/// Test: requires a real TTY (via `TerminalGuard::enter`) so it is not
387/// unit-tested directly — the terminal-generic core it delegates to
388/// ([`event_loop`]) carries the loop's test coverage, and [`TerminalGuard`]/
389/// [`KeyReaderGuard`]'s own tests cover the panic-safety and prompt-shutdown
390/// contracts this function relies on.
391/// The in-flight `handle_input` task, if any — `std::sync::Mutex` (not
392/// `tokio::sync::Mutex`) because [`dispatch_pending`] only ever locks it
393/// synchronously (take-and-abort, or store-and-replace), never across an
394/// `.await`, so the cheaper std primitive is correct and avoids an
395/// accidental `.await` inside the lock.
396type CurrentTask = Arc<StdMutex<Option<tokio::task::JoinHandle<()>>>>;
397
398/// The current turn's generation number.
399///
400/// Why: `JoinHandle::abort()` only takes effect at the aborted task's NEXT
401/// `.await` point — a chunk the engine already pushed onto its `tx` clone
402/// BEFORE the abort request lands is already sitting in a channel buffer,
403/// unaffected by the abort. Without a way to mark that chunk "stale", it
404/// still gets forwarded to the render loop and rendered — a real bug a
405/// code-review pass on PR #3477 caught: cancelling turn N doesn't stop turn
406/// N's already-in-flight output from being drawn as a fresh reply once it
407/// eventually arrives. This counter is the fix: every NEW submitted turn
408/// gets the next generation number, cancelling bumps it too (invalidating
409/// whatever generation was in flight even if nothing is found to abort), and
410/// [`dispatch_pending`]'s per-turn forwarder (see that function) drops any
411/// event whose turn's generation no longer matches the live one before it
412/// ever reaches `tx` / the reducer.
413/// What: a plain `Arc<AtomicU64>` — `SeqCst` throughout since this is a
414/// low-frequency, cross-task correctness flag, not a hot path worth a
415/// weaker ordering.
416type Generation = Arc<std::sync::atomic::AtomicU64>;
417
418/// Drain `turn_rx` and forward each event onto `real_tx`, but ONLY while
419/// `generation` still equals `my_gen` — the per-turn forwarder [`Generation`]'s
420/// doc comment describes. Pulled out of [`dispatch_pending`] as its own
421/// function specifically so it is unit-testable in complete isolation from
422/// real task scheduling: a test can pre-populate `turn_rx` with a message,
423/// bump `generation` past `my_gen` (simulating "a cancel already happened"),
424/// then run this function to completion and assert nothing reached
425/// `real_tx` — deterministic, no race against when a spawned task happens to
426/// get polled relative to another.
427/// Why: exits on its own once every `turn_tx` clone (held by the
428/// `handle_input` task in [`dispatch_pending`]) drops and `turn_rx.recv()`
429/// returns `None` — normal completion or `abort()` both drop that clone, so
430/// nothing leaks this task.
431/// What: no special handling needed for the mismatched-generation branch
432/// beyond "don't forward" — silently dropping is the correct, documented
433/// behavior (rendering stale output from an already-cancelled turn would be
434/// the bug, not the silence). `saw_terminal` is flipped to `true` whenever a
435/// relayed (generation still matching) event is `AssistantOutput { done:
436/// true, .. }` or `Quit` — [`dispatch_pending`]'s completion step reads it,
437/// after this function has fully drained, to detect a `handle_input` that
438/// returned `Ok(true)` without ever producing a terminal signal (see
439/// `ReplEvent::TurnFinished`'s doc comment for the stuck-`busy` deadlock
440/// that gap causes). A message dropped for generation mismatch does NOT set
441/// `saw_terminal` — that turn was already superseded/cancelled, and
442/// `TuiModel::on_cancelled` already reset `busy` for it independently.
443/// Test: [`tests::forward_while_current_generation_drops_stale_generation_message`],
444/// [`tests::forward_while_current_generation_forwards_matching_generation_message`],
445/// [`tests::forward_while_current_generation_flags_terminal_assistant_output`],
446/// [`tests::forward_while_current_generation_flags_quit`],
447/// [`tests::forward_while_current_generation_does_not_flag_non_terminal_events`].
448async fn forward_while_current_generation(
449 mut turn_rx: UnboundedReceiver<ReplEvent>,
450 real_tx: UnboundedSender<ReplEvent>,
451 generation: Generation,
452 my_gen: u64,
453 saw_terminal: Arc<AtomicBool>,
454) {
455 while let Some(ev) = turn_rx.recv().await {
456 if generation.load(Ordering::SeqCst) == my_gen {
457 if matches!(
458 &ev,
459 ReplEvent::AssistantOutput { done: true, .. } | ReplEvent::Quit
460 ) {
461 saw_terminal.store(true, Ordering::SeqCst);
462 }
463 let _ = real_tx.send(ev);
464 }
465 }
466}
467
468/// Drain whatever [`TuiModel::take_pending_submit`]/
469/// [`TuiModel::take_pending_cancel`] report on `model` (staged by the
470/// caller's `apply` immediately before this runs) and dispatch each to
471/// `engine`, per DOC-50 §5 Slice 5's `process_event(event, app, handler)`
472/// deliverable — generalized here to two drains instead of one dispatch
473/// function, matching this crate's `pending_submit`/`pending_cancel` split
474/// (see [`crate::app::reduce`]'s doc comment) rather than tagent's single
475/// `Option<String>` return.
476///
477/// Why: `apply` is a synchronous `FnMut`, so it cannot itself `.await`
478/// `TuiEngine::handle_input`/`cancel_session` — this is the seam that picks
479/// up where `apply` stopped, mirroring tagent's `process_event`
480/// (`crates/trusty-agents/src/repl/tui/events.rs`): spawn `handle_input` on
481/// its own task (so the render loop keeps redrawing while a request is in
482/// flight) and stash the `JoinHandle` in `current_task` so a later cancel
483/// can abort it — same `current_task: Arc<Mutex<Option<JoinHandle<()>>>>`
484/// shape tagent uses, adapted to `std::sync::Mutex` since nothing here holds
485/// the lock across an `.await`.
486///
487/// **Generation tagging (see [`Generation`]):** every submit is assigned the
488/// next generation number and gets its OWN private `mpsc` channel
489/// (`turn_tx`/`turn_rx`) instead of the shared `tx` directly — `engine.
490/// handle_input` is handed `turn_tx`, and a second, small forwarder task
491/// drains `turn_rx` and re-sends each event onto the real `tx` ONLY while
492/// `generation` still equals the turn's own number; once superseded
493/// (cancelled), the forwarder silently drops everything still queued for
494/// that turn instead of relaying it. This works without changing
495/// `TuiEngine::handle_input`'s signature at all (it still receives a plain
496/// `UnboundedSender<ReplEvent>`) and without adding a generation field to
497/// `ReplEvent` itself (irrelevant to `event.rs`'s public shape, so Slice 6/7
498/// engines never need to know this mechanism exists). The forwarder task
499/// exits on its own once every `turn_tx` clone drops (the `handle_input`
500/// task finishing OR being aborted both drop their clone), so nothing leaks.
501///
502/// **Why FIX 1 (busy-gating in `ReplApp::submit_line`) doesn't make this
503/// redundant:** with submits gated, at most one turn is EVER in flight, so
504/// generation mismatches can only happen via cancel (Ctrl-C), never via a
505/// second overlapping submit — but that one case is real and common enough
506/// (any Ctrl-C during a streaming response) that dropping it silently is
507/// still required.
508///
509/// What: cancel is drained and dispatched FIRST — bumps `generation`
510/// (invalidating the in-flight turn's forwarder before anything else
511/// happens), calls [`TuiModel::on_cancelled`] synchronously so the UI's busy
512/// state clears immediately (see that method's doc comment for why), aborts
513/// the stashed `JoinHandle`, then relays `engine.cancel_session()` on its
514/// own task so a slow backend never blocks the render loop. Submit is
515/// drained second: assigned the next generation, any previous task in
516/// `current_task` is aborted (defensive — busy-gating should prevent
517/// overlapping submits, same caveat as tagent's precedent) and replaced.
518/// `Ok(false)` from `handle_input` is relayed back as `ReplEvent::Quit` (the
519/// spawned task can't reach `&mut M` directly — see that variant's doc
520/// comment); an `Err` is relayed as an error-flavored `ReplEvent::
521/// AssistantOutput` chunk, the closest existing vocabulary to tagent's
522/// `LlmResponse { text: format!("error: {e:#}"), is_error: true }`. Both
523/// relays go through the SAME generation-tagged `turn_tx`, so a stale
524/// `Quit`/error from an already-cancelled turn is dropped exactly like a
525/// stale `AssistantOutput` chunk would be.
526///
527/// **Stuck-`busy` safety net (post-review fix, PR #3477):** `ReplApp::busy`
528/// is cleared ONLY by a terminal `AssistantOutput { done: true, .. }`/`Quit`
529/// reaching the reducer — but `handle_input` returning `Ok(true)` is NOT a
530/// guarantee one was ever sent (three real `CodeEngine` paths legitimately
531/// return `Ok(true)` having pushed only a `StatusMessage`/`WorkstreamUpdated`:
532/// `/workstream list`/`activate`, a reconnect-exhausted event pump, and a
533/// daemon-initiated session cancellation). Combined with FIX 1's busy-gating,
534/// that left `busy` stuck forever — input permanently bricked. The fix:
535/// after `handle_input` resolves (`Ok`/`Err`, any branch), the completion
536/// code drops its `turn_tx` clone and awaits the forwarder's `JoinHandle` —
537/// this is the synchronization point that guarantees `saw_terminal`
538/// reflects everything the engine actually sent, not a racy snapshot taken
539/// the instant `handle_input`'s future resolves. If `saw_terminal` is still
540/// `false`, a `ReplEvent::TurnFinished { generation: my_gen }` is sent
541/// unconditionally on the real `tx` — see that variant's doc comment for why
542/// it is a dedicated variant rather than a reused empty `AssistantOutput {
543/// done: true, .. }` (the latter would push a stray blank chat entry via
544/// that event's `None`-`streaming_idx` branch).
545///
546/// **By-construction TOCTOU fix (second re-review round):** an earlier
547/// revision ALSO compared `generation.load(..) == my_gen` on this spawned
548/// task before deciding whether to send `TurnFinished` at all — a genuine
549/// race under multi-threaded tokio (a cancel + a new submit could both run
550/// in the gap between that load and the send, letting a stale terminal from
551/// turn N clear state for a genuinely in-flight turn N+2). Fixed by moving
552/// the comparison into the REDUCER instead of narrowing the window: this
553/// task now always sends `TurnFinished` stamped with its own `my_gen`, and
554/// `dispatch_pending` calls `model.set_current_generation` on THIS (serial,
555/// single event-loop) task at the exact point it bumps `generation` (both
556/// branches above) — so the reducer's later `generation ==
557/// app.current_generation` compare (`ReplApp`'s implementation) runs
558/// serially against a value only ever written from the same task that reads
559/// it back, with no cross-thread race possible at all.
560/// Net invariant: every `handle_input` completion path — `Ok(true)` with a
561/// done chunk, `Ok(true)` with none, `Ok(false)`, and `Err` — deterministically
562/// leaves `busy == false` once no task is in flight, and a stale completion
563/// from a superseded turn never clobbers a newer one.
564/// Test: [`tests::dispatch_pending_submit_reaches_handle_input`],
565/// [`tests::dispatch_pending_cancel_reaches_cancel_session`],
566/// [`tests::dispatch_pending_cancel_aborts_genuinely_in_flight_submit_task`],
567/// [`tests::dispatch_pending_noop_when_nothing_pending`],
568/// [`tests::forward_while_current_generation_drops_stale_generation_message`],
569/// [`tests::dispatch_pending_second_submit_while_busy_does_not_start_second_task`],
570/// [`tests::dispatch_pending_ok_true_with_no_terminal_output_still_clears_busy`],
571/// [`tests::dispatch_pending_ok_true_with_only_status_message_still_clears_busy`],
572/// [`tests::dispatch_pending_err_clears_busy_and_surfaces_visible_error`].
573fn dispatch_pending<E, M>(
574 model: &mut M,
575 engine: &Arc<E>,
576 tx: &UnboundedSender<ReplEvent>,
577 current_task: &CurrentTask,
578 generation: &Generation,
579) where
580 E: TuiEngine + 'static,
581 M: TuiModel,
582{
583 if model.take_pending_cancel() {
584 // Bump FIRST: invalidates the in-flight turn's forwarder before the
585 // abort even runs, so a chunk already sitting in `turn_rx`'s buffer
586 // (pushed before `abort()` takes effect at the task's next
587 // `.await`) is dropped rather than relayed once the forwarder next
588 // polls it. `set_current_generation` runs on THIS (serial,
589 // event-loop) task, same as every reducer `apply` call — see
590 // `TuiModel::set_current_generation`'s doc comment for why that
591 // makes the model's copy of "the live generation" race-free against
592 // a spawned completion task's `TurnFinished` send.
593 let new_gen = generation.fetch_add(1, Ordering::SeqCst) + 1;
594 model.set_current_generation(new_gen);
595 model.on_cancelled();
596 if let Some(handle) = current_task.lock().unwrap().take() {
597 handle.abort();
598 }
599 let engine = Arc::clone(engine);
600 let tx = tx.clone();
601 tokio::spawn(async move {
602 if let Err(e) = engine.cancel_session().await {
603 let _ = tx.send(ReplEvent::StatusMessage(format!("cancel failed: {e:#}")));
604 }
605 });
606 }
607
608 if let Some(line) = model.take_pending_submit() {
609 let my_gen = generation.fetch_add(1, Ordering::SeqCst) + 1;
610 model.set_current_generation(my_gen);
611
612 // Private per-turn channel: `engine.handle_input` only ever sees
613 // `turn_tx`, never the real `tx` — see the doc comment above for why
614 // this is the seam that makes stale output droppable without
615 // touching `TuiEngine`'s signature or `ReplEvent`'s shape.
616 let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
617 let real_tx = tx.clone();
618 let forwarder_generation = Arc::clone(generation);
619 let saw_terminal = Arc::new(AtomicBool::new(false));
620 let forwarder_saw_terminal = Arc::clone(&saw_terminal);
621 let forwarder_handle = tokio::spawn(forward_while_current_generation(
622 turn_rx,
623 real_tx,
624 forwarder_generation,
625 my_gen,
626 forwarder_saw_terminal,
627 ));
628
629 let engine = Arc::clone(engine);
630 let completion_tx = tx.clone();
631 let handle = tokio::spawn(async move {
632 let result = engine.handle_input(line, turn_tx.clone()).await;
633 match &result {
634 Ok(true) => {}
635 Ok(false) => {
636 let _ = turn_tx.send(ReplEvent::Quit);
637 }
638 Err(e) => {
639 // Surface the error as a visible chat entry (also
640 // clears `busy` via `done: true` — see
641 // `apply_assistant_output`) rather than leaving the
642 // failure silent.
643 let _ = turn_tx.send(ReplEvent::AssistantOutput {
644 chunk: format!("error: {e:#}"),
645 done: true,
646 is_error: true,
647 });
648 }
649 }
650 // Drop our own `turn_tx` clone BEFORE awaiting the forwarder:
651 // its channel only closes (and `forward_while_current_generation`
652 // only returns) once every sender clone — including the one
653 // `engine.handle_input` held, already dropped when its future
654 // resolved above — is gone. Awaiting first would deadlock.
655 drop(turn_tx);
656 let _ = forwarder_handle.await;
657 // Safety net: `handle_input` returning `Ok(true)` is not a
658 // guarantee a terminal signal was ever sent (see this
659 // function's doc comment for the real `CodeEngine` paths that
660 // don't). Top one up so `busy` cannot stay stuck forever.
661 //
662 // Deliberately UNCONDITIONAL on the live generation here — no
663 // load-and-compare against the shared `AtomicU64` on this
664 // spawned task. An earlier revision did that compare here,
665 // which was a genuine TOCTOU race under multi-threaded tokio: a
666 // cancel + a new submit could both run in the gap between this
667 // task's load and its send, so a stale `TurnFinished` from turn
668 // N could still clear `busy`/`streaming_idx` for a genuinely
669 // in-flight turn N+2. Fixed by construction instead: this event
670 // always carries `my_gen`, and the REDUCER (serial, same task
671 // that bumps the counter) is what decides whether `generation`
672 // still matches — see `ReplEvent::TurnFinished`'s and
673 // `TuiModel::set_current_generation`'s doc comments.
674 if !saw_terminal.load(Ordering::SeqCst) {
675 let _ = completion_tx.send(ReplEvent::TurnFinished { generation: my_gen });
676 }
677 });
678 let mut slot = current_task.lock().unwrap();
679 if let Some(prev) = slot.take() {
680 prev.abort();
681 }
682 *slot = Some(handle);
683 }
684}
685
686pub async fn run<E, M>(
687 engine: Arc<E>,
688 model: M,
689 mut apply: impl FnMut(&mut M, ReplEvent),
690 render: impl FnMut(&mut ratatui::Frame, &M),
691) -> anyhow::Result<()>
692where
693 E: TuiEngine + 'static,
694 M: TuiModel,
695{
696 let (guard, mut terminal) = TerminalGuard::enter()?;
697 let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
698 let key_guard = spawn_key_reader(tx.clone());
699 let current_task: CurrentTask = Arc::new(StdMutex::new(None));
700 let generation: Generation = Arc::new(std::sync::atomic::AtomicU64::new(0));
701
702 let result: anyhow::Result<M> = async {
703 engine.setup(tx.clone()).await?;
704 engine.subscribe_workstream_events(tx.clone()).await?;
705
706 // Wrap the caller's `apply` so every event still gets the caller's
707 // reducer behavior first, then drains whatever `ReplApp`-shaped
708 // pending state (Slice 5, DOC-50 §5) that reducer just staged and
709 // dispatches it to `engine` — see [`dispatch_pending`] and
710 // [`TuiModel::take_pending_submit`]/[`TuiModel::take_pending_cancel`]
711 // for why this can't live inside `event_loop` itself (kept
712 // engine-agnostic and `TestBackend`-testable).
713 let dispatch_engine = Arc::clone(&engine);
714 let dispatch_tx = tx.clone();
715 let dispatching_apply = move |model: &mut M, ev: ReplEvent| {
716 apply(model, ev);
717 dispatch_pending(
718 model,
719 &dispatch_engine,
720 &dispatch_tx,
721 ¤t_task,
722 &generation,
723 );
724 };
725
726 event_loop(&mut terminal, model, rx, dispatching_apply, render).await
727 }
728 .await;
729
730 // Restore the terminal FIRST and unconditionally — regardless of which
731 // step above failed, and never gated behind the key-reader thread's
732 // join below (that ordering, with an unbounded join, was the shutdown
733 // hang described in the module doc comment).
734 drop(guard);
735 // Signal + join the key-reader thread second. Bounded to roughly
736 // `KEY_POLL_INTERVAL` thanks to `spawn_key_reader`'s poll-based loop, so
737 // this no longer waits for a keystroke that may never come.
738 drop(key_guard);
739
740 if let Err(e) = engine.shutdown().await {
741 tracing::warn!(error = %e, "TuiEngine::shutdown returned an error (non-fatal)");
742 }
743
744 result.map(|_model| ())
745}
746
747#[cfg(test)]
748mod tests;