trusty-code-tui 0.2.0

Engine-agnostic terminal-UI seam (TuiEngine trait + ReplEvent) shared by trusty-code and trusty-agents interactive REPLs
Documentation
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
//! Tests for `crate::run` (`event_loop`/`run`/`classify`/`spawn_key_reader`/
//! `dispatch_pending`), split into its own file to satisfy the 500-SLOC
//! production-file cap (`scripts/check_line_cap.sh`) — mirrors the precedent
//! set by `crate::app::reduce`/`crate::app::reduce::tests`. Reachable via
//! `crate::run::tests` exactly as an inline `mod tests { ... }` would have
//! been; only the file boundary changed.

use super::*;
use async_trait::async_trait;
use crossterm::event::{
    KeyCode as CtKeyCode, KeyEvent, KeyEventState, KeyModifiers as CtKeyModifiers,
};
use ratatui::backend::TestBackend;
use std::sync::atomic::AtomicUsize;
use std::time::Instant;
use tokio::time::{self, Duration as TokioDuration};

#[derive(Default)]
struct CountingModel {
    events_seen: usize,
    quit: bool,
}

impl TuiModel for CountingModel {
    fn should_quit(&self) -> bool {
        self.quit
    }
}

fn render_counts(f: &mut ratatui::Frame, model: &CountingModel) {
    use ratatui::widgets::Paragraph;
    f.render_widget(Paragraph::new(format!("{}", model.events_seen)), f.area());
}

/// A dummy `TuiEngine` — these tests exercise [`event_loop`] directly
/// (not [`run`]), so no engine method is actually invoked; it exists only
/// to satisfy trait bounds shared with `run`'s signature in case a future
/// test grows to call it.
struct NoopEngine;

#[async_trait]
impl TuiEngine for NoopEngine {
    async fn handle_input(
        &self,
        _line: String,
        _tx: UnboundedSender<ReplEvent>,
    ) -> anyhow::Result<bool> {
        Ok(true)
    }

    async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
        Ok(())
    }
}

fn key_event(code: CtKeyCode, kind: KeyEventKind) -> KeyEvent {
    KeyEvent {
        code,
        modifiers: CtKeyModifiers::NONE,
        kind,
        state: KeyEventState::NONE,
    }
}

#[test]
fn classify_maps_key_press_and_repeat() {
    let press = classify(CtEvent::Key(key_event(
        CtKeyCode::Char('a'),
        KeyEventKind::Press,
    )));
    assert!(matches!(press, Some(ReplEvent::Key(_))));

    let repeat = classify(CtEvent::Key(key_event(
        CtKeyCode::Char('a'),
        KeyEventKind::Repeat,
    )));
    assert!(matches!(repeat, Some(ReplEvent::Key(_))));
}

#[test]
fn classify_filters_key_release() {
    let release = classify(CtEvent::Key(key_event(
        CtKeyCode::Char('a'),
        KeyEventKind::Release,
    )));
    assert_eq!(
        release, None,
        "Release must not fire a second ReplEvent::Key"
    );
}

#[test]
fn classify_maps_resize() {
    assert_eq!(
        classify(CtEvent::Resize(120, 40)),
        Some(ReplEvent::Resize(120, 40))
    );
}

#[test]
fn classify_maps_mouse_scroll_up_and_down() {
    let up = classify(CtEvent::Mouse(MouseEvent {
        kind: MouseEventKind::ScrollUp,
        column: 0,
        row: 0,
        modifiers: CtKeyModifiers::NONE,
    }));
    assert_eq!(up, Some(ReplEvent::Scroll(-SCROLL_DELTA)));

    let down = classify(CtEvent::Mouse(MouseEvent {
        kind: MouseEventKind::ScrollDown,
        column: 0,
        row: 0,
        modifiers: CtKeyModifiers::NONE,
    }));
    assert_eq!(down, Some(ReplEvent::Scroll(SCROLL_DELTA)));
}

#[test]
fn classify_ignores_other_mouse_events() {
    let moved = classify(CtEvent::Mouse(MouseEvent {
        kind: MouseEventKind::Moved,
        column: 0,
        row: 0,
        modifiers: CtKeyModifiers::NONE,
    }));
    assert_eq!(moved, None);
}

/// The regression test for the shutdown hang: [`spawn_key_reader`]'s
/// returned guard must join promptly on `Drop` WITHOUT needing a
/// keystroke to unblock a `read()` call. Bounded to a few multiples of
/// [`KEY_POLL_INTERVAL`] with generous headroom so this stays reliable
/// across real TTYs (where `poll` genuinely waits out the interval) and
/// TTY-less sandboxes (where `poll` errors immediately) alike — the
/// prior blocking-`read()` design had no such bound at all.
#[test]
fn key_reader_guard_drop_completes_promptly_without_a_keypress() {
    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let guard = spawn_key_reader(tx);

    let start = Instant::now();
    drop(guard);
    let elapsed = start.elapsed();

    assert!(
        elapsed < Duration::from_secs(2),
        "KeyReaderGuard::drop must not block on a keystroke; took {:?}",
        elapsed
    );
}

#[tokio::test]
async fn event_loop_applies_events_and_redraws() {
    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).expect("construct terminal");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();

    tx.send(ReplEvent::StatusMessage("one".into())).unwrap();
    tx.send(ReplEvent::StatusMessage("two".into())).unwrap();
    drop(tx); // closes the channel so the loop exits after both events

    let model = event_loop(
        &mut terminal,
        CountingModel::default(),
        rx,
        |m, _ev| {
            m.events_seen += 1;
        },
        render_counts,
    )
    .await
    .expect("event_loop must succeed");

    assert_eq!(model.events_seen, 2);
}

