supercode-harness 0.4.10

The optional native Supercode agent and tool harness
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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
//! P5-4 (§2 module 30): the TESTABLE view-model core — a pure `handle_key`
//! (keypress → intended [`Action`]s) plus `apply` (mutate [`TuiState`] for
//! ANY action, whether it came from a keypress or from an interactive
//! handler's request landing on the bridge channels — see
//! [`crate::tui::handlers`]). Neither function touches a terminal; every
//! test in this module drives the whole thing by hand.

use std::collections::VecDeque;

use crate::mcp::{ElicitationAction, ElicitationResponse};
use crate::permissions::ApprovalOutcome;

use super::bridge::{
    PendingApprovalRequest, PendingChildApproval, PendingElicitation, PendingOAuthDisplay,
};
use super::history::PromptHistory;
use super::key::{Key, KeyEvent};
use super::keymap::{Keymap, KeymapAction};
use super::theme::Theme;

/// Who said one transcript line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    /// The human operator.
    User,
    /// The model's own text.
    Assistant,
    /// A tool call/result rendered as chrome (not model-authored text).
    Tool,
    /// A TUI-local notice (a resolved approval, a mode change, …) — never
    /// sent to the model, purely for the human's own record.
    System,
}

/// One line (or block) in the scrollback transcript.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranscriptEntry {
    /// Who said it.
    pub role: Role,
    /// The line's text.
    pub text: String,
}

/// Vim-emulation sub-mode (only consulted when [`TuiState::vim_enabled`] is
/// `true` — see that field's doc comment for the deliberately-basic scope:
/// `hjkl` motion, `i`/`a`/`o` mode entry, `x`/`dd` deletion. This is NOT a
/// full vim emulation (no registers, no visual mode, no `.`-repeat, no
/// counts) — a shippable-complete BASIC modal editor, with full vim cited
/// as a follow-up rather than half-built. See the crate-level `tui` module
/// doc comment's "shippable vs staged" note.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VimMode {
    /// Every key inserts/edits (the default when vim emulation is off, or
    /// the sub-mode `i`/`a`/`o` enter).
    #[default]
    Insert,
    /// Motion/command keys (`h`/`l`/`x`/`d`/…) — the mode `Esc` returns to.
    Normal,
}

/// What the input composer is showing right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InputFocus {
    /// The normal text-entry composer.
    #[default]
    Composer,
    /// Ctrl+R cross-session prompt-history search is live.
    HistorySearch,
}

/// Cross-session prompt-history search state (Ctrl+R), live while
/// [`TuiState::input_focus`] is [`InputFocus::HistorySearch`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HistorySearchState {
    /// What the user has typed to narrow the search.
    pub query: String,
    /// Index into the CURRENT `history.search(query)` result list — `0` is
    /// the most recent match.
    pub selected: usize,
}

/// An interactive modal covering the composer — at most one at a time
/// (§2.28: approval / elicitation / child-approval / OAuth-code-display).
/// A later request queues behind the earlier one still on screen (see
/// `TuiState::modal_queue`) rather than clobbering it.
#[derive(Debug)]
pub enum Modal {
    /// P5-1's `Ask`-tier decision, surfaced interactively (closes the
    /// deferred `tui`-implements-the-ask-UI chain).
    Approval(PendingApprovalRequest),
    /// P5-3 §2.2 C6's queued child approval, now answerable (closes that
    /// deferred chain).
    ChildApproval(PendingChildApproval),
    /// P5-2's MCP `elicitation/create`, with the free-text answer buffer
    /// the (deliberately basic — see the crate doc comment) form widget
    /// accumulates.
    Elicitation {
        /// The server's request (message + schema) plus reply channel.
        request: PendingElicitation,
        /// The free-text answer typed into the modal so far.
        answer: String,
    },
    /// P5-2's OAuth device-code display — no reply, dismiss-only.
    OAuthDeviceCode(PendingOAuthDisplay),
}

/// The status line's contents — deliberately minimal (a renderer decorates
/// this, doesn't reinterpret it).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatusLine {
    /// The active model's display label.
    pub model_label: String,
    /// Whether a turn is currently in flight.
    pub turn_active: bool,
    /// A one-shot notice (e.g. "press Ctrl+C again to exit") — cleared by
    /// the NEXT keypress that doesn't re-arm it, so it never lingers stale.
    pub notice: Option<String>,
}

/// A pure description of a state transition — the output of
/// [`TuiState::handle_key`] and the input to [`TuiState::apply`]. Not
/// `Clone`/`PartialEq`-derived as a whole: the `Show*Modal` variants embed
/// a one-shot reply channel ([`std::sync::mpsc::Sender`]/
/// `tokio::sync::oneshot::Sender`, neither of which is `PartialEq`) — tests
/// assert on the resulting [`TuiState`], not on raw `Action` equality.
#[derive(Debug)]
pub enum Action {
    /// Insert one character at the cursor.
    InsertChar(char),
    /// Delete the character before the cursor.
    Backspace,
    /// Delete the character at (after) the cursor.
    DeleteForward,
    /// Move the cursor one character left.
    MoveLeft,
    /// Move the cursor one character right.
    MoveRight,
    /// Move the cursor to the start of the composer.
    MoveHome,
    /// Move the cursor to the end of the composer.
    MoveEnd,
    /// Insert a newline without submitting (multi-line composing).
    Newline,
    /// Clear the composer buffer without submitting (non-empty-line
    /// Ctrl+C, and vim `dd`).
    ClearComposerLine,
    /// The composer's contents were submitted — `apply` clears the
    /// composer, appends the text to history + the transcript. The CLI
    /// event loop is the one that actually calls `agent.send(text)`; it
    /// sees this variant in `handle_key`'s returned `Vec<Action>` BEFORE
    /// calling `apply` (see the module doc comment on the render layer).
    Submit(String),
    /// Scroll the transcript up one page.
    ScrollUp,
    /// Scroll the transcript down one page.
    ScrollDown,
    /// Toggle the dark/light theme.
    ToggleTheme,
    /// Enter Ctrl+R cross-session prompt-history search.
    OpenHistorySearch,
    /// Type one character into the history-search query.
    HistorySearchType(char),
    /// Delete the last character of the history-search query.
    HistorySearchBackspace,
    /// Select the next (older) matching history entry.
    HistorySearchNext,
    /// Select the previous (more recent) matching history entry.
    HistorySearchPrev,
    /// Accept the selected history entry into the composer.
    HistorySearchConfirm,
    /// Leave history search without changing the composer.
    HistorySearchCancel,
    /// Switch vim sub-mode (Normal/Insert).
    VimSetMode(VimMode),
    /// Vim `h` — move left.
    VimMoveLeft,
    /// Vim `l` — move right.
    VimMoveRight,
    /// Vim `0` — move to line start.
    VimMoveHome,
    /// Vim `$` — move to line end.
    VimMoveEnd,
    /// Vim `x` — delete the character under the cursor.
    VimDeleteChar,
    /// Vim `dd` (approximated as one keystroke — see [`VimMode`]'s doc
    /// comment) — clear the composer line.
    VimDeleteLine,
    /// The CLI layer should shell out to `$EDITOR` — `apply` only flips a
    /// flag ([`TuiState::external_editor_requested`]); the actual process
    /// spawn is terminal I/O, out of the view-model's scope.
    RequestExternalEditor,
    /// The CLI layer's `$EDITOR` invocation finished — replaces the
    /// composer with the edited text.
    ExternalEditorResult(String),
    /// F9 (Fable-5 adversarial review — LOW): the CLI layer's `$EDITOR`
    /// invocation failed to spawn (editor not found, exec error, …) —
    /// clears [`TuiState::external_editor_requested`] (same as
    /// `ExternalEditorResult`, so `run_loop` doesn't keep retrying it
    /// every tick) WITHOUT touching the composer, and surfaces `message`
    /// as a system transcript notice so the session stays alive and the
    /// user actually sees why nothing happened, instead of the whole TUI
    /// process exiting out from under them.
    ExternalEditorFailed(String),
    /// An image was pasted/attached (path or a data reference) — appended
    /// to the composer as a placeholder token and recorded in
    /// [`TuiState::pending_images`] for the CLI layer to route into the
    /// multimodal read path.
    PasteImage(String),
    /// A new top-level `Ask`-tier approval request arrived — show (or
    /// queue) it as a modal.
    ShowApprovalModal(PendingApprovalRequest),
    /// The user resolved the active approval modal.
    ResolveApproval(ApprovalOutcome),
    /// A new background-child approval request arrived — show (or queue)
    /// it as a modal.
    ShowChildApprovalModal(PendingChildApproval),
    /// The user resolved the active child-approval modal.
    ResolveChildApproval(ApprovalOutcome),
    /// A new MCP elicitation request arrived — show (or queue) it as a
    /// modal.
    ShowElicitationModal(PendingElicitation),
    /// Type one character into the elicitation answer buffer.
    ElicitationType(char),
    /// Delete the last character of the elicitation answer buffer.
    ElicitationBackspace,
    /// Accept the elicitation with the typed answer.
    ResolveElicitationAccept,
    /// Decline the elicitation.
    ResolveElicitationDecline,
    /// Cancel/dismiss the elicitation without a decision.
    ResolveElicitationCancel,
    /// A new OAuth device-code display arrived — show (or queue) it.
    ShowOAuthModal(PendingOAuthDisplay),
    /// Dismiss the OAuth device-code modal (no reply — see
    /// [`PendingOAuthDisplay`]'s doc comment).
    DismissOAuthModal,
    /// A chunk of streaming assistant text arrived.
    AppendStreamingDelta(String),
    /// The in-progress streaming turn is done — move it into the
    /// transcript.
    FinalizeStreaming,
    /// Append one entry directly to the transcript (tool events, system
    /// notices raised outside a modal resolution).
    PushTranscript(TranscriptEntry),
    /// Update the status line's model label.
    SetModelLabel(String),
    /// Update the status line's turn-in-flight indicator.
    SetTurnActive(bool),
    /// First Ctrl+C on an empty, non-modal composer — arms the "press
    /// again to exit" notice without quitting yet.
    ArmQuit,
    /// Second consecutive Ctrl+C — actually quit.
    Quit,
    /// A key the current focus/modal doesn't bind to anything — carries no
    /// mutation; `apply` is a no-op for it. `handle_key` prefers returning
    /// an empty `Vec` over this where possible; it exists for the rare
    /// case a caller wants an explicit "nothing happened" marker (e.g. a
    /// disabled modal option).
    Noop,
}

