Skip to main content

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