#[tokio::test]
async fn event_loop_stops_when_model_requests_quit() {
    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).expect("construct terminal");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();

    // Send far more events than we expect to be processed — the loop
    // must stop as soon as `should_quit()` flips, not drain the channel.
    for _ in 0..10 {
        tx.send(ReplEvent::Cancel).unwrap();
    }

    let model = event_loop(
        &mut terminal,
        CountingModel::default(),
        rx,
        |m, _ev| {
            m.events_seen += 1;
            if m.events_seen == 1 {
                m.quit = true;
            }
        },
        render_counts,
    )
    .await
    .expect("event_loop must succeed");

    assert_eq!(
        model.events_seen, 1,
        "must stop at the first quit-triggering event"
    );
}

/// #8240's render-desync regression. One `terminal.draw` per event is what
/// made the pane fall minutes behind a streaming turn: `crate::layout::draw`
/// rebuilds the whole transcript per frame, so the loop could not keep up
/// with the arrival rate and the backlog grew without bound. Every event
/// must still be applied, in order — only the frames nobody could have seen
/// are skipped. Pre-fix this drew 52 times for 50 events; post-fix it draws
/// a handful, independent of the burst size.
#[tokio::test]
async fn event_loop_coalesces_a_burst_into_one_redraw() {
    const BURST: usize = 50;

    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).expect("construct terminal");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();

    for i in 0..BURST {
        tx.send(ReplEvent::StatusMessage(format!("chunk {i}")))
            .expect("queue the burst before the loop starts");
    }
    drop(tx); // the loop exits once the backlog is drained

    let redraws = Arc::new(AtomicUsize::new(0));
    let redraws_in_render = redraws.clone();

    let model = event_loop(
        &mut terminal,
        CountingModel::default(),
        rx,
        |m, _ev| m.events_seen += 1,
        move |f, m| {
            redraws_in_render.fetch_add(1, Ordering::SeqCst);
            render_counts(f, m);
        },
    )
    .await
    .expect("event_loop must succeed");

    assert_eq!(
        model.events_seen, BURST,
        "coalescing must drop nothing — every event still reaches `apply`"
    );
    let drawn = redraws.load(Ordering::SeqCst);
    assert!(
        drawn < BURST,
        "a burst of {BURST} events must not cost {BURST} frames; drew {drawn}"
    );
}

/// The drain must honour `should_quit` mid-backlog, exactly as the one-event-
/// per-frame loop did — a `Quit` sitting third in the queue stops the loop
/// there rather than applying the seven events behind it (#8240).
#[tokio::test]
async fn event_loop_stops_draining_at_a_quit() {
    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).expect("construct terminal");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();

    for _ in 0..10 {
        tx.send(ReplEvent::StatusMessage("x".into())).unwrap();
    }

    let model = event_loop(
        &mut terminal,
        CountingModel::default(),
        rx,
        |m, _ev| {
            m.events_seen += 1;
            if m.events_seen == 3 {
                m.quit = true;
            }
        },
        render_counts,
    )
    .await
    .expect("event_loop must succeed");

    assert_eq!(
        model.events_seen, 3,
        "the drain must stop at the quit, not finish the backlog"
    );
}

#[tokio::test]
async fn event_loop_stops_when_channel_closes() {
    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).expect("construct terminal");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
    drop(tx);

    let model = event_loop(
        &mut terminal,
        CountingModel::default(),
        rx,
        |m, _ev| m.events_seen += 1,
        render_counts,
    )
    .await
    .expect("event_loop must succeed even with zero events");

    assert_eq!(model.events_seen, 0);
    assert!(!model.quit);
}

#[tokio::test(start_paused = true)]
async fn event_loop_redraws_on_tick_even_without_events() {
    let backend = TestBackend::new(20, 5);
    let mut terminal = Terminal::new(backend).expect("construct terminal");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();

    let redraw_count = Arc::new(AtomicUsize::new(0));
    let redraw_count_in_render = redraw_count.clone();

    // Quit after the 3rd tick-driven redraw so the loop terminates
    // deterministically under paused time.
    let handle = tokio::spawn(async move {
        event_loop(
            &mut terminal,
            CountingModel::default(),
            rx,
            move |m, _ev| m.events_seen += 1,
            move |f, m| {
                redraw_count_in_render.fetch_add(1, Ordering::SeqCst);
                render_counts(f, m);
            },
        )
        .await
    });

    // Let the initial draw happen, then advance paused time past three
    // tick intervals; each tick redraws without needing an event.
    time::sleep(TokioDuration::from_millis(1)).await;
    for _ in 0..3 {
        time::advance(TICK).await;
    }
    // One more advance so the final scheduled tick actually fires before
    // we close the channel and let the loop exit on `None`.
    time::advance(TICK).await;
    drop(tx);

    let _model = handle
        .await
        .expect("task must not panic")
        .expect("loop must succeed");
    // Initial draw (1) + at least the ticks we advanced past (4, since a
    // `Skip`-behavior interval still fires once per elapsed period here
    // because we only advance one tick at a time) — assert a lower bound
    // rather than an exact count to avoid coupling the test to
    // `tokio::time::interval`'s internal scheduling.
    assert!(
        redraw_count.load(Ordering::SeqCst) >= 4,
        "expected at least 4 redraws (1 initial + 3 ticks), got {}",
        redraw_count.load(Ordering::SeqCst)
    );
}

/// Compile-time check that `run`'s generic bounds are satisfiable by a
/// real `TuiEngine` + `TuiModel` pair — exercised only for the type
/// signature; `run` itself requires a TTY so it is not called (and not
/// invoked) here, only referenced in a dead-code path the compiler still
/// has to type-check.
#[allow(dead_code)]
async fn run_type_checks(engine: Arc<NoopEngine>) -> anyhow::Result<()> {
    run(
        engine,
        CountingModel::default(),
        |m: &mut CountingModel, _ev| m.events_seen += 1,
        render_counts,
    )
    .await
}