/// The whole TUI view-model — see the module doc comment. Constructed
/// fresh per TUI session by the CLI render layer; every mutation goes
/// through [`Self::apply`].
#[derive(Debug)]
pub struct TuiState {
    /// The composer's current text.
    pub input: String,
    /// Byte offset into `input` — always on a `char` boundary.
    pub cursor: usize,
    /// The scrollback transcript, oldest first.
    pub transcript: Vec<TranscriptEntry>,
    /// In-progress assistant text (streaming) — `None` when no turn is
    /// mid-flight.
    pub streaming: Option<String>,
    /// The currently-showing modal, if any.
    pub modal: Option<Modal>,
    /// Requests that arrived while a modal was already showing — FIFO,
    /// drained into `modal` by [`Self::dequeue_modal`] once the current one
    /// resolves.
    modal_queue: VecDeque<Modal>,
    /// The active display theme.
    pub theme: Theme,
    /// The resolved (default + overrides) keybinding table.
    pub keymap: Keymap,
    /// D8 "vim" — whether modal editing is active at all
    /// ([`crate::Config::tui_vim_mode`]). `false` (the default): every key
    /// is a plain insert/navigate, [`VimMode`] is never consulted.
    pub vim_enabled: bool,
    /// The current vim sub-mode (only meaningful when `vim_enabled`).
    pub vim_mode: VimMode,
    /// The cross-session prompt history.
    pub history: PromptHistory,
    /// Live Ctrl+R search state, if [`Self::input_focus`] is
    /// [`InputFocus::HistorySearch`].
    pub history_search: Option<HistorySearchState>,
    /// What the composer area is currently showing.
    pub input_focus: InputFocus,
    /// The status line's contents.
    pub status: StatusLine,
    /// Current transcript scroll offset (pages back from the bottom).
    pub scroll: usize,
    /// Set once the user has asked to quit — the render loop's exit
    /// signal.
    pub should_quit: bool,
    /// Whether the FIRST of a double-Ctrl+C-to-quit has already landed.
    quit_armed: bool,
    /// Set while the CLI layer's `$EDITOR` invocation is in flight.
    pub external_editor_requested: bool,
    /// Image references pasted into the composer, in submission order —
    /// drained by the CLI layer once it reads [`Action::Submit`].
    pub pending_images: Vec<String>,
    /// Set by `apply(Action::Submit(text))` to `Some(text)` — the CLI event
    /// loop's ONE polling point for "a turn needs to be sent": call
    /// [`Self::take_submission`] after every [`Self::on_key`] (or manual
    /// `apply`) to both read and clear it in one step, so a submission is
    /// never double-sent.
    pub last_submission: Option<String>,
}

impl TuiState {
    /// A fresh, empty state — `theme`/`vim_enabled`/`keymap` typically come
    /// from the resolved [`crate::Config`] (`tui_theme`/`tui_vim_mode`/
    /// `tui_keymap`), `history` from [`PromptHistory::load_from_file`].
    pub fn new(theme: Theme, keymap: Keymap, vim_enabled: bool, history: PromptHistory) -> Self {
        TuiState {
            input: String::new(),
            cursor: 0,
            transcript: Vec::new(),
            streaming: None,
            modal: None,
            modal_queue: VecDeque::new(),
            theme,
            keymap,
            vim_enabled,
            vim_mode: if vim_enabled {
                VimMode::Normal
            } else {
                VimMode::Insert
            },
            history,
            history_search: None,
            input_focus: InputFocus::Composer,
            status: StatusLine::default(),
            scroll: 0,
            should_quit: false,
            quit_armed: false,
            external_editor_requested: false,
            pending_images: Vec::new(),
            last_submission: None,
        }
    }

    /// Convenience for a caller that doesn't need `Default::default()`-style
    /// construction control — plain-mode, dark theme, default keymap, empty
    /// history. Handy for tests and the render layer's smoke-test harness.
    pub fn new_default() -> Self {
        TuiState::new(
            Theme::default(),
            Keymap::default(),
            false,
            PromptHistory::new(),
        )
    }

    /// Translate one keypress into the [`Action`]s it produces — READS
    /// state (to be context-sensitive: a modal open, history-search
    /// active, vim normal-mode all change what a key means) but never
    /// mutates it. Call [`Self::apply`] on each returned action (in order)
    /// to actually realize the transition — the render layer's `on_key`
    /// convenience does exactly that.
    pub fn handle_key(&self, key: KeyEvent) -> Vec<Action> {
        if let Some(modal) = &self.modal {
            return self.handle_key_in_modal(modal, key);
        }
        match self.input_focus {
            InputFocus::HistorySearch => self.handle_key_in_history_search(key),
            InputFocus::Composer => self.handle_key_in_composer(key),
        }
    }

