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