// ─────────────────────────────────────────────────────────────────────────
// `dispatch_pending` — Slice 5 (DOC-50 §5): the Ctrl-C → engine.cancel_session
// / Submit → engine.handle_input wiring. Uses `crate::app::ReplApp` (the
// real `TuiModel` these methods exist for) plus a `MockEngine` that records
// which methods were called, rather than `CountingModel` above (which never
// overrides `take_pending_submit`/`take_pending_cancel`, so it can't exercise
// this path at all).
// ─────────────────────────────────────────────────────────────────────────

use crate::app::{ChatRole, ReplApp, apply as app_apply};
use crate::event::{KeyCode, KeyInput, KeyModifiers};
use crate::model::CancelReply;
use std::sync::atomic::AtomicU64;
use tokio::sync::Notify;

#[derive(Default)]
struct MockEngine {
    cancel_calls: AtomicUsize,
    handle_input_calls: AtomicUsize,
    /// When set, `handle_input` returns this instead of `Ok(true)` — lets a
    /// test exercise the `Ok(false)` → `ReplEvent::Quit` relay.
    handle_input_returns_quit: AtomicBool,
    /// When `Some`, `handle_input` sends one `AssistantOutput` chunk, sets
    /// [`Self::chunk_sent`], and then blocks on this `Notify` before
    /// returning — a controllable await point so a test can prove the task
    /// is genuinely mid-poll (parked at an `.await`, not merely spawned-and-
    /// never-scheduled) at the moment it gets aborted. `None` (the default)
    /// keeps every other test's fire-and-return-immediately behavior
    /// unchanged. See issue raised on PR #3477: the original
    /// `dispatch_pending_cancel_aborts_in_flight_submit_task` proved nothing
    /// because a `MockEngine` with no internal `.await` is never actually
    /// polled by a current-thread runtime before `abort()` lands, making
    /// "genuinely interrupted" indistinguishable from "never started".
    hold_until: Option<Arc<Notify>>,
    /// Set by `handle_input` immediately after sending its chunk and before
    /// waiting on [`Self::hold_until`] — a test polls this (not a fixed
    /// sleep) to know the task has reached its await point.
    chunk_sent: AtomicBool,
    /// Set by `handle_input` only AFTER `hold_until`'s wait resolves — never
    /// set at all if the task is aborted while parked there. A test that
    /// observes `chunk_sent == true` (task genuinely reached the await
    /// point) followed by `completed` staying `false` forever (even after
    /// further scheduling opportunities, with `notify` never released) has
    /// proven the task was truly interrupted mid-flight, not merely
    /// unpolled.
    completed: AtomicBool,
    /// When set, `handle_input` sends only a `StatusMessage` (no
    /// `AssistantOutput`/`Quit` at all) and returns `Ok(true)` — the real
    /// `/workstream list` shape (`crates/trusty-code/src/tui_client/
    /// engine_state.rs::handle_workstream_command`) that originally left
    /// `busy` stuck forever.
    send_status_only: AtomicBool,
    /// When set, `handle_input` sends nothing at all and returns `Err(...)`
    /// — exercises the error-completion path.
    returns_err: AtomicBool,
    /// Every `(request_id, answer)` pair `respond_permission` was handed
    /// (#3422), in call order.
    permission_answers: StdMutex<Vec<(String, crate::model::PermissionAnswer)>>,
    /// When set, `respond_permission` records the call and then returns
    /// `Err(...)` — the wedged/disconnected-backend shape (#3422), where the
    /// answer never reaches the suspended call.
    respond_permission_returns_err: AtomicBool,
    /// When `Some`, `cancel_session_reply` sets [`Self::cancel_dispatched`] and
    /// then blocks on this `Notify` before answering (#8207) — the held-open
    /// cancel future a test needs in order to observe the unconfirmed window at
    /// all, rather than only the state after the reply has already landed.
    hold_cancel_until: Option<Arc<Notify>>,
    /// Set by `cancel_session_reply` immediately before it waits on
    /// [`Self::hold_cancel_until`] — polled (not slept on) by a test that needs
    /// the RPC to have genuinely started.
    cancel_dispatched: AtomicBool,
    /// What `cancel_session_reply` answers once released (#8207). `None` — the
    /// default — answers [`CancelReply::Stopped`], the confirmed stop.
    cancel_reply: StdMutex<Option<CancelReply>>,
}

#[async_trait]
impl TuiEngine for MockEngine {
    async fn handle_input(
        &self,
        _line: String,
        tx: UnboundedSender<ReplEvent>,
    ) -> anyhow::Result<bool> {
        self.handle_input_calls.fetch_add(1, Ordering::SeqCst);
        if let Some(notify) = &self.hold_until {
            let _ = tx.send(ReplEvent::AssistantOutput {
                chunk: "partial".to_string(),
                done: false,
                is_error: false,
            });
            self.chunk_sent.store(true, Ordering::SeqCst);
            notify.notified().await;
            self.completed.store(true, Ordering::SeqCst);
        }
        if self.returns_err.load(Ordering::SeqCst) {
            return Err(anyhow::anyhow!("mock engine failure"));
        }
        if self.send_status_only.load(Ordering::SeqCst) {
            let _ = tx.send(ReplEvent::StatusMessage("workstreams: a, b, c".to_string()));
        }
        Ok(!self.handle_input_returns_quit.load(Ordering::SeqCst))
    }