    fn handle_key_in_composer(&self, key: KeyEvent) -> Vec<Action> {
        let km = &self.keymap;
        if key == km.key_for(KeymapAction::Quit) {
            return if self.input.is_empty() {
                if self.quit_armed {
                    vec![Action::Quit]
                } else {
                    vec![Action::ArmQuit]
                }
            } else {
                // Non-empty composer: Ctrl+C clears the line (matches the
                // pre-P5-4 REPL's own "a lone idle Ctrl-C only clears the
                // current line" convention — see `crates/cli/src/main.rs`
                // `chat()`'s doc comment).
                vec![Action::MoveHome, Action::ClearComposerLine]
            };
        }
        if key == km.key_for(KeymapAction::HistorySearch) {
            return vec![Action::OpenHistorySearch];
        }
        if key == km.key_for(KeymapAction::ToggleTheme) {
            return vec![Action::ToggleTheme];
        }
        if key == km.key_for(KeymapAction::ScrollUp) {
            return vec![Action::ScrollUp];
        }
        if key == km.key_for(KeymapAction::ScrollDown) {
            return vec![Action::ScrollDown];
        }
        if key == km.key_for(KeymapAction::ExternalEditor) {
            return vec![Action::RequestExternalEditor];
        }
        if key == km.key_for(KeymapAction::Newline) {
            return vec![Action::Newline];
        }
        if self.vim_enabled && self.vim_mode == VimMode::Normal {
            return self.handle_key_vim_normal(key);
        }
        if key == km.key_for(KeymapAction::Submit) {
            if self.input.is_empty() {
                return vec![];
            }
            return vec![Action::Submit(self.input.clone())];
        }
        match key.key {
            Key::Char(c) if !key.ctrl && !key.alt => vec![Action::InsertChar(c)],
            Key::Backspace => vec![Action::Backspace],
            Key::Delete => vec![Action::DeleteForward],
            Key::Left => vec![Action::MoveLeft],
            Key::Right => vec![Action::MoveRight],
            Key::Home => vec![Action::MoveHome],
            Key::End => vec![Action::MoveEnd],
            Key::Escape if self.vim_enabled => vec![Action::VimSetMode(VimMode::Normal)],
            _ => vec![],
        }
    }

    fn handle_key_vim_normal(&self, key: KeyEvent) -> Vec<Action> {
        if key.ctrl || key.alt {
            return vec![];
        }
        match key.key {
            Key::Char('i') => vec![Action::VimSetMode(VimMode::Insert)],
            Key::Char('a') => vec![Action::VimMoveRight, Action::VimSetMode(VimMode::Insert)],
            Key::Char('o') => vec![
                Action::VimMoveEnd,
                Action::Newline,
                Action::VimSetMode(VimMode::Insert),
            ],
            Key::Char('h') => vec![Action::VimMoveLeft],
            Key::Char('l') => vec![Action::VimMoveRight],
            Key::Char('0') => vec![Action::VimMoveHome],
            Key::Char('$') => vec![Action::VimMoveEnd],
            Key::Char('x') => vec![Action::VimDeleteChar],
            // `dd` (delete the whole composer line) is approximated as a
            // single `d` press — see the crate doc comment's "basic, not
            // full vim" scope note (no two-keystroke command buffering).
            Key::Char('d') => vec![Action::VimDeleteLine],
            Key::Enter if self.input.is_empty() => vec![],
            Key::Enter => vec![Action::Submit(self.input.clone())],
            _ => vec![],
        }
    }

    fn handle_key_in_history_search(&self, key: KeyEvent) -> Vec<Action> {
        match key.key {
            Key::Escape => vec![Action::HistorySearchCancel],
            Key::Enter => vec![Action::HistorySearchConfirm],
            Key::Up => vec![Action::HistorySearchPrev],
            Key::Down => vec![Action::HistorySearchNext],
            _ if key == self.keymap.key_for(KeymapAction::HistorySearch) => {
                vec![Action::HistorySearchNext]
            }
            Key::Backspace => vec![Action::HistorySearchBackspace],
            Key::Char(c) if !key.ctrl && !key.alt => vec![Action::HistorySearchType(c)],
            _ => vec![],
        }
    }

    fn handle_key_in_modal(&self, modal: &Modal, key: KeyEvent) -> Vec<Action> {
        match modal {
            // F3 (Fable-5 adversarial review — MEDIUM): both approval
            // arms below now guard on `!key.ctrl && !key.alt`, matching
            // the elicitation arm's own `Key::Char(c) if !key.ctrl &&
            // !key.alt` guard further down — WITHOUT it, Ctrl+A (a common
            // "select all"/readline chord in plenty of other programs)
            // resolved `Allow`, and Ctrl+S resolved `AllowForSession`, on
            // a modal whose whole POINT is a deliberate human decision;
            // a reflexive chord muscle-memoried from another program must
            // never resolve one.
            Modal::Approval(_) if !key.ctrl && !key.alt => match key.key {
                Key::Char('y') | Key::Char('a') => {
                    vec![Action::ResolveApproval(ApprovalOutcome::Allow)]
                }
                Key::Char('s') => vec![Action::ResolveApproval(ApprovalOutcome::AllowForSession)],
                Key::Char('n') | Key::Char('d') | Key::Escape => {
                    vec![Action::ResolveApproval(ApprovalOutcome::Deny)]
                }
                _ => vec![],
            },
            Modal::Approval(_) => vec![],
            Modal::ChildApproval(_) if !key.ctrl && !key.alt => match key.key {
                Key::Char('y') | Key::Char('a') => {
                    vec![Action::ResolveChildApproval(ApprovalOutcome::Allow)]
                }
                Key::Char('s') => vec![Action::ResolveChildApproval(
                    ApprovalOutcome::AllowForSession,
                )],
                Key::Char('n') | Key::Char('d') | Key::Escape => {
                    vec![Action::ResolveChildApproval(ApprovalOutcome::Deny)]
                }
                _ => vec![],
            },
            Modal::ChildApproval(_) => vec![],
            Modal::Elicitation { .. } => match key.key {
                Key::Enter => vec![Action::ResolveElicitationAccept],
                Key::Escape => vec![Action::ResolveElicitationCancel],
                Key::F(2) => vec![Action::ResolveElicitationDecline],
                Key::Backspace => vec![Action::ElicitationBackspace],
                Key::Char(c) if !key.ctrl && !key.alt => vec![Action::ElicitationType(c)],
                _ => vec![],
            },
            Modal::OAuthDeviceCode(_) => match key.key {
                Key::Enter | Key::Escape => vec![Action::DismissOAuthModal],
                _ => vec![],
            },
        }
    }