    async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
        Ok(())
    }

    /// #8207: the dispatch layer calls this, not `cancel_session` — the
    /// one-state form cannot express "accepted, not stopped yet", which is the
    /// whole point of the fix. Left un-overridden so the double also proves the
    /// trait default is reachable for an engine that has no two-state cancel.
    async fn cancel_session_reply(&self) -> CancelReply {
        self.cancel_calls.fetch_add(1, Ordering::SeqCst);
        if let Some(notify) = &self.hold_cancel_until {
            self.cancel_dispatched.store(true, Ordering::SeqCst);
            notify.notified().await;
        }
        self.cancel_reply
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
            .unwrap_or(CancelReply::Stopped)
    }

    async fn respond_permission(
        &self,
        request_id: String,
        answer: crate::model::PermissionAnswer,
    ) -> anyhow::Result<()> {
        self.permission_answers
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push((request_id, answer));
        if self.respond_permission_returns_err.load(Ordering::SeqCst) {
            return Err(anyhow::anyhow!("mock respond_permission failure"));
        }
        Ok(())
    }
}

/// Shorthand for a fresh generation counter — every dispatch-layer test
/// starts its own `run()`-equivalent state from scratch.
fn new_generation() -> Generation {
    Arc::new(AtomicU64::new(0))
}

fn ctrl_c() -> ReplEvent {
    ReplEvent::Key(KeyInput {
        code: KeyCode::Char('c'),
        modifiers: KeyModifiers {
            ctrl: true,
            alt: false,
            shift: false,
        },
    })
}