    /// Apply one [`Action`] — the only place [`TuiState`] mutates. Any key
    /// OTHER than the one that just armed `Self::quit_armed` disarms it
    /// (so "Ctrl+C, type something, Ctrl+C" does NOT quit — only two
    /// CONSECUTIVE Ctrl+C presses do), except `ArmQuit`/`Quit` themselves.
    pub fn apply(&mut self, action: Action) {
        if !matches!(action, Action::ArmQuit | Action::Quit) {
            if self.quit_armed {
                self.status.notice = None;
            }
            self.quit_armed = false;
        }
        match action {
            Action::InsertChar(c) => {
                self.input.insert(self.cursor, c);
                self.cursor += c.len_utf8();
            }
            Action::Backspace => {
                if self.cursor > 0 {
                    let mut idx = self.cursor - 1;
                    while !self.input.is_char_boundary(idx) {
                        idx -= 1;
                    }
                    self.input.remove(idx);
                    self.cursor = idx;
                }
            }
            Action::DeleteForward => {
                if self.cursor < self.input.len() {
                    self.input.remove(self.cursor);
                }
            }
            Action::MoveLeft => {
                if self.cursor > 0 {
                    let mut idx = self.cursor - 1;
                    while !self.input.is_char_boundary(idx) {
                        idx -= 1;
                    }
                    self.cursor = idx;
                }
            }
            Action::MoveRight => {
                if self.cursor < self.input.len() {
                    let mut idx = self.cursor + 1;
                    while idx < self.input.len() && !self.input.is_char_boundary(idx) {
                        idx += 1;
                    }
                    self.cursor = idx;
                }
            }
            Action::MoveHome => self.cursor = 0,
            Action::MoveEnd => self.cursor = self.input.len(),
            Action::Newline => {
                self.input.insert(self.cursor, '\n');
                self.cursor += 1;
            }
            Action::ClearComposerLine => {
                self.input.clear();
                self.cursor = 0;
            }
            Action::Submit(text) => {
                self.history.push(text.clone());
                self.transcript.push(TranscriptEntry {
                    role: Role::User,
                    text: text.clone(),
                });
                self.input.clear();
                self.cursor = 0;
                // F5 (Fable-5 adversarial review): this used to clear
                // `pending_images` right here — BEFORE the CLI layer's
                // render loop ever gets a chance to read `last_submission`
                // (that only happens on the NEXT tick, via
                // `Self::take_submission`). A pasted image's path was
                // gone by the time anything could route it into the turn
                // — the model only ever saw the literal `[image: …]`
                // placeholder text. `pending_images` now stays put until
                // [`Self::take_pending_images`] drains it — see that
                // method's doc comment for the paired contract.
                self.last_submission = Some(text);
            }
            Action::ScrollUp => self.scroll = self.scroll.saturating_add(1),
            Action::ScrollDown => self.scroll = self.scroll.saturating_sub(1),
            Action::ToggleTheme => self.theme = self.theme.toggled(),
            Action::OpenHistorySearch => {
                self.input_focus = InputFocus::HistorySearch;
                self.history_search = Some(HistorySearchState::default());
            }
            Action::HistorySearchType(c) => {
                if let Some(s) = &mut self.history_search {
                    s.query.push(c);
                    s.selected = 0;
                }
            }
            Action::HistorySearchBackspace => {
                if let Some(s) = &mut self.history_search {
                    s.query.pop();
                    s.selected = 0;
                }
            }
            Action::HistorySearchNext => {
                if let Some(s) = &mut self.history_search {
                    let n = self.history.search(&s.query).len();
                    if n > 0 {
                        s.selected = (s.selected + 1) % n;
                    }
                }
            }
            Action::HistorySearchPrev => {
                if let Some(s) = &mut self.history_search {
                    let n = self.history.search(&s.query).len();
                    if n > 0 {
                        s.selected = (s.selected + n - 1) % n;
                    }
                }
            }
            Action::HistorySearchConfirm => {
                if let Some(s) = self.history_search.take() {
                    if let Some(&hit) = self.history.search(&s.query).get(s.selected) {
                        self.input = hit.to_string();
                        self.cursor = self.input.len();
                    }
                }
                self.input_focus = InputFocus::Composer;
            }
            Action::HistorySearchCancel => {
                self.history_search = None;
                self.input_focus = InputFocus::Composer;
            }
            Action::VimSetMode(mode) => self.vim_mode = mode,
            Action::VimMoveLeft => self.apply(Action::MoveLeft),
            Action::VimMoveRight => self.apply(Action::MoveRight),
            Action::VimMoveHome => self.apply(Action::MoveHome),
            Action::VimMoveEnd => self.apply(Action::MoveEnd),
            Action::VimDeleteChar => self.apply(Action::DeleteForward),
            Action::VimDeleteLine => self.apply(Action::ClearComposerLine),
            Action::RequestExternalEditor => self.external_editor_requested = true,
            Action::ExternalEditorResult(text) => {
                self.external_editor_requested = false;
                self.input = text;
                self.cursor = self.input.len();
            }
            Action::ExternalEditorFailed(message) => {
                self.external_editor_requested = false;
                self.transcript.push(TranscriptEntry {
                    role: Role::System,
                    text: format!("$EDITOR failed: {message}"),
                });
            }
            Action::PasteImage(reference) => {
                self.pending_images.push(reference.clone());
                let token = format!("[image: {reference}]");
                self.input.insert_str(self.cursor, &token);
                self.cursor += token.len();
            }
            Action::ShowApprovalModal(req) => self.enqueue_or_show(Modal::Approval(req)),
            Action::ResolveApproval(outcome) => {
                if let Some(Modal::Approval(req)) =
                    self.take_modal_if(|m| matches!(m, Modal::Approval(_)))
                {
                    let note = approval_note(&req.tool, req.subject.as_deref(), outcome);
                    let _ = req.reply_tx.send(outcome);
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: note,
                    });
                }
                self.dequeue_modal();
            }
            Action::ShowChildApprovalModal(req) => self.enqueue_or_show(Modal::ChildApproval(req)),
            Action::ResolveChildApproval(outcome) => {
                if let Some(Modal::ChildApproval(req)) =
                    self.take_modal_if(|m| matches!(m, Modal::ChildApproval(_)))
                {
                    let note = format!(
                        "child `{}` {}",
                        req.child_agent_id,
                        approval_note(&req.tool, req.subject.as_deref(), outcome)
                    );
                    let _ = req.reply_tx.send(outcome);
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: note,
                    });
                }
                self.dequeue_modal();
            }
            Action::ShowElicitationModal(req) => self.enqueue_or_show(Modal::Elicitation {
                request: req,
                answer: String::new(),
            }),
            Action::ElicitationType(c) => {
                if let Some(Modal::Elicitation { answer, .. }) = &mut self.modal {
                    answer.push(c);
                }
            }
            Action::ElicitationBackspace => {
                if let Some(Modal::Elicitation { answer, .. }) = &mut self.modal {
                    answer.pop();
                }
            }
            Action::ResolveElicitationAccept => {
                if let Some(Modal::Elicitation { request, answer }) =
                    self.take_modal_if(|m| matches!(m, Modal::Elicitation { .. }))
                {
                    let content = elicitation_content(&request.requested_schema, &answer);
                    // F9 (Fable-5 adversarial review — LOW security bit):
                    // this used to echo `answer` VERBATIM into the
                    // scrollback transcript — a server asking for a token/
                    // password left it sitting in plaintext, visible on
                    // screen and in anything that later scrolls back
                    // through the transcript. The MCP elicitation schema
                    // has no standardized "this field is a secret" signal
                    // to key an exemption off (see
                    // `PendingElicitation::requested_schema`'s shape), so
                    // the safe default is masking EVERY elicitation
                    // answer's echo, not guessing from the field name —
                    // the actual `content` sent back to the server (right
                    // above) is unaffected, this only changes what the
                    // HUMAN'S OWN screen shows afterward.
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: format!("elicitation answered: {}", mask_elicitation_answer(&answer)),
                    });
                    let _ = request.reply_tx.send(ElicitationResponse {
                        action: ElicitationAction::Accept,
                        content: Some(content),
                    });
                }
                self.dequeue_modal();
            }
            Action::ResolveElicitationDecline => {
                if let Some(Modal::Elicitation { request, .. }) =
                    self.take_modal_if(|m| matches!(m, Modal::Elicitation { .. }))
                {
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: "elicitation declined".to_string(),
                    });
                    let _ = request.reply_tx.send(ElicitationResponse {
                        action: ElicitationAction::Decline,
                        content: None,
                    });
                }
                self.dequeue_modal();
            }
            Action::ResolveElicitationCancel => {
                if let Some(Modal::Elicitation { request, .. }) =
                    self.take_modal_if(|m| matches!(m, Modal::Elicitation { .. }))
                {
                    let _ = request.reply_tx.send(ElicitationResponse {
                        action: ElicitationAction::Cancel,
                        content: None,
                    });
                }
                self.dequeue_modal();
            }
            Action::ShowOAuthModal(display) => {
                self.enqueue_or_show(Modal::OAuthDeviceCode(display))
            }
            Action::DismissOAuthModal => {
                self.take_modal_if(|m| matches!(m, Modal::OAuthDeviceCode(_)));
                self.dequeue_modal();
            }
            Action::AppendStreamingDelta(delta) => {
                self.streaming
                    .get_or_insert_with(String::new)
                    .push_str(&delta);
            }
            Action::FinalizeStreaming => {
                if let Some(text) = self.streaming.take() {
                    self.transcript.push(TranscriptEntry {
                        role: Role::Assistant,
                        text,
                    });
                }
            }
            Action::PushTranscript(entry) => self.transcript.push(entry),
            Action::SetModelLabel(label) => self.status.model_label = label,
            Action::SetTurnActive(active) => self.status.turn_active = active,
            Action::ArmQuit => {
                self.quit_armed = true;
                self.status.notice = Some("press Ctrl+C again to exit".to_string());
            }
            Action::Quit => self.should_quit = true,
            Action::Noop => {}
        }
    }

    /// Run [`Self::handle_key`], then [`Self::apply`] every resulting
    /// action in order — the render layer's one-call-per-keypress
    /// convenience. Every externally-relevant outcome (a turn to send, an
    /// editor to launch, …) lands in a dedicated `TuiState` field
    /// ([`Self::last_submission`]/[`Self::external_editor_requested`]/
    /// [`Self::should_quit`]) the caller polls afterward — `Action` itself
    /// is intentionally NOT `Clone` (it carries one-shot reply channels),
    /// so this doesn't hand actions back; a caller that needs to react to
    /// the RAW action stream (e.g. a test) calls `handle_key`+`apply`
    /// directly instead, as most of this module's own tests do.
    pub fn on_key(&mut self, key: KeyEvent) {
        for action in self.handle_key(key) {
            self.apply(action);
        }
    }

    /// Take (and clear) the most recent submission, if any — see
    /// [`Self::last_submission`]'s doc comment.
    pub fn take_submission(&mut self) -> Option<String> {
        self.last_submission.take()
    }

    /// F5 (Fable-5 adversarial review): the CLI layer's paired polling
    /// point alongside [`Self::take_submission`] — call both together,
    /// same tick, right after `take_submission` returns `Some`: this
    /// drains (and clears) every image path staged via
    /// [`Action::PasteImage`] for THAT submission, for the caller to
    /// route into the turn's multimodal content (e.g.
    /// `Agent::send_with_images`). Previously `Action::Submit` cleared
    /// `pending_images` eagerly, before the CLI layer could ever read it
    /// — this method is what makes draining it the CLI's job instead, so
    /// a pasted image path actually reaches the model.
    pub fn take_pending_images(&mut self) -> Vec<String> {
        std::mem::take(&mut self.pending_images)
    }

    fn enqueue_or_show(&mut self, modal: Modal) {
        if self.modal.is_none() {
            self.modal = Some(modal);
        } else {
            self.modal_queue.push_back(modal);
        }
    }

    fn dequeue_modal(&mut self) {
        if self.modal.is_none() {
            self.modal = self.modal_queue.pop_front();
        }
    }

    fn take_modal_if(&mut self, pred: impl FnOnce(&Modal) -> bool) -> Option<Modal> {
        if self.modal.as_ref().is_some_and(pred) {
            self.modal.take()
        } else {
            None
        }
    }

    /// D-1 (Fable-5 delta review — MEDIUM, "error-path indefinite hang"):
    /// drop the active modal AND everything still queued behind it,
    /// without sending a reply. Each [`Modal`] variant that carries a
    /// reply channel (`Approval`/`ChildApproval`'s `std::sync::mpsc::Sender`,
    /// `Elicitation`'s `tokio::sync::oneshot::Sender`) has its sender
    /// dropped as part of this — the corresponding blocked caller
    /// (`TuiApprovalHandler::ask`/elicitation) already treats a closed
    /// channel as its documented fail-closed default
    /// (`ApprovalOutcome::Deny` / a declined `ElicitationResponse`; see
    /// `crate::tui::handlers`), so this never silently allows anything.
    /// `OAuthDeviceCode` carries no reply channel — dropping it is a plain
    /// dismissal.
    ///
    /// The CLI's render loop (`run_turn_blocking_with_input`) calls this
    /// when its own terminal I/O has failed while a modal is still
    /// unanswered: nothing is left alive to answer it (crossterm is
    /// broken), and the in-flight turn's worker thread is parked in a
    /// blocking `recv()`/`.await` on that modal's reply channel that
    /// `std::thread::scope` will join before the loop can return ANY
    /// value, including its own I/O error — so leaving the modal pending
    /// would hang the whole session forever instead of surfacing that
    /// error.
    pub fn fail_close_pending_modals(&mut self) {
        self.modal = None;
        self.modal_queue.clear();
    }
}