/// The acceptance criterion this whole slice exists for: pressing Ctrl-C
/// must reach the engine's cancel, not just clear local UI state (thin-client
/// axiom, DOC-50 §5 Slice 5). Drives the real reducer (`crate::app::apply`) so
/// this proves the FULL path — key press to `pending_cancel` to
/// `dispatch_pending` to the engine — not just `dispatch_pending` in isolation.
/// #8207 moved the dispatched method to `cancel_session_reply`, the only one
/// that can report whether the run actually stopped.
#[tokio::test]
async fn dispatch_pending_cancel_reaches_cancel_session_reply() {
    let engine = Arc::new(MockEngine::default());
    let mut app = ReplApp::new("demo", "u");
    app.busy = true;

    app_apply(&mut app, ctrl_c());
    assert!(app.pending_cancel, "reducer must stage pending_cancel");

    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    assert!(!app.pending_cancel, "must be drained synchronously");
    // #8207: `busy` deliberately survives the request — only the reply clears
    // it. See `TuiModel::on_cancel_requested`.
    assert!(
        app.cancelling,
        "the request must enter the cancelling state"
    );
    assert!(app.busy, "input stays closed until the cancel is confirmed");

    // The RPC itself runs on a spawned task; wait for it to actually run
    // rather than asserting immediately after `dispatch_pending` returns.
    for _ in 0..200 {
        if engine.cancel_calls.load(Ordering::SeqCst) > 0 {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert_eq!(
        engine.cancel_calls.load(Ordering::SeqCst),
        1,
        "Ctrl-C must reach engine.cancel_session_reply() exactly once"
    );
}

/// Drive one cancel through the real reducer and dispatch layer, then wait for
/// the spawned RPC to have genuinely started (#8207).
async fn dispatch_cancel(
    app: &mut ReplApp,
    engine: &Arc<MockEngine>,
    tx: &UnboundedSender<ReplEvent>,
    current_task: &CurrentTask,
    generation: &Generation,
) {
    app_apply(app, ctrl_c());
    dispatch_pending(app, engine, tx, current_task, generation);
    for _ in 0..500 {
        if engine.cancel_dispatched.load(Ordering::SeqCst) {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert!(
        engine.cancel_dispatched.load(Ordering::SeqCst),
        "the cancel RPC must be in flight, or this test proves nothing"
    );
}

/// Drain the next event off `rx` and apply it, failing if none arrives.
async fn next_event(app: &mut ReplApp, rx: &mut UnboundedReceiver<ReplEvent>) -> ReplEvent {
    for _ in 0..500 {
        if let Ok(ev) = rx.try_recv() {
            app_apply(app, ev.clone());
            return ev;
        }
        tokio::task::yield_now().await;
    }
    panic!("no event reached the render loop");
}

fn scrollback(app: &ReplApp) -> String {
    app.chat
        .iter()
        .map(|l| l.text.as_str())
        .collect::<Vec<_>>()
        .join("\n")
}

/// #8207's headline regression, driven through the real dispatch layer with the
/// cancel future HELD OPEN: for the whole window between the Ctrl-C and the
/// reply, the TUI shows a cancelling state (not "cancelled"), refuses to accept
/// a turn, and — the closure condition — sends nothing to the engine, so the
/// daemon never answers `-32003 already has a task running`. Releasing the
/// future then confirms the stop and reopens input.
///
/// A test that only inspected the final state would pass against the pre-fix
/// code, which reported "cancelled" on request; the window is the whole point.
#[tokio::test]
async fn dispatch_pending_cancel_holds_input_until_the_reply_lands() {
    let notify = Arc::new(Notify::new());
    let engine = Arc::new(MockEngine {
        hold_cancel_until: Some(Arc::clone(&notify)),
        ..Default::default()
    });
    let mut app = ReplApp::new("demo", "u");
    app.busy = true;
    let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    dispatch_cancel(&mut app, &engine, &tx, &current_task, &generation).await;

    // The unconfirmed window.
    assert!(
        !app.accepts_submit(),
        "input must stay closed while the cancel is unconfirmed"
    );
    let text = scrollback(&app);
    assert!(text.contains("cancelling"), "{text}");
    assert!(
        !text.contains("cancelled"),
        "nothing may claim the run stopped before the reply: {text}"
    );

    app_apply(&mut app, ReplEvent::Submit("q".to_string()));
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    for _ in 0..200 {
        tokio::task::yield_now().await;
    }
    assert_eq!(
        engine.handle_input_calls.load(Ordering::SeqCst),
        0,
        "a prompt submitted inside the cancel window must never reach the engine"
    );

    // The daemon confirms the stop.
    notify.notify_one();
    let ev = next_event(&mut app, &mut rx).await;
    assert_eq!(ev, ReplEvent::CancelSettled(CancelReply::Stopped));
    assert!(app.accepts_submit(), "a confirmed stop reopens input");
    assert!(scrollback(&app).contains("cancelled"));
}

/// #8207: the daemon's `-32010` answer (`CancelReply::StillCancelling`) reaches
/// the pane as a plain sentence and leaves the cancelling state in place — input
/// must NOT reopen as if the run had stopped, and no code may appear.
#[tokio::test]
async fn dispatch_pending_cancel_still_cancelling_keeps_input_closed() {
    let engine = Arc::new(MockEngine {
        hold_cancel_until: Some(Arc::new(Notify::new())),
        cancel_reply: StdMutex::new(Some(CancelReply::StillCancelling {
            detail: "session s-1: cancellation requested but the task did not stop within 10s"
                .to_string(),
        })),
        ..Default::default()
    });
    let mut app = ReplApp::new("demo", "u");
    app.busy = true;
    let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    dispatch_cancel(&mut app, &engine, &tx, &current_task, &generation).await;
    if let Some(notify) = &engine.hold_cancel_until {
        notify.notify_one();
    }
    next_event(&mut app, &mut rx).await;

    assert!(
        !app.accepts_submit(),
        "an unconfirmed cancel must not reopen input"
    );
    let text = scrollback(&app);
    assert!(text.contains("still cancelling"), "{text}");
    assert!(!text.contains("cancelled"), "{text}");
    assert!(!text.contains("-32010"), "{text}");
}

/// #8207's fail-open check at the dispatch layer: a cancel that fails outright
/// (here via the trait default lifting an `Err`) must read as a failure, must
/// not say "cancelled", and must not leave the pane cancelling forever.
#[tokio::test]
async fn dispatch_pending_cancel_failure_never_reports_cancelled() {
    let engine = Arc::new(MockEngine {
        hold_cancel_until: Some(Arc::new(Notify::new())),
        cancel_reply: StdMutex::new(Some(CancelReply::Failed {
            error: "no tcode daemon is answering on /tmp/tcode.sock".to_string(),
        })),
        ..Default::default()
    });
    let mut app = ReplApp::new("demo", "u");
    app.busy = true;
    let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    dispatch_cancel(&mut app, &engine, &tx, &current_task, &generation).await;
    if let Some(notify) = &engine.hold_cancel_until {
        notify.notify_one();
    }
    next_event(&mut app, &mut rx).await;

    assert!(!app.cancelling, "the pane must not stay cancelling forever");
    let text = scrollback(&app);
    assert!(text.contains("cancel failed"), "{text}");
    assert!(
        !text.contains("cancelled"),
        "no failure arm may report cancelled: {text}"
    );
}

/// #3422's acceptance criterion at the dispatch layer: answering the prompt
/// must reach `TuiEngine::respond_permission` with the matching answer, since
/// only the backend can release the suspended tool call. Drives the real
/// reducer so this proves the full path — event, key press, staged answer,
/// dispatch, engine — not `dispatch_pending` in isolation.
#[tokio::test]
async fn dispatch_pending_permission_answer_reaches_respond_permission() {
    let engine = Arc::new(MockEngine::default());
    let mut app = ReplApp::new("demo", "u");
    app_apply(
        &mut app,
        ReplEvent::PermissionRequested {
            request_id: "req-1".to_string(),
            agent: "python-engineer".to_string(),
            agent_id: "spawn-1".to_string(),
            tool: "bash".to_string(),
            subject: "rm -rf build".to_string(),
            rule: "bash[rm *]".to_string(),
        },
    );
    app_apply(
        &mut app,
        ReplEvent::Key(KeyInput {
            code: KeyCode::Char('a'),
            modifiers: KeyModifiers::default(),
        }),
    );
    assert!(
        app.pending_permission_response.is_some(),
        "reducer must stage the answer"
    );

    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    assert!(
        app.pending_permission_response.is_none(),
        "must be drained synchronously"
    );
    assert_eq!(
        generation.load(Ordering::SeqCst),
        0,
        "an answer releases a held call; it starts no turn"
    );

    for _ in 0..200 {
        if !engine
            .permission_answers
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .is_empty()
        {
            break;
        }
        tokio::task::yield_now().await;
    }
    let answers = engine
        .permission_answers
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    assert_eq!(
        answers,
        vec![(
            "req-1".to_string(),
            crate::model::PermissionAnswer::AllowForSession { pattern: None }
        )],
        "the answer must reach the engine verbatim, exactly once"
    );
}

/// #3422: a `respond_permission` RPC that FAILS must reopen the prompt. The
/// prompt closes optimistically the moment a key is pressed (the keyboard
/// must not freeze on a slow backend), so a failed relay otherwise leaves
/// the operator with no prompt while the tool call stays suspended on the
/// backend until it times out — the answer becomes unreachable. Drives the
/// real reducer over the event the dispatch layer publishes, so this proves
/// the whole failure path rather than the spawned task in isolation.
#[tokio::test]
async fn dispatch_pending_permission_answer_failure_reopens_the_prompt() {
    let engine = Arc::new(MockEngine::default());
    engine
        .respond_permission_returns_err
        .store(true, Ordering::SeqCst);
    let mut app = ReplApp::new("demo", "u");
    app_apply(
        &mut app,
        ReplEvent::PermissionRequested {
            request_id: "req-1".to_string(),
            agent: "python-engineer".to_string(),
            agent_id: "spawn-1".to_string(),
            tool: "bash".to_string(),
            subject: "rm -rf build".to_string(),
            rule: "bash[rm *]".to_string(),
        },
    );
    app_apply(
        &mut app,
        ReplEvent::Key(KeyInput {
            code: KeyCode::Char('y'),
            modifiers: KeyModifiers::default(),
        }),
    );
    assert!(
        app.pending_permission.is_none(),
        "answering closes the prompt optimistically"
    );

    let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    // Poll the real condition (the relay task publishing its failure), not a
    // fixed sleep — same shape as the success test above.
    let mut published = None;
    for _ in 0..200 {
        if let Ok(ev) = rx.try_recv() {
            published = Some(ev);
            break;
        }
        tokio::task::yield_now().await;
    }
    let published = published.expect("a failed respond_permission must publish an event");
    app_apply(&mut app, published);

    assert_eq!(
        app.pending_permission
            .as_ref()
            .expect("the prompt must reopen so the answer can be retried")
            .request_id,
        "req-1",
        "the reopened prompt must be the one that failed to send"
    );
    let transcript = app
        .chat
        .iter()
        .map(|l| l.text.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        transcript.contains("mock respond_permission failure"),
        "the status line must name the failure: {transcript}"
    );
}

/// `ReplEvent::Submit`/Enter staging a line must reach
/// `TuiEngine::handle_input`.
#[tokio::test]
async fn dispatch_pending_submit_reaches_handle_input() {
    let engine = Arc::new(MockEngine::default());
    let mut app = ReplApp::new("demo", "u");
    app_apply(&mut app, ReplEvent::Submit("hello".to_string()));
    assert_eq!(app.pending_submit.as_deref(), Some("hello"));

    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    assert!(
        app.pending_submit.is_none(),
        "must be drained synchronously"
    );

    for _ in 0..200 {
        if engine.handle_input_calls.load(Ordering::SeqCst) > 0 {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert_eq!(engine.handle_input_calls.load(Ordering::SeqCst), 1);
}

/// `handle_input` returning `Ok(false)` must relay `ReplEvent::Quit` onto
/// the channel so the render loop's next `apply` sets `ReplApp::quit` —
/// the only way a spawned task can reach model state it doesn't own.
#[tokio::test]
async fn dispatch_pending_submit_ok_false_relays_quit_event() {
    let engine = Arc::new(MockEngine::default());
    engine
        .handle_input_returns_quit
        .store(true, Ordering::SeqCst);
    let mut app = ReplApp::new("demo", "u");
    app_apply(&mut app, ReplEvent::Submit("bye".to_string()));

    let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    let ev = rx.recv().await.expect("Quit event must be sent");
    assert_eq!(ev, ReplEvent::Quit);
}

/// A cancel dispatched while a submit task is GENUINELY in flight (parked
/// mid-`.await`, proven via `MockEngine::chunk_sent` — not merely spawned
/// and never polled, the gap a code-review pass on PR #3477 caught in an
/// earlier revision of this test) must abort that task's `JoinHandle`.
/// Proof of genuine interruption: `chunk_sent` becoming `true` shows the
/// task reached its await point; `completed` staying `false` — even after
/// further scheduling opportunities and WITHOUT ever releasing `notify` —
/// shows it never resumed past that point, i.e. it was truly cancelled, not
/// merely "replaced in the slot" while still running to completion
/// unobserved. Mirrors tagent's `current_task` abort-on-cancel precedent
/// (`crates/trusty-agents/src/repl/tui/events.rs`).
#[tokio::test]
async fn dispatch_pending_cancel_aborts_genuinely_in_flight_submit_task() {
    let notify = Arc::new(Notify::new());
    let engine = Arc::new(MockEngine {
        hold_until: Some(Arc::clone(&notify)),
        ..Default::default()
    });
    let mut app = ReplApp::new("demo", "u");
    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    app_apply(&mut app, ReplEvent::Submit("long task".to_string()));
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    assert!(
        current_task.lock().unwrap().is_some(),
        "submit must stash a JoinHandle in current_task"
    );

    // Wait for genuine proof the task is parked at its await point (sent its
    // chunk, now blocked on `notify`) — not a fixed sleep, and not merely
    // "spawned".
    for _ in 0..500 {
        if engine.chunk_sent.load(Ordering::SeqCst) {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert!(
        engine.chunk_sent.load(Ordering::SeqCst),
        "task must reach its await point before we cancel it, or this test proves nothing"
    );

    app.busy = true;
    app_apply(&mut app, ctrl_c());
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    assert!(
        current_task.lock().unwrap().is_none(),
        "cancel must take (and abort) the stashed handle"
    );
    // #8207: the request enters the cancelling state; `busy` is the reply's to
    // clear.
    assert!(
        app.cancelling,
        "the request must enter the cancelling state"
    );

    // The decisive check: release the gate the (supposedly aborted) task
    // was parked on. If `abort()` genuinely worked, the task is already gone
    // and this is a no-op — `completed` can never become `true`. If abort
    // were silently ineffective (the bug this test guards against), the
    // task would still be alive, wake up, and complete.
    notify.notify_one();
    for _ in 0..500 {
        tokio::task::yield_now().await;
    }
    assert!(
        !engine.completed.load(Ordering::SeqCst),
        "an aborted task must never resume past its await point, even when its wait condition is satisfied afterward"
    );
}

/// Neither `handle_input` nor `cancel_session` is called when nothing was
/// staged — `dispatch_pending` must be a true no-op on an idle model,
/// matching every plain keystroke (insert/backspace/cursor-move) that
/// doesn't set either pending flag.
#[tokio::test]
async fn dispatch_pending_noop_when_nothing_pending() {
    let engine = Arc::new(MockEngine::default());
    let mut app = ReplApp::new("demo", "u");
    app_apply(
        &mut app,
        ReplEvent::Key(KeyInput {
            code: KeyCode::Char('h'),
            modifiers: KeyModifiers::default(),
        }),
    );

    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    // Give any wrongly-spawned task a chance to run before asserting.
    tokio::task::yield_now().await;
    assert_eq!(engine.cancel_calls.load(Ordering::SeqCst), 0);
    assert_eq!(engine.handle_input_calls.load(Ordering::SeqCst), 0);
}

/// FIX 2 (generation tagging, PR #3477 review): a message already sitting in
/// a turn's private channel — sent before a cancel bumped the live
/// generation past that turn's own number, exactly the race `abort()` only
/// taking effect at the next `.await` creates (an already-queued chunk
/// survives the abort itself) — must be dropped by
/// [`forward_while_current_generation`], never relayed onto the real
/// channel where it would render as a fresh reply to a request the user
/// already cancelled.
///
/// Deliberately tests [`forward_while_current_generation`] directly rather
/// than through `dispatch_pending`'s spawned tasks: whether a real spawned
/// forwarder drains a message before or after a concurrent generation bump
/// is itself a scheduling race (forwarding it BEFORE the bump is correct —
/// the chunk was legitimately live when sent), so asserting "never forwarded"
/// against the full spawned pipeline is nondeterministic by construction. The
/// actual invariant this crate guarantees is narrower and fully
/// deterministic: ANY message the forwarder has not yet drained by the time
/// `generation` no longer matches its turn gets dropped when the forwarder
/// finally gets to it — which is exactly what direct, un-raced construction
/// below proves.
#[tokio::test]
async fn forward_while_current_generation_drops_stale_generation_message() {
    let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let (real_tx, mut real_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let generation: Generation = Arc::new(AtomicU64::new(5));

    // A message sent while generation 5 was still live...
    turn_tx
        .send(ReplEvent::AssistantOutput {
            chunk: "partial".to_string(),
            done: false,
            is_error: false,
        })
        .unwrap();
    // ...but by the time anyone drains it, a cancel has already bumped the
    // live generation to 6 — turn 5 is now stale, exactly what
    // `dispatch_pending`'s cancel branch does before `abort()` runs.
    generation.store(6, Ordering::SeqCst);
    drop(turn_tx); // no more messages; the forwarder runs to completion

    forward_while_current_generation(turn_rx, real_tx, generation, 5, no_terminal_flag()).await;

    assert!(
        real_rx.try_recv().is_err(),
        "a message tagged for a superseded generation must never reach the real channel"
    );
}

/// Symmetric companion to the drop test above: a message whose generation
/// still matches the live one must be forwarded normally — the mechanism
/// must not become a black hole for ordinary, un-cancelled turns.
#[tokio::test]
async fn forward_while_current_generation_forwards_matching_generation_message() {
    let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let (real_tx, mut real_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let generation: Generation = Arc::new(AtomicU64::new(1));

    turn_tx
        .send(ReplEvent::AssistantOutput {
            chunk: "hello".to_string(),
            done: true,
            is_error: false,
        })
        .unwrap();
    drop(turn_tx);

    forward_while_current_generation(turn_rx, real_tx, generation, 1, no_terminal_flag()).await;

    let ev = real_rx
        .try_recv()
        .expect("matching-generation message must forward");
    assert_eq!(
        ev,
        ReplEvent::AssistantOutput {
            chunk: "hello".to_string(),
            done: true,
            is_error: false,
        }
    );
}

/// Shorthand for a fresh, unset `saw_terminal` flag — most forwarder tests
/// don't care about it.
fn no_terminal_flag() -> Arc<AtomicBool> {
    Arc::new(AtomicBool::new(false))
}

/// The stuck-`busy` fix's load-bearing signal: relaying a terminal
/// `AssistantOutput { done: true, .. }` must flip `saw_terminal`.
#[tokio::test]
async fn forward_while_current_generation_flags_terminal_assistant_output() {
    let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let (real_tx, _real_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let generation: Generation = Arc::new(AtomicU64::new(1));
    let saw_terminal = Arc::new(AtomicBool::new(false));

    turn_tx
        .send(ReplEvent::AssistantOutput {
            chunk: "done".to_string(),
            done: true,
            is_error: false,
        })
        .unwrap();
    drop(turn_tx);

    forward_while_current_generation(turn_rx, real_tx, generation, 1, Arc::clone(&saw_terminal))
        .await;

    assert!(saw_terminal.load(Ordering::SeqCst));
}

/// `Quit` also counts as a terminal signal.
#[tokio::test]
async fn forward_while_current_generation_flags_quit() {
    let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let (real_tx, _real_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let generation: Generation = Arc::new(AtomicU64::new(1));
    let saw_terminal = Arc::new(AtomicBool::new(false));

    turn_tx.send(ReplEvent::Quit).unwrap();
    drop(turn_tx);

    forward_while_current_generation(turn_rx, real_tx, generation, 1, Arc::clone(&saw_terminal))
        .await;

    assert!(saw_terminal.load(Ordering::SeqCst));
}

/// Non-terminal events (`StatusMessage`, a non-`done` `AssistantOutput`
/// chunk) must NOT flip `saw_terminal` — this is exactly the `/workstream
/// list` shape (`StatusMessage`/`WorkstreamUpdated` only) that originally
/// left `busy` stuck.
#[tokio::test]
async fn forward_while_current_generation_does_not_flag_non_terminal_events() {
    let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let (real_tx, mut real_rx) = mpsc::unbounded_channel::<ReplEvent>();
    let generation: Generation = Arc::new(AtomicU64::new(1));
    let saw_terminal = Arc::new(AtomicBool::new(false));

    turn_tx
        .send(ReplEvent::StatusMessage("workstream list: ...".to_string()))
        .unwrap();
    turn_tx
        .send(ReplEvent::AssistantOutput {
            chunk: "still streaming".to_string(),
            done: false,
            is_error: false,
        })
        .unwrap();
    drop(turn_tx);

    forward_while_current_generation(turn_rx, real_tx, generation, 1, Arc::clone(&saw_terminal))
        .await;

    assert!(!saw_terminal.load(Ordering::SeqCst));
    // Both messages still forward normally — only the flag is unaffected.
    assert!(real_rx.try_recv().is_ok());
    assert!(real_rx.try_recv().is_ok());
}

/// FIX 1 (busy-gating) at the dispatch layer: while a turn is in flight, a
/// second `Submit` must never reach `TuiEngine::handle_input` a second time.
/// `ReplApp::submit_line`'s own busy guard means `pending_submit` never gets
/// staged for the second attempt, so `dispatch_pending` has nothing to
/// dispatch — this is the direct fix for the double-submit corruption
/// (task B's chunks splicing into task A's orphaned `streaming_idx` entry)
/// a code-review pass caught on PR #3477.
#[tokio::test]
async fn dispatch_pending_second_submit_while_busy_does_not_start_second_task() {
    let engine = Arc::new(MockEngine::default());
    let mut app = ReplApp::new("demo", "u");
    let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    app_apply(&mut app, ReplEvent::Submit("explain X".to_string()));
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    for _ in 0..200 {
        if engine.handle_input_calls.load(Ordering::SeqCst) > 0 {
            break;
        }
        tokio::task::yield_now().await;
    }
    assert_eq!(engine.handle_input_calls.load(Ordering::SeqCst), 1);
    assert!(app.busy, "first submit must leave the app busy");

    // Second submit attempt while still busy: the reducer refuses to stage
    // it at all (`ReplApp::submit_line`'s guard), so there is nothing for
    // `dispatch_pending` to dispatch.
    app_apply(&mut app, ReplEvent::Submit("explain Y".to_string()));
    assert!(app.pending_submit.is_none(), "must not stage a second turn");
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);

    tokio::task::yield_now().await;
    assert_eq!(
        engine.handle_input_calls.load(Ordering::SeqCst),
        1,
        "a second submit while busy must never reach handle_input"
    );
}

// ─────────────────────────────────────────────────────────────────────────
// Stuck-`busy` deadlock regression tests (re-review fix on PR #3477): FIX 1
// (busy-gating) means the ONLY way out of a stuck `busy = true` is a
// terminal signal reaching the reducer. These drive the REAL channel
// end-to-end through the REAL reducer (`app_apply`) — the gap the review
// found in the original `dispatch_pending_*` tests, which only asserted on
// `handle_input_calls`/`pending_submit`, never on `busy` actually clearing.
// ─────────────────────────────────────────────────────────────────────────

/// Drain `rx` to close (all sender clones dropped) through the REAL reducer,
/// bounded so a regression that reintroduces the deadlock fails the test
/// instead of hanging CI forever.
async fn drain_all_and_apply(app: &mut ReplApp, mut rx: UnboundedReceiver<ReplEvent>) {
    tokio::time::timeout(Duration::from_secs(5), async {
        while let Some(ev) = rx.recv().await {
            app_apply(app, ev);
        }
    })
    .await
    .expect("channel must close — a stuck task would hang this instead");
}

/// The exact bug the re-review found: `handle_input` returns `Ok(true)`
/// having sent ZERO events at all (the real `/workstream list`/`activate`
/// shape, `crates/trusty-code/src/tui_client/engine_state.rs::
/// handle_workstream_command`, which only pushes `StatusMessage`/
/// `WorkstreamUpdated` for other command variants — this is the minimal
/// repro: nothing at all). Before the fix, `busy` stayed `true` forever and
/// `ReplApp::submit_line`'s FIX 1 guard meant the user could never submit
/// again.
#[tokio::test]
async fn dispatch_pending_ok_true_with_no_terminal_output_still_clears_busy() {
    let engine = Arc::new(MockEngine::default());
    let mut app = ReplApp::new("demo", "u");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    app_apply(&mut app, ReplEvent::Submit("do a thing".to_string()));
    assert!(app.busy, "submit must mark busy");
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    drop(tx);

    drain_all_and_apply(&mut app, rx).await;

    assert!(
        !app.busy,
        "busy must clear even when handle_input sends zero events"
    );
}

/// The `/workstream list` shape more precisely: `Ok(true)` with only a
/// `StatusMessage` (no `AssistantOutput`/`Quit` ever produced).
#[tokio::test]
async fn dispatch_pending_ok_true_with_only_status_message_still_clears_busy() {
    let engine = Arc::new(MockEngine {
        send_status_only: AtomicBool::new(true),
        ..Default::default()
    });
    let mut app = ReplApp::new("demo", "u");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    app_apply(&mut app, ReplEvent::Submit("/workstream list".to_string()));
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    drop(tx);

    drain_all_and_apply(&mut app, rx).await;

    assert!(
        !app.busy,
        "busy must clear when handle_input only ever sends a StatusMessage"
    );
}

/// The `Err(e)` completion path: must ALSO clear `busy` (not just the
/// `Ok(true)`-with-no-terminal path) AND surface a visible error rather than
/// failing silently — a silent error that also locks input is the same
/// class of bug.
#[tokio::test]
async fn dispatch_pending_err_clears_busy_and_surfaces_visible_error() {
    let engine = Arc::new(MockEngine {
        returns_err: AtomicBool::new(true),
        ..Default::default()
    });
    let mut app = ReplApp::new("demo", "u");
    let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
    let current_task: CurrentTask = Arc::new(StdMutex::new(None));
    let generation = new_generation();

    app_apply(&mut app, ReplEvent::Submit("boom".to_string()));
    dispatch_pending(&mut app, &engine, &tx, &current_task, &generation);
    drop(tx);

    drain_all_and_apply(&mut app, rx).await;

    assert!(!app.busy, "busy must clear on engine error");
    assert!(
        app.chat
            .iter()
            .any(|line| line.role == ChatRole::Error && line.text.contains("mock engine failure")),
        "the error must be surfaced as a visible chat entry, not silently swallowed"
    );
}