fn approval_note(tool: &str, subject: Option<&str>, outcome: ApprovalOutcome) -> String {
    let verdict = match outcome {
        ApprovalOutcome::Deny => "denied",
        ApprovalOutcome::Allow => "allowed (once)",
        ApprovalOutcome::AllowForSession => "allowed (for session)",
    };
    match subject {
        Some(s) => format!("approval: {tool} `{s}` — {verdict}"),
        None => format!("approval: {tool}{verdict}"),
    }
}

/// P5-2: build the `content` an [`ElicitationResponse::Accept`] carries
/// from the modal's free-text `answer` — deliberately basic (not a full
/// JSON-Schema-driven form builder, see the crate doc comment's
/// shippable-vs-staged note): if `schema` names exactly one top-level
/// property, the answer is wrapped under THAT property's name (so a
/// single-field schema round-trips as the field the server actually asked
/// for); otherwise it's wrapped under a generic `"value"` key.
fn elicitation_content(schema: &serde_json::Value, answer: &str) -> serde_json::Value {
    if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
        if props.len() == 1 {
            if let Some(name) = props.keys().next() {
                return serde_json::json!({ name: answer });
            }
        }
    }
    serde_json::json!({ "value": answer })
}

/// F9 (Fable-5 adversarial review — LOW security bit): mask an
/// elicitation answer before it's echoed into the (human-visible-only)
/// transcript — see [`TuiState::apply`]'s `ResolveElicitationAccept` arm
/// for why every answer is masked rather than trying to guess which ones
/// are "sensitive" from the field name. A fixed-width placeholder (not
/// one bullet per character) so the mask itself doesn't leak the
/// answer's length; an empty answer gets its own honest placeholder
/// rather than a mask that looks identical to a real one.
fn mask_elicitation_answer(answer: &str) -> &'static str {
    if answer.is_empty() {
        "(empty)"
    } else {
        "••••"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::mpsc;

    fn state() -> TuiState {
        TuiState::new_default()
    }

    // ---- composer basics ----

    #[test]
    fn typing_inserts_and_advances_cursor() {
        let mut s = state();
        s.on_key(KeyEvent::ch('h'));
        s.on_key(KeyEvent::ch('i'));
        assert_eq!(s.input, "hi");
        assert_eq!(s.cursor, 2);
    }

    #[test]
    fn backspace_removes_the_char_before_cursor() {
        let mut s = state();
        s.on_key(KeyEvent::ch('a'));
        s.on_key(KeyEvent::ch('b'));
        s.on_key(KeyEvent::plain(Key::Backspace));
        assert_eq!(s.input, "a");
        assert_eq!(s.cursor, 1);
    }

    #[test]
    fn backspace_on_multibyte_char_removes_the_whole_char() {
        let mut s = state();
        for c in "".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        assert_eq!(s.cursor, "".len()); // 3 bytes: 'h' (1) + 'é' (2)
        s.on_key(KeyEvent::plain(Key::Backspace));
        assert_eq!(s.input, "h");
        assert_eq!(s.cursor, 1);
    }

    #[test]
    fn move_left_right_home_end() {
        let mut s = state();
        for c in "abc".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.on_key(KeyEvent::plain(Key::Home));
        assert_eq!(s.cursor, 0);
        s.on_key(KeyEvent::plain(Key::Right));
        assert_eq!(s.cursor, 1);
        s.on_key(KeyEvent::plain(Key::End));
        assert_eq!(s.cursor, 3);
        s.on_key(KeyEvent::plain(Key::Left));
        assert_eq!(s.cursor, 2);
    }

    #[test]
    fn submit_clears_composer_and_pushes_transcript_and_history() {
        let mut s = state();
        for c in "hello".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        let actions = s.handle_key(KeyEvent::plain(Key::Enter));
        assert!(matches!(actions.as_slice(), [Action::Submit(t)] if t == "hello"));
        for a in actions {
            s.apply(a);
        }
        assert_eq!(s.input, "");
        assert_eq!(s.transcript.last().unwrap().text, "hello");
        assert_eq!(s.transcript.last().unwrap().role, Role::User);
        assert_eq!(s.history.search(""), vec!["hello"]);
    }

    #[test]
    fn enter_on_empty_composer_does_nothing() {
        let s = state();
        let actions = s.handle_key(KeyEvent::plain(Key::Enter));
        assert!(actions.is_empty());
    }

    #[test]
    fn newline_key_inserts_newline_without_submitting() {
        let mut s = state();
        s.on_key(KeyEvent::ch('a'));
        s.on_key(KeyEvent {
            key: Key::Enter,
            ctrl: false,
            alt: true,
            shift: false,
        });
        s.on_key(KeyEvent::ch('b'));
        assert_eq!(s.input, "a\nb");
        assert!(s.transcript.is_empty());
    }

    // ---- quit (double ctrl-c) ----

    #[test]
    fn ctrl_c_on_empty_composer_arms_then_quits_on_repeat() {
        let mut s = state();
        let a1 = s.handle_key(KeyEvent::ctrl(Key::Char('c')));
        assert!(matches!(a1.as_slice(), [Action::ArmQuit]));
        for a in a1 {
            s.apply(a);
        }
        assert!(!s.should_quit);
        assert!(s.status.notice.is_some());

        let a2 = s.handle_key(KeyEvent::ctrl(Key::Char('c')));
        assert!(matches!(a2.as_slice(), [Action::Quit]));
        for a in a2 {
            s.apply(a);
        }
        assert!(s.should_quit);
    }

    #[test]
    fn ctrl_c_disarms_after_an_intervening_keypress() {
        let mut s = state();
        s.on_key(KeyEvent::ctrl(Key::Char('c')));
        assert!(s.quit_armed);
        s.on_key(KeyEvent::ch('x'));
        assert!(!s.quit_armed);
        // Now Ctrl+C sees a non-empty composer, so it clears the line
        // instead of arming/quitting.
        s.on_key(KeyEvent::ctrl(Key::Char('c')));
        assert!(!s.should_quit);
        assert_eq!(s.input, "");
    }

    #[test]
    fn ctrl_c_on_nonempty_composer_clears_the_line() {
        let mut s = state();
        for c in "oops".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.on_key(KeyEvent::ctrl(Key::Char('c')));
        assert_eq!(s.input, "");
        assert!(!s.should_quit);
    }

    // ---- theme toggle ----

    #[test]
    fn ctrl_t_toggles_theme() {
        let mut s = state();
        assert_eq!(s.theme, Theme::Dark);
        s.on_key(KeyEvent::ctrl(Key::Char('t')));
        assert_eq!(s.theme, Theme::Light);
        s.on_key(KeyEvent::ctrl(Key::Char('t')));
        assert_eq!(s.theme, Theme::Dark);
    }

    // ---- history search ----

    #[test]
    fn ctrl_r_opens_history_search_and_narrows_by_typing() {
        let mut s = state();
        s.history.push("fix login bug");
        s.history.push("add tests");
        s.on_key(KeyEvent::ctrl(Key::Char('r')));
        assert_eq!(s.input_focus, InputFocus::HistorySearch);
        for c in "login".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        assert_eq!(s.history_search.as_ref().unwrap().query, "login");
        s.on_key(KeyEvent::plain(Key::Enter));
        assert_eq!(s.input, "fix login bug");
        assert_eq!(s.input_focus, InputFocus::Composer);
    }

    #[test]
    fn history_search_escape_cancels_without_changing_composer() {
        let mut s = state();
        s.history.push("something");
        s.on_key(KeyEvent::ctrl(Key::Char('r')));
        s.on_key(KeyEvent::ch('x'));
        s.on_key(KeyEvent::plain(Key::Escape));
        assert_eq!(s.input, "");
        assert_eq!(s.input_focus, InputFocus::Composer);
        assert!(s.history_search.is_none());
    }

    // ---- vim basic mode ----

    #[test]
    fn vim_disabled_by_default_i_inserts_char() {
        let mut s = state();
        assert!(!s.vim_enabled);
        s.on_key(KeyEvent::ch('i'));
        assert_eq!(s.input, "i");
    }

    #[test]
    fn vim_enabled_starts_in_normal_mode_and_i_enters_insert() {
        let mut s = TuiState::new(
            Theme::default(),
            Keymap::default(),
            true,
            PromptHistory::new(),
        );
        assert_eq!(s.vim_mode, VimMode::Normal);
        s.on_key(KeyEvent::ch('i'));
        assert_eq!(s.vim_mode, VimMode::Insert);
        assert_eq!(s.input, "");
        s.on_key(KeyEvent::ch('a'));
        assert_eq!(s.input, "a");
    }

    #[test]
    fn vim_normal_hjkl_and_x_and_dd() {
        let mut s = TuiState::new(
            Theme::default(),
            Keymap::default(),
            true,
            PromptHistory::new(),
        );
        s.on_key(KeyEvent::ch('i'));
        for c in "abc".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.on_key(KeyEvent::plain(Key::Escape));
        assert_eq!(s.vim_mode, VimMode::Normal);
        assert_eq!(s.input, "abc");
        s.on_key(KeyEvent::ch('h'));
        s.on_key(KeyEvent::ch('h'));
        assert_eq!(s.cursor, 1);
        s.on_key(KeyEvent::ch('x'));
        assert_eq!(s.input, "ac");
        s.on_key(KeyEvent::ch('d'));
        assert_eq!(s.input, "");
    }

    // ---- approval modal (P5-1 chain) ----

    #[test]
    fn approval_modal_allow_for_session_sends_outcome_and_clears_modal() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: Some("rm -rf /tmp/x".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        assert!(matches!(s.modal, Some(Modal::Approval(_))));
        let actions = s.handle_key(KeyEvent::ch('s'));
        assert!(matches!(
            actions.as_slice(),
            [Action::ResolveApproval(ApprovalOutcome::AllowForSession)]
        ));
        for a in actions {
            s.apply(a);
        }
        assert!(s.modal.is_none());
        assert_eq!(rx.try_recv(), Ok(ApprovalOutcome::AllowForSession));
        assert!(s
            .transcript
            .last()
            .unwrap()
            .text
            .contains("allowed (for session)"));
    }

    #[test]
    fn approval_modal_deny_sends_deny() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: None,
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.on_key(KeyEvent::ch('n'));
        assert_eq!(rx.try_recv(), Ok(ApprovalOutcome::Deny));
    }

    #[test]
    fn approval_modal_escape_denies() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "write_file".to_string(),
            subject: Some("x.txt".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.on_key(KeyEvent::plain(Key::Escape));
        assert_eq!(rx.try_recv(), Ok(ApprovalOutcome::Deny));
    }

    /// F3 (Fable-5 adversarial review — MEDIUM): Ctrl+A / Ctrl+S in an
    /// approval modal must NOT resolve it (a reflexive "select all"/
    /// "save" chord from another program must never allow a tool call).
    #[test]
    fn approval_modal_ignores_ctrl_a_and_ctrl_s() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: Some("rm -rf /tmp/x".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        assert!(s.handle_key(KeyEvent::ctrl(Key::Char('a'))).is_empty());
        assert!(s.handle_key(KeyEvent::ctrl(Key::Char('s'))).is_empty());
        assert!(
            matches!(s.modal, Some(Modal::Approval(_))),
            "the modal must still be showing — neither chord may resolve it"
        );
        assert!(rx.try_recv().is_err(), "no reply must have been sent");

        // A plain (unmodified) 'y' still works — the guard only screens
        // out ctrl/alt, it doesn't disable the modal.
        s.on_key(KeyEvent::ch('y'));
        assert_eq!(rx.try_recv(), Ok(ApprovalOutcome::Allow));
    }

    /// F3: Alt-modified keys are ignored the same way.
    #[test]
    fn approval_modal_ignores_alt_modified_keys() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: None,
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        let alt_y = KeyEvent {
            key: Key::Char('y'),
            ctrl: false,
            alt: true,
            shift: false,
        };
        assert!(s.handle_key(alt_y).is_empty());
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn a_second_request_queues_behind_the_first_modal() {
        let mut s = state();
        let (tx1, rx1) = mpsc::channel();
        let (tx2, rx2) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: None,
            raw_args: serde_json::json!({}),
            reply_tx: tx1,
        }));
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "write_file".to_string(),
            subject: None,
            raw_args: serde_json::json!({}),
            reply_tx: tx2,
        }));
        // Second request hasn't been shown yet.
        assert!(rx2.try_recv().is_err());
        s.on_key(KeyEvent::ch('y')); // resolve the first
        assert_eq!(rx1.try_recv(), Ok(ApprovalOutcome::Allow));
        // The second is now the active modal.
        assert!(matches!(s.modal, Some(Modal::Approval(_))));
        s.on_key(KeyEvent::ch('n'));
        assert_eq!(rx2.try_recv(), Ok(ApprovalOutcome::Deny));
    }

    // ---- child approval modal (P5-3 chain) ----

    #[test]
    fn child_approval_modal_allow_sends_outcome_tagged_with_child_id() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowChildApprovalModal(PendingChildApproval {
            child_agent_id: "agent-bg-1".to_string(),
            tool: "bash".to_string(),
            subject: Some("curl evil.example".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.on_key(KeyEvent::ch('y'));
        assert_eq!(rx.try_recv(), Ok(ApprovalOutcome::Allow));
        assert!(s.transcript.last().unwrap().text.contains("agent-bg-1"));
    }

    /// F3 (Fable-5 adversarial review — MEDIUM): same guard, the
    /// child-approval modal.
    #[test]
    fn child_approval_modal_ignores_ctrl_a_and_ctrl_s() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowChildApprovalModal(PendingChildApproval {
            child_agent_id: "agent-bg-2".to_string(),
            tool: "bash".to_string(),
            subject: Some("curl evil.example".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        assert!(s.handle_key(KeyEvent::ctrl(Key::Char('a'))).is_empty());
        assert!(s.handle_key(KeyEvent::ctrl(Key::Char('s'))).is_empty());
        assert!(matches!(s.modal, Some(Modal::ChildApproval(_))));
        assert!(rx.try_recv().is_err());
    }

    // ---- elicitation modal (P5-2 chain) ----

    #[tokio::test]
    async fn elicitation_modal_accept_wraps_answer_under_the_single_schema_property() {
        let mut s = state();
        let (tx, rx) = tokio::sync::oneshot::channel();
        s.apply(Action::ShowElicitationModal(PendingElicitation {
            message: "What's your name?".to_string(),
            requested_schema: serde_json::json!({
                "type": "object",
                "properties": { "name": {"type": "string"} }
            }),
            reply_tx: tx,
        }));
        for c in "Ada".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.on_key(KeyEvent::plain(Key::Enter));
        assert!(s.modal.is_none());
        let resp = rx.await.unwrap();
        assert_eq!(resp.action, ElicitationAction::Accept);
        assert_eq!(resp.content, Some(serde_json::json!({"name": "Ada"})));
    }

    /// F9 (Fable-5 adversarial review — LOW security bit): the answer
    /// sent BACK TO THE SERVER (`resp.content`) must still be the real,
    /// unmasked text — masking is purely a transcript-echo (human-screen)
    /// concern, never a protocol-correctness one.
    #[tokio::test]
    async fn elicitation_modal_accept_masks_the_transcript_echo_but_not_the_reply_content() {
        let mut s = state();
        let (tx, rx) = tokio::sync::oneshot::channel();
        s.apply(Action::ShowElicitationModal(PendingElicitation {
            message: "What's the API token?".to_string(),
            requested_schema: serde_json::json!({
                "type": "object",
                "properties": { "token": {"type": "string"} }
            }),
            reply_tx: tx,
        }));
        for c in "sk-super-secret".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.on_key(KeyEvent::plain(Key::Enter));

        let resp = rx.await.unwrap();
        assert_eq!(
            resp.content,
            Some(serde_json::json!({"token": "sk-super-secret"})),
            "the server must still receive the real answer"
        );

        let echoed = &s.transcript.last().unwrap().text;
        assert!(
            !echoed.contains("sk-super-secret"),
            "the transcript echo must not contain the raw answer: {echoed}"
        );
        assert!(
            echoed.contains("••••"),
            "the transcript echo must show a mask placeholder: {echoed}"
        );
    }

    #[test]
    fn mask_elicitation_answer_gives_empty_its_own_placeholder() {
        assert_eq!(mask_elicitation_answer(""), "(empty)");
        assert_eq!(mask_elicitation_answer("x"), "••••");
        assert_eq!(mask_elicitation_answer("a very long secret token"), "••••");
    }

    #[tokio::test]
    async fn elicitation_modal_escape_cancels() {
        let mut s = state();
        let (tx, rx) = tokio::sync::oneshot::channel();
        s.apply(Action::ShowElicitationModal(PendingElicitation {
            message: "".to_string(),
            requested_schema: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.on_key(KeyEvent::plain(Key::Escape));
        let resp = rx.await.unwrap();
        assert_eq!(resp.action, ElicitationAction::Cancel);
        assert_eq!(resp.content, None);
    }

    #[tokio::test]
    async fn elicitation_modal_f2_declines() {
        let mut s = state();
        let (tx, rx) = tokio::sync::oneshot::channel();
        s.apply(Action::ShowElicitationModal(PendingElicitation {
            message: "".to_string(),
            requested_schema: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.on_key(KeyEvent::plain(Key::F(2)));
        let resp = rx.await.unwrap();
        assert_eq!(resp.action, ElicitationAction::Decline);
    }

    #[test]
    fn elicitation_backspace_edits_the_answer_buffer() {
        let mut s = state();
        let (tx, _rx) = tokio::sync::oneshot::channel();
        s.apply(Action::ShowElicitationModal(PendingElicitation {
            message: "".to_string(),
            requested_schema: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.on_key(KeyEvent::ch('a'));
        s.on_key(KeyEvent::ch('b'));
        s.on_key(KeyEvent::plain(Key::Backspace));
        if let Some(Modal::Elicitation { answer, .. }) = &s.modal {
            assert_eq!(answer, "a");
        } else {
            panic!("expected elicitation modal");
        }
    }

    // ---- OAuth device-code display ----

    #[test]
    fn oauth_modal_shows_and_dismisses_on_enter() {
        let mut s = state();
        s.apply(Action::ShowOAuthModal(PendingOAuthDisplay {
            server_name: "acme".to_string(),
            user_code: "ABCD-1234".to_string(),
            verification_uri: "https://example.com/device".to_string(),
            verification_uri_complete: None,
            expires_in_secs: 600,
        }));
        assert!(matches!(s.modal, Some(Modal::OAuthDeviceCode(_))));
        s.on_key(KeyEvent::plain(Key::Enter));
        assert!(s.modal.is_none());
    }

    // ---- streaming / transcript ----

    #[test]
    fn streaming_deltas_accumulate_and_finalize_into_transcript() {
        let mut s = state();
        s.apply(Action::AppendStreamingDelta("Hel".to_string()));
        s.apply(Action::AppendStreamingDelta("lo".to_string()));
        assert_eq!(s.streaming.as_deref(), Some("Hello"));
        s.apply(Action::FinalizeStreaming);
        assert!(s.streaming.is_none());
        assert_eq!(s.transcript.last().unwrap().text, "Hello");
        assert_eq!(s.transcript.last().unwrap().role, Role::Assistant);
    }

    // ---- image paste ----

    #[test]
    fn paste_image_inserts_a_placeholder_and_records_the_reference() {
        let mut s = state();
        s.apply(Action::PasteImage("/tmp/screenshot.png".to_string()));
        assert!(s.input.contains("[image: /tmp/screenshot.png]"));
        assert_eq!(s.pending_images, vec!["/tmp/screenshot.png".to_string()]);
    }

    /// F5 (Fable-5 adversarial review): `pending_images` used to be
    /// cleared inside `apply(Action::Submit(_))` itself — before the CLI
    /// layer's render loop ever got a chance to read `last_submission`
    /// (that only happens on the NEXT tick) — so a pasted image was
    /// already gone by the time anything could route it into the turn.
    /// Proves the fix: the images are still there right after `Submit`,
    /// and `take_pending_images` is what drains them (once).
    #[test]
    fn pending_images_survive_submit_and_are_drained_by_take_pending_images() {
        let mut s = state();
        s.apply(Action::PasteImage("/tmp/screenshot.png".to_string()));
        for c in "describe this".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.on_key(KeyEvent::plain(Key::Enter));
        assert_eq!(
            s.take_submission().as_deref(),
            Some("[image: /tmp/screenshot.png]describe this")
        );
        assert_eq!(
            s.pending_images,
            vec!["/tmp/screenshot.png".to_string()],
            "the image must still be there for the CLI layer to drain, \
             right after the submission is read"
        );
        assert_eq!(
            s.take_pending_images(),
            vec!["/tmp/screenshot.png".to_string()]
        );
        assert!(
            s.pending_images.is_empty(),
            "take_pending_images must clear, not just read"
        );
    }

    // ---- external editor ----

    #[test]
    fn external_editor_request_then_result_replaces_composer() {
        let mut s = state();
        s.on_key(KeyEvent::ctrl(Key::Char('e')));
        assert!(s.external_editor_requested);
        s.apply(Action::ExternalEditorResult("edited text".to_string()));
        assert!(!s.external_editor_requested);
        assert_eq!(s.input, "edited text");
    }

    /// F9 (Fable-5 adversarial review — LOW): an `$EDITOR` spawn failure
    /// must clear the pending flag (so `run_loop` doesn't retry-loop
    /// launching a nonexistent editor forever) and leave a visible trace
    /// — WITHOUT touching the composer's existing text, unlike a success.
    #[test]
    fn external_editor_failed_clears_the_flag_and_notes_it_without_touching_the_composer() {
        let mut s = state();
        s.on_key(KeyEvent::ctrl(Key::Char('e')));
        assert!(s.external_editor_requested);
        for c in "unsaved draft".chars() {
            s.on_key(KeyEvent::ch(c));
        }
        s.apply(Action::ExternalEditorFailed(
            "No such file or directory (os error 2)".to_string(),
        ));
        assert!(!s.external_editor_requested);
        assert_eq!(
            s.input, "unsaved draft",
            "a failed editor invocation must not clobber the composer"
        );
        assert!(s
            .transcript
            .last()
            .unwrap()
            .text
            .contains("No such file or directory"));
    }

    // ---- D-1 (Fable-5 delta review — MEDIUM): fail-closing pending
    // modals so a blocked `ask()`/elicitation caller can never be left
    // stuck once the render loop that would have answered it is gone ----

    /// The active modal's reply sender is dropped, and a blocked
    /// `recv()` on the paired receiver (exactly what
    /// `TuiApprovalHandler::ask`/`TuiChildApprovalHandler::ask` do) sees
    /// the channel close — which is already their documented fail-closed
    /// path (`.unwrap_or(ApprovalOutcome::Deny)`), proven directly here
    /// via the raw receiver rather than trusting the handler.
    #[test]
    fn fail_close_pending_modals_drops_the_active_approval_reply_sender() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: Some("rm -rf /tmp/x".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        assert!(matches!(s.modal, Some(Modal::Approval(_))));

        s.fail_close_pending_modals();

        assert!(s.modal.is_none());
        assert_eq!(
            rx.recv(),
            Err(mpsc::RecvError),
            "the sender must have been dropped without a reply — that's \
             what makes ask()'s blocked recv() resolve Deny"
        );
    }

    /// Same guard, the child-approval modal's reply sender.
    #[test]
    fn fail_close_pending_modals_drops_the_active_child_approval_reply_sender() {
        let mut s = state();
        let (tx, rx) = mpsc::channel();
        s.apply(Action::ShowChildApprovalModal(PendingChildApproval {
            child_agent_id: "agent-bg-3".to_string(),
            tool: "bash".to_string(),
            subject: None,
            raw_args: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.fail_close_pending_modals();
        assert!(s.modal.is_none());
        assert_eq!(rx.recv(), Err(mpsc::RecvError));
    }

    /// The elicitation modal's `oneshot` reply sender is dropped too —
    /// an awaited `rx.await` on the paired receiver resolves `Err`, which
    /// `McpElicitationHandler::handle` already maps to a declined
    /// response (see [`crate::mcp::ElicitationResponse`]'s handling in
    /// `crate::tui::handlers`), never a silent accept.
    #[tokio::test]
    async fn fail_close_pending_modals_drops_the_active_elicitation_reply_sender() {
        let mut s = state();
        let (tx, rx) = tokio::sync::oneshot::channel();
        s.apply(Action::ShowElicitationModal(PendingElicitation {
            message: "".to_string(),
            requested_schema: serde_json::json!({}),
            reply_tx: tx,
        }));
        s.fail_close_pending_modals();
        assert!(s.modal.is_none());
        assert!(
            rx.await.is_err(),
            "the oneshot sender must have been dropped without a reply"
        );
    }

    /// A request queued BEHIND the active modal must also be fail-closed
    /// — not just the one currently showing. Before this fix, a plain
    /// `state.modal = None` alone would have promoted the queued request
    /// into view (via the normal `dequeue_modal` path elsewhere), which
    /// is exactly the still-unanswered-modal state D-1 exists to avoid.
    #[test]
    fn fail_close_pending_modals_also_drops_everything_still_queued() {
        let mut s = state();
        let (tx1, rx1) = mpsc::channel();
        let (tx2, rx2) = mpsc::channel();
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "bash".to_string(),
            subject: None,
            raw_args: serde_json::json!({}),
            reply_tx: tx1,
        }));
        s.apply(Action::ShowApprovalModal(PendingApprovalRequest {
            tool: "write_file".to_string(),
            subject: Some("x.txt".to_string()),
            raw_args: serde_json::json!({}),
            reply_tx: tx2,
        }));
        assert!(matches!(s.modal, Some(Modal::Approval(_))));
        assert_eq!(s.modal_queue.len(), 1);

        s.fail_close_pending_modals();

        assert!(s.modal.is_none());
        assert_eq!(s.modal_queue.len(), 0);
        assert_eq!(rx1.recv(), Err(mpsc::RecvError));
        assert_eq!(
            rx2.recv(),
            Err(mpsc::RecvError),
            "the QUEUED request's sender must be dropped too, not just the active one"
        );
    }
}