newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
//! **Real-PTY acceptance test for the interaction view's TERMINAL LIFECYCLE**
//! (C2, #1876).
//!
//! What only this tier can prove: the inline interaction frame takes a real
//! terminal into raw mode and must hand it back on **every** exit path. No
//! mock can observe that — the thing at risk is the state of an actual tty
//! device, not a value in our process. This grounds `InlineGuard`'s
//! Drop-based restoration claim and the module's pure row-model tests, which
//! by construction never touch a terminal.
//!
//! Modelled on `transcript_pager_pty_test` (#1677), including the control
//! that makes the result mean something: **`raw_during`**. A test that never
//! observed raw mode would "prove" restoration vacuously — it would pass
//! against a build where `InlineGuard::enter` did nothing at all.
//!
//! # Why the failure path is the one that matters
//!
//! A clean close restoring the terminal is the easy half; every
//! implementation gets it right. The half that strands an operator in a shell
//! that no longer echoes is the unwind — and `config_panel::run` shows the
//! shape that gets it wrong, calling `disable_raw_mode()` as a statement
//! after its loop, which a panic skips entirely. `InlineGuard` owes the
//! restore from `Drop`, and `panic_restores_the_terminal` is what says so
//! against a real device rather than by inspection.
//!
//! # The postcondition is KERNEL state, not escape bytes
//!
//! [`Pty::is_raw`] runs `tcgetattr` on the parent's own slave fd, and pty line
//! discipline belongs to the *device*, so the parent observes exactly the
//! raw/cooked state the child installed. A child could emit a plausible-looking
//! restore sequence and still leave the tty raw — and that failure is precisely
//! the one that wrecks a terminal.

use std::time::{Duration, Instant};

use tests_pty::{screen_grid, signal_winch, Pty};

use crate::interaction_view::InlineGuard;
use crate::prompt_visibility_test::wait_for_child;

const CHILD_TEST: &str = "interaction_view_pty_test::interaction_view_child";

/// Generous: this tier runs under parallel load on shared runners.
const REACH_TIMEOUT: Duration = Duration::from_secs(60);
const EXIT_TIMEOUT: Duration = Duration::from_secs(60);

/// The child half: takes the real terminal over exactly as an inline
/// interaction frame does. `NEWT_INTERACTION_PTY_CHILD` selects the lifecycle.
#[test]
#[ignore = "child process of the interaction-view PTY acceptance test"]
fn interaction_view_child() {
    let Some(mode) = std::env::var_os("NEWT_INTERACTION_PTY_CHILD") else {
        return;
    };
    match mode.to_string_lossy().as_ref() {
        // The ordinary path: the frame closes and the scope ends.
        "clean" => {
            let _guard = InlineGuard::enter().expect("enter raw mode");
            hold();
        }
        // The failure path AFTER entry: the guard is live and the process
        // unwinds. Restoration must not depend on reaching the end of the
        // function — it is a Drop obligation.
        "panic" => {
            let _guard = InlineGuard::enter().expect("enter raw mode");
            hold();
            panic!("synthetic failure while the interaction frame is up (#1876)");
        }
        // An error RETURN out of the middle, which is how a failed
        // `terminal.draw` leaves `present`. The guard is dropped by the `?`
        // unwind of scope, not by any cleanup the author remembered to write.
        "error" => {
            fn inner() -> std::io::Result<()> {
                let _guard = InlineGuard::enter()?;
                {
                    use std::io::Read as _;
                    let mut byte = [0u8; 1];
                    let _ = std::io::stdin().read(&mut byte);
                }
                Err(std::io::Error::other("synthetic draw failure"))
            }
            assert!(inner().is_err(), "the fixture must take the error path");
        }
        // **Nested modals.** An interaction frame opened over a frame that is
        // already up — the shape `modal.rs::RawGuard` was written for
        // (#1770). The child holds TWICE so the parent can sample the tty in
        // the window BETWEEN the inner drop and the outer one, which is the
        // only moment the defect is visible: if the inner guard restores
        // globally, the outer frame is still drawn but the terminal is
        // already cooked, so its keyboard is line-buffered and echoing.
        "nested" => {
            let _outer = InlineGuard::enter().expect("enter raw mode (outer)");
            {
                let _inner = InlineGuard::enter().expect("enter raw mode (inner)");
                hold();
            } // inner drops here; the OUTER frame is still up.
            hold();
        }
        // **The real renderer, not a bare guard.** `present` owns the inline
        // viewport, polls events, redraws on resize, and answers on an
        // accelerator — so resize and narrow-width are exercised against the
        // production loop rather than against a fixture that merely holds
        // raw mode.
        "present" => {
            let interaction = fixture_interaction();
            let outcome =
                crate::interaction_view::present(&interaction).expect("the frame runs and returns");
            // Printed AFTER the guard has dropped and erased the region, so
            // the parent can distinguish "answered" from "still drawing".
            println!("OUTCOME:{outcome:?}");
        }
        // **An interaction arriving mid-turn.** A spinner owns the bottom row
        // and repaints ~10x/second; the frame must open over a CLEAN region
        // and must not be painted back over. This is #1312's defect class —
        // "a permission prompt rendered invisibly underneath a spinner that
        // overwrote it ~8x/second" — for the rich frame rather than the plain
        // prompt, which `prompt_visibility_test` already covers.
        //
        // The suspend is the mechanism under test: `suspend_for_prompt`
        // erases every registered ephemeral writer and holds them quiesced
        // for the window's lifetime. `RichSurface::present_interaction` does
        // exactly this pair; it is spelled out here rather than constructing
        // a whole RichSurface, which would drag in an editor and a config.
        "active_turn" => {
            use newt_core::tty::{LineCaps, Sink, Spinner, Terminal};
            let spinner = Spinner::start_with_caps(LineCaps::Own, "thinking…", Sink::Stdout, true)
                .expect("the pty is a real terminal, so the spinner takes the line");
            // Let it paint a few frames, so the test is about a LIVE writer
            // rather than one that never started.
            std::thread::sleep(Duration::from_millis(400));

            let interaction = fixture_interaction();
            let outcome = {
                let _window =
                    Terminal::suspend_for_prompt(newt_core::tty::TerminalTaker::RichSurfaceModal);
                crate::interaction_view::present(&interaction).expect("the frame runs")
            };
            drop(spinner);
            println!("OUTCOME:{outcome:?}");
        }
        // **Where the next line lands.** The four placements the arbiter
        // decides for a frame under the transcript; see `committed_frame_case`.
        "committed_frame" => committed_frame_case(5, false, true, false),
        "committed_frame_held" => committed_frame_case(5, true, false, false),
        "committed_frame_scroll" => committed_frame_case(22, false, true, false),
        "committed_frame_contested" => committed_frame_case(18, true, false, false),
        "committed_frame_partial" => committed_frame_case(5, false, true, true),
        "committed_frame_partial_scroll" => committed_frame_case(23, false, true, true),
        "cockpit_resize" => {
            crate::cockpit::presenter::panel_resize_case();
        }
        "cockpit_live_resize" => {
            crate::cockpit::presenter::panel_live_resize_case();
        }
        "cockpit_panel_loop" => {
            crate::cockpit::presenter::cockpit_panel_loop_case();
        }
        "cockpit_acceptance" => {
            crate::cockpit::presenter::cockpit_acceptance_case();
        }
        "startup_migration" => {
            crate::cockpit::presenter::startup_migration_case();
        }
        "persona_migration" => {
            crate::cockpit::presenter::persona_migration_case();
        }
        "cockpit_migration" => {
            crate::cockpit::presenter::cockpit_migration_case();
        }
        "cockpit_bang" => {
            crate::cockpit::presenter::cockpit_bang_case();
        }
        "cockpit_buffered_input" => {
            crate::cockpit::presenter::cockpit_buffered_input_case();
        }
        "cockpit_clarification_input" => {
            crate::cockpit::presenter::cockpit_clarification_input_case();
        }
        #[cfg(feature = "rich-tui")]
        "cockpit_psyche" => {
            crate::cockpit::presenter::cockpit_psyche_case();
        }
        #[cfg(feature = "live-spill")]
        "cockpit_pager" => {
            crate::cockpit::presenter::cockpit_pager_case();
        }
        other => panic!("unknown child mode {other:?}"),
    }
}

/// HOLD the child until the parent has sampled the tty. Exiting immediately
/// is a race the parent loses: the restore would run before the first
/// `is_raw()` read, and the test would "pass" without ever having observed
/// raw mode — which is exactly what the `raw_during` control refuses to
/// accept. One blocking byte-read makes the window deterministic.
fn hold() {
    use std::io::Read as _;
    let mut byte = [0u8; 1];
    let _ = std::io::stdin().read(&mut byte);
}

/// The bottom rows a `committed_frame_held` child keeps, painted with these
/// sentinels: the prompt editor's shape, as `panel_raw_mode_pty_test` makes it.
const FRAME_HOLDER_ROWS: u16 = 3;
const FRAME_HOLDER_SENTINEL: &str = "HOLDER-ROW";

/// The row under the transcript, after a frame.
///
/// From a cleared screen (libtest's own progress line shares this pty), print
/// `lines` transcript rows, keep the bottom rows when `held`, open the real
/// `present` frame — under a prompt window when `window`, which is the pair
/// `RichSurface::present_interaction` makes — and commit one more line the
/// moment it closes. The parent replays the bytes with erases and reads where
/// that line landed.
fn committed_frame_case(lines: u16, held: bool, window: bool, partial: bool) {
    use std::io::Write as _;
    let mut out = std::io::stdout();
    write!(out, "\x1b[2J\x1b[H").expect("clear");
    for n in 0..lines {
        writeln!(out, "TRANSCRIPT-{n:02}").expect("print");
    }
    out.flush().expect("flush");
    let holder = held.then(|| {
        let (_, rows) = crossterm::terminal::size().expect("size");
        let holder = crate::inline_viewport::lease_bottom_rows(
            FRAME_HOLDER_ROWS,
            newt_core::tty::OnCollision::Refuse,
        )
        .expect("the holder takes the bottom rows first");
        for r in 0..FRAME_HOLDER_ROWS {
            write!(
                out,
                "\x1b[{};1H{FRAME_HOLDER_SENTINEL}-{r}",
                rows - FRAME_HOLDER_ROWS + r + 1
            )
            .expect("paint");
        }
        // Back to the transcript's end, where a turn leaves the cursor.
        write!(out, "\x1b[{};1H", lines + 1).expect("park");
        out.flush().expect("flush");
        holder
    });
    if partial {
        write!(out, "PARTIAL-END").expect("partial sentinel without newline");
        out.flush().expect("flush partial sentinel");
    }
    let interaction = fixture_interaction();
    let window = window.then(|| {
        newt_core::tty::Terminal::suspend_for_prompt(
            newt_core::tty::TerminalTaker::RichSurfaceModal,
        )
    });
    let (outcome, _) = crate::interaction_view::present(&interaction).expect("the frame runs");
    drop(window);
    println!("COMMITTED-AFTER-FRAME");
    drop(holder);
    println!("OUTCOME:{outcome:?}");
    hold();
}

/// A permission-shaped interaction with labels long enough that a narrow
/// terminal must wrap them.
fn fixture_interaction() -> newt_core::interaction_surface::SurfaceInteraction {
    use newt_interaction::{
        ChoiceOption, Control, ControlId, ControlKind, InteractionDefinition, InteractionKind,
        OptionId, Requirement, SemanticRole,
    };
    let option = |id: &str, key: &str, label: &str| ChoiceOption {
        id: OptionId::new(id).expect("valid option id"),
        role: SemanticRole::Allow,
        label: label.to_string(),
        key: key.to_string(),
        aliases: Vec::new(),
    };
    let mut definition = InteractionDefinition::new(
        InteractionKind::Choice,
        "\u{2298} run_command wants to run `bash` \u{2014} outside the granted exec allowlist.",
        vec![Control {
            id: ControlId::new("decision").expect("valid control id"),
            kind: ControlKind::Choice {
                options: vec![
                    option("allow_once", "a", "allow once"),
                    option("deny", "d", "deny (default)"),
                ],
            },
            label: String::new(),
            requirement: Requirement::Required,
        }],
    );
    definition.note = Some("Esc=back \u{b7} Ctrl-C/Ctrl-D=exit".into());
    newt_core::interaction_surface::SurfaceInteraction::blocking(definition)
}

/// Answer a Device Status Report if the child asked for one.
///
/// `ratatui`'s `Viewport::Inline` asks the terminal where the cursor is
/// (`ESC[6n`) so it knows which rows it may own, and it waits for the reply.
/// A bare pty has no emulator behind it, so nothing answers and the frame
/// never initialises — which is precisely the class of thing only a real-PTY
/// test finds. The parent holds the master fd, so answering is its job.
/// `answered` counts the replies already sent FOR THIS SEGMENT, and each
/// segment's buffer starts empty — so it must be reset per segment. A
/// cumulative counter compared against a per-segment count silently stops
/// answering: the post-resize query then goes unanswered and the child dies
/// with "The cursor position could not be read within a normal duration",
/// which is how this was found.
fn answer_cursor_report(pty: &Pty, screen: &str, answered: &mut usize) {
    // EVERY query, not just the first: a resize makes the viewport re-ask,
    // and a latch that answered once left the frame waiting forever on the
    // second.
    let asked = screen.matches("\u{1b}[6n").count();
    while *answered < asked {
        // Row 1, column 1: the frame is entered at a known-clean row because
        // `suspend_for_prompt` has erased every ephemeral writer first.
        pty.type_in("\u{1b}[1;1R");
        *answered += 1;
    }
}

/// Lines libtest itself printed, which share the pty with the frame.
///
/// The child runs under `--nocapture` so its `OUTCOME:` marker reaches the
/// parent, and libtest's own progress lines come with it. A width assertion
/// that measured those would be testing libtest's formatting, not the frame's
/// — and would fail for a reason that has nothing to do with the property.
fn is_harness_noise(line: &str) -> bool {
    let t = line.trim();
    t.is_empty()
        || t.starts_with("running ")
        || t.starts_with("test ")
        || t.starts_with("test result:")
        || t.starts_with("failures")
        || t.starts_with("OUTCOME:")
        || t.starts_with("interaction_view_pty_test::")
        || t.starts_with("note: ")
        || t.starts_with("thread '")
}

/// Visible text with CSI/OSC sequences removed, one entry per screen line.
///
/// Used only where POSITION does not matter (presence of a marker). Width
/// assertions use [`screen_grid`] instead — see its doc for why.
#[allow(dead_code)]
fn visible_lines(screen: &str) -> Vec<String> {
    let mut out = String::new();
    let mut chars = screen.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '\u{1b}' {
            out.push(c);
            continue;
        }
        match chars.peek() {
            // CSI: parameters/intermediates, then a final byte in @..~
            Some('[') => {
                chars.next();
                for f in chars.by_ref() {
                    if ('\u{40}'..='\u{7e}').contains(&f) {
                        break;
                    }
                }
            }
            // OSC: runs to BEL or ST
            Some(']') => {
                chars.next();
                while let Some(f) = chars.next() {
                    if f == '\u{7}' || (f == '\u{1b}' && chars.peek() == Some(&'\\')) {
                        break;
                    }
                }
            }
            _ => {
                chars.next();
            }
        }
    }
    out.replace('\r', "\n")
        .lines()
        .map(str::to_string)
        .collect()
}

/// Spawn the child in `mode`, with fd 0/1 on `pty`.
///
/// **The ONE spawn site in this file, deliberately.** Three drivers need a
/// child (a simple lifecycle, a nested one, and the real `present` loop) and
/// each began as its own spawn call. That is three copies of one trust
/// decision, and `docs/security/spawn-inventory.toml` counts occurrences per
/// file — so it would have been three things to justify and three places for
/// them to drift apart. One helper keeps the inventory entry at a count of
/// one and makes the justification cover exactly one shape:
///
/// (Note for whoever edits this doc: `scripts/spawn_inventory.py` matches its
/// needle over raw file text without stripping comments, so writing the
/// spawn-constructor's name in prose here counts as a second site and fails
/// the gate. Bumping the allowlist to accommodate a comment would be the
/// wrong fix — it would reserve room for a real spawn nobody reviewed.)
///
/// re-execute THIS test binary (`std::env::current_exe`) with an `--exact`
/// filter so the child runs one ignored `#[test]` with fd 0/1 on a pty. Fixed
/// argv, no shell, no attacker- or model-controlled input; the child is the
/// binary cargo just built, so it cannot be stale or foreign.
fn spawn_child(pty: &Pty, mode: &str) -> std::process::Child {
    let mut child = std::process::Command::new(
        std::env::current_exe().expect("the test binary re-invokes itself"),
    );
    child
        .args(["--exact", CHILD_TEST, "--ignored", "--nocapture"])
        .env("NEWT_INTERACTION_PTY_CHILD", mode)
        .env("TERM", "xterm-256color")
        .stdin(pty.slave_stdio())
        .stdout(pty.slave_stdio())
        .stderr(std::process::Stdio::null());
    if matches!(
        mode,
        "cockpit_bang"
            | "cockpit_buffered_input"
            | "cockpit_pager"
            | "cockpit_panel_loop"
            | "cockpit_psyche"
    ) {
        child.env("NEWT_EDIT_MODE", "emacs");
    }
    child.spawn().expect("spawn the pty child")
}

/// Ground the modal reservation's resize contract in a disposable process.
/// Reusing this child launcher keeps the extra tty and Crossterm's global
/// event source out of sibling keyboard tests, without dropping assertions.
pub(crate) fn drive_cockpit_resize() {
    drive_cockpit_case("cockpit_resize");
}

/// #2571: the same disposable child, resizing while the panel is open.
pub(crate) fn drive_cockpit_live_resize() {
    drive_cockpit_case("cockpit_live_resize");
}

pub(crate) fn drive_startup_migration() {
    drive_cockpit_case("startup_migration");
}

pub(crate) fn drive_persona_migration() {
    drive_cockpit_case("persona_migration");
}

pub(crate) fn drive_cockpit_migration() {
    drive_cockpit_case("cockpit_migration");
}

pub(crate) fn drive_cockpit_acceptance() {
    drive_cockpit_case("cockpit_acceptance");
}

pub(crate) fn drive_cockpit_buffered_input() {
    drive_cockpit_case("cockpit_buffered_input");
}

pub(crate) fn drive_cockpit_clarification_input() {
    drive_cockpit_case("cockpit_clarification_input");
}

/// #2489: open the real `/psyche` panel under a real cockpit and read the
/// screen the way the operator does. `screen_grid` ignores erase commands, so a
/// second writer's stale frame shows up as a repeated title or two dials on one
/// row — exactly the garble in the report.
#[cfg(feature = "rich-tui")]
pub(crate) fn drive_cockpit_psyche() {
    const TITLE: &str = "psyche — operator dials";
    let pty = Pty::open_with_cursor_reply(1, 1);
    pty.resize(30, 100);
    let baseline = pty.termios_snapshot();
    let mut child = spawn_child(&pty, "cockpit_psyche");
    let mut transcript = String::new();
    let result = (|| -> Result<(), String> {
        if !pty.wait_for_screen_after(TITLE, "Esc cancel", REACH_TIMEOUT) {
            return Err("the psyche panel never painted its footer".into());
        }
        let frame = pty.screen();
        transcript.push_str(&frame);
        let rows = screen_grid(&frame);
        let titles = rows.iter().filter(|row| row.contains(TITLE)).count();
        if titles != 1 {
            return Err(format!(
                "panel title drawn {titles} times, want 1: {rows:?}"
            ));
        }
        // Each dial owns its own row: two labels on one row means the rows were
        // wrapped or scrolled into each other.
        const LABELS: [&str; 4] = ["agreeableness", "extraversion", "warmth", "prosocial"];
        for row in &rows {
            let n = LABELS.iter().filter(|l| row.contains(**l)).count();
            if n > 1 {
                return Err(format!(
                    "dial rows interleaved on one row {row:?}: {rows:?}"
                ));
            }
        }
        // ...and every dial is drawn exactly once: a missing or duplicated
        // label also means the panel did not own its rows.
        for label in LABELS {
            let n = rows.iter().filter(|row| row.contains(label)).count();
            if n != 1 {
                return Err(format!("dial {label:?} drawn {n} times, want 1: {rows:?}"));
            }
        }
        pty.type_in("\x1b");
        if !pty.wait_for_screen_after("PSYCHE_RETURNED", "^D exit", REACH_TIMEOUT) {
            return Err("Esc did not close the panel and restore the editor".into());
        }
        transcript.push_str(&pty.screen());
        pty.type_in("after-psyche\r");
        if !pty.wait_for_screen("PSYCHE_RESTORED", REACH_TIMEOUT) {
            return Err("the next submission was lost or contaminated by panel keys".into());
        }
        if pty.termios_snapshot() != baseline {
            return Err("panel/cockpit did not restore the exact terminal mode".into());
        }
        pty.type_in("\n");
        Ok(())
    })();
    if result.is_err() {
        let _ = child.kill();
    }
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    transcript.push_str(&pty.screen_to_eof());
    assert!(result.is_ok(), "{result:?}: {transcript:?}");
    assert!(
        status.is_some_and(|status| status.success()),
        "{status:?}: {transcript:?}"
    );
}

#[cfg(feature = "live-spill")]
pub(crate) fn drive_cockpit_pager() {
    for sizes in [
        &[][..],
        &[(12, 46), (30, 100), (24, 80)][..],
        &[(12, 46), (30, 100)][..],
    ] {
        drive_cockpit_pager_sizes(sizes);
    }
}

#[cfg(feature = "live-spill")]
fn drive_cockpit_pager_sizes(sizes: &[(u16, u16)]) {
    let pty = Pty::open_with_cursor_reply(1, 1);
    pty.resize(24, 80);
    let baseline = pty.termios_snapshot();
    let mut child = spawn_child(&pty, "cockpit_pager");
    let mut transcript = String::new();
    let result = (|| -> Result<(), String> {
        if !pty.wait_for_screen_after("spill-row-00", "╯", REACH_TIMEOUT) {
            return Err("pager never painted its bottom border".into());
        }
        let first = pty.screen();
        transcript.push_str(&first);
        let (primary, frame) = first
            .split_once("\x1b[?1049h")
            .ok_or("pager must enter the real alternate screen, not stdout capture")?;
        let (_, after_history) = primary
            .split_once("HISTORY_BEFORE_PAGER")
            .ok_or("fixture must paint primary-screen history before the pager")?;
        // screen_grid deliberately ignores erase and alternate-buffer commands.
        // Check the real primary-screen bytes too: the loan must neither scroll
        // the history away nor erase it before the terminal saves that screen.
        if after_history.contains('\n')
            || after_history.contains("\x1b[1;1H\x1b[J")
            || after_history.contains("\x1b[2J")
        {
            return Err(
                "pager loan moved or cleared visible history before alternate entry".into(),
            );
        }
        let rows = screen_grid(frame);
        if !rows.get(1).is_some_and(|row| row.contains("spill-row-00"))
            || !rows.get(2).is_some_and(|row| row.contains("spill-row-01"))
            || frame.contains("^D exit")
        {
            return Err(format!(
                "pager must show separate body rows and occlude the composer: {rows:?}"
            ));
        }
        for &(height, width) in sizes {
            pty.resize(height, width);
            signal_winch(child.id());
            if !pty.wait_for_screen("╯", REACH_TIMEOUT) {
                return Err(format!("no repaint after resize to {width}x{height}"));
            }
            let repaint = pty.screen();
            transcript.push_str(&repaint);
            let rows = screen_grid(&repaint);
            if rows.len() != usize::from(height)
                || rows
                    .last()
                    .is_none_or(|row| row.chars().nth(usize::from(width - 1)) != Some('╯'))
                || !rows.get(1).is_some_and(|row| row.contains("spill-row-00"))
                || repaint.contains("^D exit")
            {
                return Err(format!(
                    "pager geometry or input ownership lost after resize: {rows:?}"
                ));
            }
        }
        pty.type_in("z\x1b");
        if !pty.wait_for_screen_after("PAGER_RETURNED", "^D exit", REACH_TIMEOUT) {
            return Err("pager did not return the editor after Esc".into());
        }
        let tail = pty.screen();
        transcript.push_str(&tail);
        if !tail.contains("\x1b[?1049l") || tail.contains("spill-row-") {
            return Err("pager pixels escaped into the restored transcript".into());
        }
        let (_, restored) = tail.split_once("\x1b[?1049l").unwrap();
        if restored.contains("\x1b[1;1H\x1b[J") || restored.contains("\x1b[2J") {
            return Err("pager release cleared the restored primary screen".into());
        }
        // Exclude every alternate-screen frame. The marker was in row zero;
        // the primary stream must neither erase it (above) nor overwrite it.
        let rows = screen_grid(&format!("{primary}{restored}"));
        if !rows
            .first()
            .is_some_and(|row| row.contains("HISTORY_BEFORE_PAGER"))
        {
            return Err(format!("prior visible history was not restored: {rows:?}"));
        }
        pty.type_in("after-view\r");
        if !pty.wait_for_screen("PAGER_RESTORED", REACH_TIMEOUT) {
            return Err("the next submission was lost or contaminated by modal keys".into());
        }
        if pty.termios_snapshot() != baseline {
            return Err("pager/cockpit did not restore the exact terminal mode".into());
        }
        pty.type_in("\n");
        Ok(())
    })();
    if result.is_err() {
        let _ = child.kill();
    }
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    transcript.push_str(&pty.screen_to_eof());
    assert!(result.is_ok(), "{result:?}: {transcript:?}");
    assert!(
        status.is_some_and(|status| status.success()),
        "{status:?}: {transcript:?}"
    );
}

/// The screen after `stream`, honouring what `screen_grid` ignores: erases
/// (`ED`/`EL`) and scrolling at the bottom row. Approximation: cursor motion
/// is absolute and there is no reflow, so a resize is not modelled: `rows` is
/// the height to scroll at, and rows are not lost when the terminal shrinks.
pub(crate) fn erasing_grid(stream: &str, rows: usize) -> Vec<String> {
    erasing_screen(stream, rows).0
}

/// [`erasing_grid`] plus where the cursor is (0-based row, column): what a
/// terminal would answer to a cursor-position query at the end of `stream`.
pub(crate) fn erasing_screen(stream: &str, rows: usize) -> (Vec<String>, (usize, usize)) {
    let mut grid: Vec<Vec<char>> = vec![Vec::new(); rows];
    let (mut row, mut col) = (0usize, 0usize);
    let mut chars = stream.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\n' => {
                col = 0;
                if row + 1 == rows {
                    grid.remove(0);
                    grid.push(Vec::new());
                } else {
                    row += 1;
                }
            }
            '\r' => col = 0,
            '\u{1b}' if chars.peek() == Some(&'[') => {
                chars.next();
                let mut params = String::new();
                let mut fin = '\0';
                for f in chars.by_ref() {
                    if ('\u{40}'..='\u{7e}').contains(&f) {
                        fin = f;
                        break;
                    }
                    params.push(f);
                }
                let n = |i: usize, d: usize| {
                    params
                        .split(';')
                        .nth(i)
                        .and_then(|p| p.parse().ok())
                        .unwrap_or(d)
                };
                match fin {
                    'H' => (row, col) = ((n(0, 1) - 1).min(rows - 1), n(1, 1) - 1),
                    'J' | 'K' => {
                        let mode = n(0, 0);
                        let cut = |line: &mut Vec<char>, from: usize, to: usize| {
                            for cell in line.iter_mut().take(to).skip(from) {
                                *cell = ' ';
                            }
                        };
                        let width = grid[row].len();
                        match mode {
                            0 => cut(&mut grid[row], col, width),
                            1 => cut(&mut grid[row], 0, col + 1),
                            _ => cut(&mut grid[row], 0, width),
                        }
                        if fin == 'J' {
                            let (from, to) = match mode {
                                0 => (row + 1, rows),
                                1 => (0, row),
                                _ => (0, rows),
                            };
                            for line in &mut grid[from..to] {
                                line.clear();
                            }
                        }
                    }
                    _ => {}
                }
            }
            '\u{1b}' => {
                chars.next();
            }
            c if !c.is_control() => {
                let line = &mut grid[row];
                if line.len() <= col {
                    line.resize(col + 1, ' ');
                }
                line[col] = c;
                col += 1;
            }
            _ => {}
        }
    }
    let lines = grid
        .into_iter()
        .map(|l| l.into_iter().collect::<String>().trim_end().to_string())
        .collect();
    (lines, (row, col))
}

fn panel_repaint_rows(stream: &str, terminal_rows: usize) -> Vec<String> {
    erasing_grid(stream, terminal_rows)
}

fn panel_height(rows: &[String]) -> Option<usize> {
    let top = rows.iter().position(|row| row.contains('╭'));
    let bottom = rows.iter().rposition(|row| row.contains('╰'));
    top.zip(bottom).map(|(top, bottom)| bottom - top + 1)
}

fn wait_for_panel_repaint(
    pty: &Pty,
    terminal_rows: usize,
    ready: impl Fn(&[String]) -> bool,
) -> Result<(String, Vec<String>), String> {
    let deadline = Instant::now() + REACH_TIMEOUT;
    let mut repaint = String::new();
    let mut rows = Vec::new();
    // Ratatui ends each panel frame by hiding the cursor. A corner alone
    // can belong to an earlier repaint or precede the remainder of a frame.
    // Accumulate complete frames until the actual requested state is visible;
    // a drain is not a frame boundary, and an old frame cannot acknowledge
    // the next input just because it also contains a bottom-right corner.
    const FRAME_END: &str = "\x1b[?25l";
    while pty.wait_for_screen(
        FRAME_END,
        deadline.saturating_duration_since(Instant::now()),
    ) {
        repaint.push_str(&pty.screen());
        if let Some(end) = repaint.rfind(FRAME_END) {
            rows = panel_repaint_rows(&repaint[..end + FRAME_END.len()], terminal_rows);
            if ready(&rows) {
                return Ok((repaint, rows));
            }
        }
        if Instant::now() >= deadline {
            break;
        }
    }
    Err(format!(
        "panel repaint did not reach the requested state: {rows:?}; bytes: {repaint:?}"
    ))
}

#[test]
fn panel_repaint_discards_erased_zoom_frame_in_one_drain() {
    // A drain may contain the final zoomed frame followed by its erase and
    // the restored inline frame. These are the same ED/CUP operations the
    // real panel emits; the first border must no longer count toward height.
    let repaint = concat!(
        "\x1b[1;1H╭ zoom ╮\x1b[2;1H❯ stale selection",
        "\x1b[20;1H╰──────╯\x1b[?25l",
        "\x1b[1;1H\x1b[J",
        "\x1b[13;1H╭ loop ╮\x1b[14;1H❯ panel-row-03",
        "\x1b[20;1H╰──────╯\x1b[?25l",
    );
    let rows = panel_repaint_rows(repaint, 20);
    assert_eq!(rows.iter().position(|row| row.contains('╭')), Some(12));
    assert_eq!(rows.iter().rposition(|row| row.contains('╰')), Some(19));
    assert!(rows[13].contains("❯ panel-row-03"));
    assert!(!rows.iter().any(|row| row.contains("stale selection")));
}

/// #2573 review: drive a real panel through resizes and keys, then close it.
/// The selection must survive, no resize may erase from row 0 (the transcript
/// above the panel stays), the border must sit at each new width, and the
/// draft and terminal modes must come back.
pub(crate) fn drive_cockpit_panel_loop() {
    let pty = Pty::open_with_cursor_reply(1, 1);
    pty.resize(24, 80);
    let baseline = pty.termios_snapshot();
    let mut child = spawn_child(&pty, "cockpit_panel_loop");
    let mut transcript = String::new();
    let result = (|| -> Result<(), String> {
        let (repaint, _) = wait_for_panel_repaint(&pty, 24, |rows| {
            panel_height(rows) == Some(8) && rows.iter().any(|row| row.contains("❯ panel-row-00"))
        })?;
        transcript.push_str(&repaint);
        pty.type_in("jjj");
        let (repaint, _) = wait_for_panel_repaint(&pty, 24, |rows| {
            rows.iter().any(|row| row.contains("❯ panel-row-03"))
        })?;
        transcript.push_str(&repaint);
        for &(height, width) in &[(24u16, 50u16), (24, 100), (40, 100), (16, 100)] {
            pty.resize(height, width);
            signal_winch(child.id());
            let (repaint, rows) = wait_for_panel_repaint(&pty, usize::from(height), |rows| {
                rows.iter()
                    .any(|row| row.chars().nth(usize::from(width - 1)) == Some('╯'))
                    && rows.iter().any(|row| row.contains("❯ panel-row-03"))
            })?;
            transcript.push_str(&repaint);
            if repaint.contains("\x1b[1;1H\x1b[J") || repaint.contains("\x1b[2J") {
                return Err(format!("resize to {width}x{height} erased from row 0"));
            }
            if !rows
                .iter()
                .any(|row| row.chars().nth(usize::from(width - 1)) == Some('╯'))
            {
                return Err(format!("border not at the new width {width}: {rows:?}"));
            }
            if !rows.iter().any(|row| row.contains("❯ panel-row-03")) {
                return Err(format!(
                    "selection lost after resize to {width}x{height}: {rows:?}"
                ));
            }
        }
        // #2574: the sizing keys, through the same loop. Height is counted
        // from the drawn borders; the selection must survive every step.
        let mut terminal_height = 16;
        for (keys, want, what) in [
            ("\x1b[1;2A", Some(9), "Shift-Up grows one row"),
            ("\x1b[1;2B", Some(8), "Shift-Down shrinks one row"),
            ("\x1a", Some(16), "Ctrl-Z fills the 16-row screen"),
            // Resizes WHILE zoomed: the fill request follows the screen, at
            // each new height and width, and the selection survives.
            (
                "resize:12x60",
                Some(12),
                "zoomed, terminal narrowed and shortened",
            ),
            (
                "resize:20x100",
                Some(20),
                "zoomed, terminal widened and lengthened",
            ),
            ("\x1a", Some(8), "Ctrl-Z again restores the prior height"),
        ] {
            let mut width = 100;
            if let Some(size) = keys.strip_prefix("resize:") {
                let (h, w) = size.split_once('x').expect("HxW");
                let (h, w): (u16, u16) = (h.parse().unwrap(), w.parse().unwrap());
                width = w;
                terminal_height = usize::from(h);
                pty.resize(h, w);
                signal_winch(child.id());
            } else {
                pty.type_in(keys);
            }
            let (repaint, rows) = wait_for_panel_repaint(&pty, terminal_height, |rows| {
                panel_height(rows) == want
                    && rows.iter().any(|row| row.contains("❯ panel-row-03"))
                    && rows
                        .iter()
                        .any(|row| row.chars().nth(usize::from(width - 1)) == Some('╯'))
            })
            .map_err(|error| format!("{what}: {error}"))?;
            transcript.push_str(&repaint);
            if panel_height(&rows) != want {
                return Err(format!(
                    "{what}: height {:?}: {rows:?}",
                    panel_height(&rows)
                ));
            }
            if keys.starts_with("resize:")
                && !rows
                    .iter()
                    .any(|row| row.chars().nth(usize::from(width - 1)) == Some('╯'))
            {
                return Err(format!("{what}: border not at width {width}: {rows:?}"));
            }
            if !rows.iter().any(|row| row.contains("❯ panel-row-03")) {
                return Err(format!("selection lost after: {what}: {rows:?}"));
            }
        }
        pty.type_in("\x1b");
        if !pty.wait_for_screen("PANEL_CLOSED", REACH_TIMEOUT) {
            return Err("Esc did not close the panel".into());
        }
        transcript.push_str(&pty.screen());
        pty.type_in("\r");
        if !pty.wait_for_screen("PANEL_LOOP_RESTORED", REACH_TIMEOUT) {
            return Err("the draft was not handed back intact".into());
        }
        if pty.termios_snapshot() != baseline {
            return Err("panel/cockpit did not restore the exact terminal mode".into());
        }
        pty.type_in("\n");
        Ok(())
    })();
    if result.is_err() {
        let _ = child.kill();
    }
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    transcript.push_str(&pty.screen_to_eof());
    assert!(result.is_ok(), "{result:?}: {transcript:?}");
    assert!(
        status.is_some_and(|status| status.success()),
        "{status:?}: {transcript:?}"
    );
}

/// #2573 hardening: closing a panel leaves the transcript above it and none
/// of the panel. No zoom and no resize, on purpose: a zoomed panel covers the
/// transcript and the presenter scrolls it into scrollback (by design), and
/// `erasing_grid` does not model a resize, so this is the case where "still on
/// screen" is a claim it can make exactly.
pub(crate) fn drive_cockpit_panel_close() {
    let pty = Pty::open_with_cursor_reply(1, 1);
    pty.resize(24, 80);
    let mut child = spawn_child(&pty, "cockpit_panel_loop");
    let mut transcript = String::new();
    let result = (|| -> Result<(), String> {
        if !pty.wait_for_screen_after("panel-row-00", "╯", REACH_TIMEOUT) {
            return Err("the panel never painted".into());
        }
        pty.type_in("jjj");
        if !pty.wait_for_screen("panel-row-03", REACH_TIMEOUT) {
            return Err("the selection did not move".into());
        }
        transcript.push_str(&pty.screen());
        let open = erasing_grid(&transcript, 24);
        if !open.iter().any(|row| row.contains("panel-row-03")) {
            return Err(format!(
                "control: the panel is not on the replayed screen: {open:?}"
            ));
        }
        pty.type_in("\x1b");
        if !pty.wait_for_screen("PANEL_CLOSED", REACH_TIMEOUT) {
            return Err("Esc did not close the panel".into());
        }
        transcript.push_str(&pty.screen());
        let live = erasing_grid(&transcript, 24);
        if !live.iter().any(|row| row.contains("HISTORY_ABOVE_PANEL")) {
            return Err(format!(
                "close erased the history above the panel: {live:?}"
            ));
        }
        if let Some(row) = live.iter().find(|row| row.contains("panel-row-")) {
            return Err(format!("panel text left after close: {row:?}: {live:?}"));
        }
        pty.type_in("\r");
        if !pty.wait_for_screen("PANEL_LOOP_RESTORED", REACH_TIMEOUT) {
            return Err("the draft was not handed back intact".into());
        }
        pty.type_in("\n");
        Ok(())
    })();
    if result.is_err() {
        let _ = child.kill();
    }
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    transcript.push_str(&pty.screen_to_eof());
    assert!(result.is_ok(), "{result:?}: {transcript:?}");
    assert!(
        status.is_some_and(|status| status.success()),
        "{status:?}: {transcript:?}"
    );
}

pub(crate) fn drive_cockpit_bang() {
    let pty = Pty::open_with_cursor_reply(1, 1);
    let baseline = pty.termios_snapshot();
    let mut child = spawn_child(&pty, "cockpit_bang");
    let mut failure = None;
    for (step, input) in ["hello child\r", "\x03", "\x04", "after interrupts\r"]
        .into_iter()
        .cycle()
        .take(8)
        .enumerate()
    {
        if !pty.wait_for_screen(&format!("BANG_READY_{step}>"), REACH_TIMEOUT) {
            failure = Some(format!("child {step} never became ready"));
            break;
        }
        if pty.termios_snapshot() != baseline {
            failure = Some(format!(
                "child {step} did not receive the inherited cooked terminal"
            ));
            break;
        }
        pty.type_in(input);
        if !pty.wait_for_screen_after(&format!("BANG_RETURN_{step}"), "^D exit", REACH_TIMEOUT) {
            failure = Some(format!("child {step} did not return to the editor"));
            break;
        }
        if !pty.is_raw() {
            failure = Some(format!("editor {step} did not regain raw input"));
            break;
        }
        pty.type_in(&format!("next-{step}\r"));
    }
    let restored = if failure.is_none() && pty.wait_for_screen("BANG_RESTORED", REACH_TIMEOUT) {
        let restored = pty.termios_snapshot();
        pty.type_in("\n");
        Some(restored)
    } else {
        failure.get_or_insert_with(|| "the cockpit never restored the terminal".into());
        None
    };
    if failure.is_some() {
        let _ = child.kill();
    }
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    let screen = pty.screen_to_eof();
    assert!(failure.is_none(), "{failure:?}: {screen:?}");
    assert!(
        status.is_some_and(|status| status.success()),
        "{status:?}: {screen:?}"
    );
    assert!(screen.contains("BANG_READ_0:0:hello child"), "{screen:?}");
    assert!(
        !screen.contains("BANG_READ_1:"),
        "Ctrl-C must interrupt the child: {screen:?}"
    );
    assert!(
        screen.contains("BANG_READ_2:1:"),
        "EOF must reach the child: {screen:?}"
    );
    assert!(
        screen.contains("BANG_READ_3:0:after interrupts"),
        "{screen:?}"
    );
    assert_eq!(
        restored,
        Some(baseline),
        "full inherited terminal mode after cockpit shutdown"
    );
}

fn drive_cockpit_case(mode: &str) {
    let pty = Pty::open();
    let mut child = spawn_child(&pty, mode);
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    let screen = pty.screen_to_eof();
    assert!(
        status.is_some_and(|status| status.success()),
        "{mode} child failed: {status:?}; {screen:?}"
    );
}

/// Everything the parent needs to judge one lifecycle.
struct Outcome {
    raw_after: bool,
    /// Was the pty raw while the frame was up? **The control**: a test that
    /// never observed raw mode would prove restoration vacuously.
    raw_during: bool,
    screen: String,
}

fn drive(mode: &str) -> Outcome {
    let pty = Pty::open();
    let mut child = spawn_child(&pty, mode);

    // There is no alternate-screen byte to poll for — this surface
    // deliberately never enters one — so the reach condition IS the kernel
    // state we care about.
    let mut screen = String::new();
    let raw_during = {
        let deadline = Instant::now() + REACH_TIMEOUT;
        loop {
            screen.push_str(&pty.screen());
            if pty.is_raw() {
                break true;
            }
            if Instant::now() >= deadline {
                break false;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    };

    // Release the child's blocking read so it proceeds to its exit path.
    pty.type_in("x");

    let _status = std::thread::scope(|scope| {
        let waiter = scope.spawn(|| wait_for_child(&mut child, EXIT_TIMEOUT));
        while !waiter.is_finished() {
            screen.push_str(&pty.screen());
            std::thread::sleep(Duration::from_millis(20));
        }
        waiter.join().expect("child reaper thread")
    });
    // Drain whatever the exit path emitted.
    std::thread::sleep(Duration::from_millis(80));
    screen.push_str(&pty.screen());

    Outcome {
        raw_after: pty.is_raw(),
        raw_during,
        screen,
    }
}

/// What the parent observed across a NESTED lifecycle.
struct NestedOutcome {
    /// Raw once the outer guard was up? (The control.)
    raw_during_outer: bool,
    /// Raw in the window after the INNER guard dropped but while the OUTER
    /// frame is still live? **This is the property.**
    raw_after_inner_drop: bool,
    /// Cooked once both are gone?
    raw_after_all: bool,
}

/// Drive the nested lifecycle, sampling in the window between the two drops.
fn drive_nested() -> NestedOutcome {
    let pty = Pty::open();
    let mut child = spawn_child(&pty, "nested");

    let raw_during_outer = {
        let deadline = Instant::now() + REACH_TIMEOUT;
        loop {
            if pty.is_raw() {
                break true;
            }
            if Instant::now() >= deadline {
                break false;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    };

    // Release the INNER hold. The child drops the inner guard and parks on
    // the second hold with the outer frame still up.
    pty.type_in("x");
    // Give the inner Drop time to run before sampling. Sampling too early
    // would read the pre-drop state and pass vacuously.
    std::thread::sleep(Duration::from_millis(250));
    let raw_after_inner_drop = pty.is_raw();

    // Release the OUTER hold and let the child exit.
    pty.type_in("x");
    let _ = std::thread::scope(|scope| {
        let waiter = scope.spawn(|| wait_for_child(&mut child, EXIT_TIMEOUT));
        while !waiter.is_finished() {
            let _ = pty.screen();
            std::thread::sleep(Duration::from_millis(20));
        }
        waiter.join().expect("child reaper thread")
    });
    std::thread::sleep(Duration::from_millis(80));
    let _ = pty.screen();

    NestedOutcome {
        raw_during_outer,
        raw_after_inner_drop,
        raw_after_all: pty.is_raw(),
    }
}

fn assert_restored(what: &str, out: &Outcome) {
    assert!(
        out.raw_during,
        "{what}: the pty was never raw — the test proved nothing about \
         restoration, because it never observed the state being restored FROM"
    );
    assert!(
        !out.raw_after,
        "{what}: the terminal was left in RAW mode — an operator's shell would \
         be unusable. This is kernel state via tcgetattr, not an inference \
         from escape bytes; screen={:?}",
        out.screen
    );
}

/// **The alternate screen is never entered.**
///
/// `plain_scroller_tui.md` permits an alt-screen modal on RichTUI, but the
/// carve-out is conditional: *"Operator-invoked and modal. It opens on an
/// explicit command … not ambiently, and never during a turn."* An
/// interaction prompt is model-triggered and happens DURING a turn, so it
/// satisfies neither condition and must stay inline. Asserted on the bytes
/// because that is where the violation would be visible.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn the_interaction_frame_never_enters_the_alternate_screen() {
    let out = drive("clean");
    assert!(
        out.raw_during,
        "the pty was never raw; nothing was exercised"
    );
    assert!(
        !out.screen.contains("\x1b[?1049h"),
        "the interaction frame entered the alternate screen, which the \
         plain-scroller carve-out does not permit during a turn; screen={:?}",
        out.screen
    );
}

#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_clean_close_leaves_the_terminal_exactly_as_it_was_found() {
    let out = drive("clean");
    assert_restored("clean", &out);
    // PR #2799: a raw-mode guard must not consume the caller's input through
    // a cursor query. The release byte must reach the child's own reader.
    assert!(!out.screen.contains("\x1b[6n"), "{:?}", out.screen);
}

/// **The failure path.** The one that turns a bug into a wrecked terminal,
/// and the one least likely to be noticed missing.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_panic_while_the_frame_is_up_still_restores_the_terminal() {
    assert_restored("panic", &drive("panic"));
}

/// **The error-return path.** How a failed `terminal.draw` leaves `present`:
/// the guard is dropped by scope unwind, not by cleanup the author
/// remembered to write.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn an_error_return_while_the_frame_is_up_still_restores_the_terminal() {
    assert_restored("error", &drive("error"));
}

/// **A nested frame must not hand the terminal back while the outer one is
/// still up.**
///
/// The failure this catches is not a leak but its mirror: an over-eager
/// restore. `crossterm::enable_raw_mode` keeps ONE process-global "mode prior
/// to raw" and makes a second call a no-op, so a guard built on it sees the
/// inner `enter` do nothing and the inner `drop` restore GLOBALLY. The outer
/// frame is still drawn, but the terminal is already cooked — keys
/// line-buffered until Enter and echoed by the kernel over the frame, which
/// is exactly the "prompt that looked hung" `modal.rs::RawGuard` documents
/// from #1770.
///
/// Observable only from outside, and only in the window between the two
/// drops, which is why the child holds twice.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_nested_frame_does_not_restore_the_terminal_early() {
    let out = drive_nested();
    assert!(
        out.raw_during_outer,
        "the pty was never raw — the test proved nothing, because it never \
         observed the state that must be preserved"
    );
    assert!(
        out.raw_after_inner_drop,
        "the INNER frame's drop handed the terminal back while the OUTER \
         frame was still up: raw mode was lost mid-modal, so the outer \
         frame's keyboard is line-buffered and kernel-echoed (#1770)"
    );
    assert!(
        !out.raw_after_all,
        "both frames are gone and the terminal is still RAW"
    );
}

/// One `present` lifecycle, captured in PHASES.
///
/// `Pty::screen()` DRAINS the master, so capturing per phase gives the output
/// produced *in that phase* rather than a running transcript. That matters:
/// the grid has no model of erase sequences, so a cumulative capture would
/// still hold the pre-resize frame drawn at the old width and a
/// "nothing exceeds the new width" assertion would fail on history rather
/// than on what the operator can see.
struct Frames {
    /// The first frame, before any resize and before the answer key.
    first: String,
    /// Output produced after the resize (empty when there was none).
    after_resize: String,
    /// Everything from the answer key onwards, including the child's marker.
    tail: String,
    raw_during: bool,
    raw_after: bool,
}

/// Drain for `ticks` x 20ms, answering every cursor-report query that appears
/// in THIS segment.
fn collect(pty: &Pty, ticks: usize) -> String {
    let mut out = String::new();
    let mut answered = 0usize;
    for _ in 0..ticks {
        out.push_str(&pty.screen());
        answer_cursor_report(pty, &out, &mut answered);
        std::thread::sleep(Duration::from_millis(20));
    }
    out
}

/// Drive the real `present` frame on a pty of the given size, optionally
/// resizing once the frame is up, then answer with `key`.
fn drive_present(rows: u16, cols: u16, resize_to: Option<(u16, u16)>, key: &str) -> Frames {
    let pty = Pty::open();
    pty.resize(rows, cols);
    let mut child = spawn_child(&pty, "present");

    let mut first = String::new();
    let mut answered = 0usize;
    let raw_during = {
        let deadline = Instant::now() + REACH_TIMEOUT;
        loop {
            first.push_str(&pty.screen());
            answer_cursor_report(&pty, &first, &mut answered);
            if pty.is_raw() {
                break true;
            }
            if Instant::now() >= deadline {
                break false;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    };
    // Let the first frame land. `collect` owns its own reply counter, and
    // `first` keeps accumulating, so hand it the running one for this segment.
    for _ in 0..30 {
        first.push_str(&pty.screen());
        answer_cursor_report(&pty, &first, &mut answered);
        std::thread::sleep(Duration::from_millis(20));
    }

    let after_resize = match resize_to {
        Some((r, c)) => {
            pty.resize(r, c);
            // A `slave_stdio()` child has no controlling terminal, so
            // TIOCSWINSZ alone delivers no signal — the explicit SIGWINCH is
            // what makes the resize observable rather than merely configured.
            signal_winch(child.id());
            // A FRESH segment, so a fresh reply counter — the viewport
            // re-queries the cursor after a resize and will hang without it.
            collect(&pty, 35)
        }
        None => String::new(),
    };

    pty.type_in(key);
    let mut tail = String::new();
    let _ = std::thread::scope(|scope| {
        let waiter = scope.spawn(|| wait_for_child(&mut child, EXIT_TIMEOUT));
        while !waiter.is_finished() {
            tail.push_str(&pty.screen());
            std::thread::sleep(Duration::from_millis(20));
        }
        waiter.join().expect("child reaper thread")
    });
    std::thread::sleep(Duration::from_millis(120));
    tail.push_str(&pty.screen());

    Frames {
        first,
        after_resize,
        tail,
        raw_during,
        raw_after: pty.is_raw(),
    }
}

/// Frame lines wider than `width`, with libtest's own output excluded.
fn overflowing(segment: &str, width: usize) -> Vec<String> {
    screen_grid(segment)
        .into_iter()
        .filter(|l| !is_harness_noise(l) && l.chars().count() > width)
        .collect()
}

/// **Resize: the frame reflows to the new width and the terminal is still
/// handed back.**
///
/// Two different failures live here, so both are asserted: a frame that
/// ignores SIGWINCH keeps drawing at the old width and corrupts the display,
/// and a frame that handles it but loses its guard leaves the terminal raw.
/// Passing one says nothing about the other.
///
/// The width claim is made on the output produced AFTER the resize, because
/// that is the only segment that describes the resized terminal.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_resize_reflows_the_frame_and_still_restores_the_terminal() {
    const NARROW: usize = 46;
    let f = drive_present(24, 100, Some((12, NARROW as u16)), "d\r");
    assert!(
        f.raw_during,
        "the pty was never raw — nothing was exercised"
    );
    assert!(!f.raw_after, "the terminal was left RAW after a resize");
    // The frame survived the resize rather than wedging: a frame that died on
    // SIGWINCH would never read the key.
    assert!(
        f.tail.contains("OUTCOME:"),
        "the frame did not answer after the resize; tail={:?}",
        f.tail
    );
    assert!(
        !f.after_resize.trim().is_empty(),
        "the frame drew nothing after SIGWINCH — it did not notice the resize"
    );
    let over = overflowing(&f.after_resize, NARROW);
    assert!(
        over.is_empty(),
        "after resizing to {NARROW} columns the frame still drew wider: {over:#?}"
    );
}

/// Grounds the mocked inspection state machine: F4 and Enter must not answer
/// the pending interpreter grant, and returning from inspection must leave the
/// original decision usable on the same real terminal.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn inspect_pending_grant_returns_without_answering() {
    let f = drive_present(24, 100, None, "\x1bOS\r\x1bOSd\r");
    assert!(f.raw_during);
    assert!(!f.raw_after);
    assert!(f.tail.contains("inspect pending request"), "{:?}", f.tail);
    assert!(f.tail.contains("Answer(\"deny\")"), "{:?}", f.tail);
    assert!(!f.tail.contains("Answer(\"allow_once\")"));
}

/// **Narrow width: content degrades legibly rather than corrupting the frame.**
///
/// Asserted on the GRID — cursor positioning applied — because `ratatui`
/// positions text rather than padding it, so a check over stripped escapes
/// would concatenate fragments and measure nothing.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_narrow_terminal_wraps_rather_than_overflowing() {
    const COLS: usize = 28;
    let f = drive_present(20, COLS as u16, None, "d\r");
    assert!(
        f.raw_during,
        "the pty was never raw — nothing was exercised"
    );
    assert!(!f.raw_after, "the terminal was left RAW");

    let over = overflowing(&f.first, COLS);
    assert!(
        over.is_empty(),
        "the frame overflowed a {COLS}-column terminal: {over:#?}"
    );
    // Degrading LEGIBLY means the content is still there, wrapped — not
    // truncated away. Without this, a frame that drew nothing at all would
    // satisfy "nothing overflows".
    let flat = screen_grid(&f.first).join(" ");
    assert!(
        flat.contains("run_command") || flat.contains("bash"),
        "the body vanished at {COLS} columns rather than wrapping: {flat:?}"
    );
    assert!(f.tail.contains("OUTCOME:"), "the frame did not answer");
}

/// Pump until `needle` is on the REPLAYED screen. Not on the byte stream: a
/// fresh frame is painted against an empty back buffer, so ratatui skips the
/// blank cells and emits each word as its own run with a cursor move before
/// it; a two-word label never arrives as one run of bytes.
fn painted(pump: &mut crate::panel_raw_mode_pty_test::Pump<'_>, needle: &str, rows: usize) -> bool {
    let deadline = Instant::now() + REACH_TIMEOUT;
    loop {
        pump.pump();
        if erasing_grid(&pump.transcript, rows)
            .iter()
            .any(|row| row.contains(needle))
        {
            return true;
        }
        if Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

/// What a `committed_frame*` child left on a 24x80 screen: the grid replayed
/// with erases up to the child's `OUTCOME:` marker, the cursor at that point,
/// and the whole byte stream for the failure message.
struct Committed {
    grid: Vec<String>,
    open_grid: Vec<String>,
    cursor: (usize, usize),
    stream: String,
}

/// Drive one `committed_frame*` child. With `answer_queries`, every cursor
/// report is answered truthfully from a replay of what the child painted
/// (`Pump`), as a terminal would; without it the terminal stays silent, which
/// is the fallback the arbiter must never guess through.
fn drive_committed_frame(mode: &str, answer_queries: bool) -> Committed {
    const ROWS: usize = 24;
    let pty = Pty::open();
    pty.resize(ROWS as u16, 80);
    let mut child = spawn_child(&pty, mode);
    let mut pump = crate::panel_raw_mode_pty_test::Pump::new(&pty, answer_queries, ROWS);
    let mut open_grid = Vec::new();
    let result = (|| -> Result<(), String> {
        // The deny option, as the frame spells it: `[d]eny (default)`.
        if !painted(&mut pump, "(default)", ROWS) {
            return Err("the frame never painted its options".into());
        }
        open_grid = erasing_grid(&pump.transcript, ROWS);
        // Enter takes the default (deny); the frame closes and the child
        // commits the line this test is about.
        pty.type_in("\r");
        pump.until("OUTCOME:").ok_or("the frame never answered")?;
        Ok(())
    })();
    let raw_after = pty.is_raw();
    // Release the hold, whatever happened. The child is back in cooked mode
    // by now, so its one-byte read needs a whole line.
    pty.type_in("x\n");
    let status = wait_for_child(&mut child, EXIT_TIMEOUT);
    pump.pump();
    let stream = pump.transcript;
    assert!(result.is_ok(), "{mode}: {result:?}; stream={stream:?}");
    assert!(
        status.is_some_and(|status| status.success()),
        "{mode}: {status:?}; stream={stream:?}"
    );
    assert!(
        !raw_after,
        "{mode}: the terminal was left RAW; stream={stream:?}"
    );
    let before_outcome = stream.split("OUTCOME:").next().unwrap_or_default();
    let (grid, cursor) = erasing_screen(before_outcome, ROWS);
    Committed {
        grid,
        open_grid,
        cursor,
        stream,
    }
}

/// The frame is gone from the replayed screen: none of its chrome or text.
fn assert_frame_erased(mode: &str, c: &Committed) {
    for needle in ["╭", "╰", "run_command", "(default)", "decision required"] {
        assert!(
            !c.grid.iter().any(|row| row.contains(needle)),
            "{mode}: {needle:?} is still on screen after the frame closed: {:#?}\nstream={:?}",
            c.grid,
            c.stream
        );
    }
}

/// The committed line sits directly under the transcript's last row, and the
/// cursor is on the row after it.
fn assert_committed_under(mode: &str, c: &Committed, last: &str) {
    let k = c
        .grid
        .iter()
        .position(|row| row.trim_end() == last)
        .unwrap_or_else(|| panic!("{mode}: {last} is not on screen: {:#?}", c.grid));
    assert_eq!(
        c.grid.get(k + 1).map(|row| row.trim_end()),
        Some("COMMITTED-AFTER-FRAME"),
        "{mode}: the line committed after the frame is not directly under \
         {last}: {:#?}\nstream={:?}",
        c.grid,
        c.stream
    );
    assert_eq!(
        c.cursor,
        (k + 2, 0),
        "{mode}: the cursor did not come back to the transcript: {:#?}",
        c.grid
    );
}

/// **Grounds `place_below_cursor`'s `a_frame_opens_on_the_cursor_row…` row
/// against a real terminal.** The frame opens where the transcript ends, and
/// when it closes the next committed line lands on the row the frame's top
/// row was: no blank band, and nothing of the frame left.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn after_a_frame_the_next_line_prints_directly_under_the_transcript() {
    let c = drive_committed_frame("committed_frame", true);
    assert_committed_under("committed_frame", &c, "TRANSCRIPT-04");
    assert_frame_erased("committed_frame", &c);
    assert!(
        c.grid[6..].iter().all(|row| row.is_empty()),
        "rows under the committed line are not blank: {:#?}",
        c.grid
    );
}

/// #2800: grounds the pure partial-row erase test in the real frame lifecycle.
/// The sentinel has no newline: it must survive both opening and closing,
/// including deficit scrolling, and subsequent output must append to it.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_partial_transcript_line_survives_opening_and_closing_a_frame() {
    for mode in ["committed_frame_partial", "committed_frame_partial_scroll"] {
        let c = drive_committed_frame(mode, true);
        assert!(
            c.open_grid
                .iter()
                .any(|row| row.trim_end() == "PARTIAL-END"),
            "{mode}: opening erased the partial line: {:#?}; stream={:?}",
            c.open_grid,
            c.stream
        );
        let row = c
            .grid
            .iter()
            .position(|row| row.trim_end() == "PARTIAL-ENDCOMMITTED-AFTER-FRAME")
            .unwrap_or_else(|| {
                panic!(
                    "{mode}: closing lost the line or its return column: {:#?}; stream={:?}",
                    c.grid, c.stream
                )
            });
        assert_eq!(c.cursor, (row + 1, 0));
        assert_frame_erased(mode, &c);
    }
}

/// **The operator's report (2026-10-06/07), reproduced.** Something holds
/// the bottom rows, so a bottom-anchored lease was shifted above it and the
/// frame was PARKED rows below the transcript; the next committed line used
/// to land there, under a band of blank rows. With the arbiter placing the
/// rows under the transcript the holder is left alone and the line lands
/// where it belongs. Grounds `a_holder_below_a_frame_that_fits_is_not_a_
/// collision`.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn after_a_frame_beside_a_row_holder_the_next_line_prints_under_the_transcript() {
    let c = drive_committed_frame("committed_frame_held", true);
    assert_committed_under("committed_frame_held", &c, "TRANSCRIPT-04");
    assert_frame_erased("committed_frame_held", &c);
    for r in 0..usize::from(FRAME_HOLDER_ROWS) {
        assert!(
            c.grid[21 + r].contains(&format!("{FRAME_HOLDER_SENTINEL}-{r}")),
            "holder row {r} was erased or overwritten: {:#?}\nstream={:?}",
            c.grid,
            c.stream
        );
    }
}

/// **A frame that does not fit scrolls the transcript, not the other way
/// round.** With the cursor near the bottom the arbiter scrolls the
/// transcript up by exactly the deficit; the committed line still sits under
/// its last row. Grounds `a_frame_that_runs_off_the_bottom_scrolls_the_
/// transcript_by_the_deficit`.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_frame_near_the_bottom_scrolls_the_transcript_and_the_next_line_follows_it() {
    let c = drive_committed_frame("committed_frame_scroll", true);
    assert_committed_under("committed_frame_scroll", &c, "TRANSCRIPT-21");
    assert_frame_erased("committed_frame_scroll", &c);
    assert!(
        !c.grid.iter().any(|row| row.contains("TRANSCRIPT-00")),
        "the frame could not have fit without scrolling, yet row 0 is still \
         there: {:#?}",
        c.grid
    );
}

/// **Contested rows: the frame shifts above the holder, the cursor still
/// comes back.** The transcript's tail is under the frame (that is what a
/// shift costs, and what the pre-arbiter frame did too), the holder's rows
/// are untouched, and the committed line lands where the cursor was. Grounds
/// `contested_rows_follow_the_policy_and_a_shift_still_returns_the_cursor`.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_frame_shifted_above_a_holder_still_returns_the_cursor_to_the_transcript() {
    let c = drive_committed_frame("committed_frame_contested", true);
    assert_eq!(
        c.grid[18].trim_end(),
        "COMMITTED-AFTER-FRAME",
        "the committed line is not on the cursor's row: {:#?}\nstream={:?}",
        c.grid,
        c.stream
    );
    assert_eq!(c.cursor, (19, 0), "{:#?}", c.grid);
    assert_frame_erased("committed_frame_contested", &c);
    for r in 0..usize::from(FRAME_HOLDER_ROWS) {
        assert!(
            c.grid[21 + r].contains(&format!("{FRAME_HOLDER_SENTINEL}-{r}")),
            "holder row {r} was erased or overwritten: {:#?}",
            c.grid
        );
    }
}

/// **A silent terminal gets no guess.** When nothing answers the cursor query
/// the arbiter declines, the frame opens on a bottom-anchored lease as it
/// always did, still answers, and still hands the terminal back. Where the
/// committed line lands is NOT asserted: that is the pre-arbiter behaviour,
/// kept rather than replaced by an invented row.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_terminal_that_does_not_report_the_cursor_still_gets_a_frame_and_no_guess() {
    let c = drive_committed_frame("committed_frame", false);
    assert!(
        c.grid
            .iter()
            .any(|row| row.trim_end() == "COMMITTED-AFTER-FRAME"),
        "{:#?}",
        c.grid
    );
    assert_frame_erased("committed_frame/silent", &c);
}

/// Drive the active-turn lifecycle: spinner up, then the frame opens over it.
///
/// Returns (whole stream, index where the frame began, tail, raw-during,
/// raw-after). The caller asserts on the stream AFTER the frame began, which
/// is the only window in which a spinner glyph means anything: before it, the
/// spinner is *supposed* to be painting.
fn drive_active_turn(key: &str) -> (String, usize, String, bool, bool) {
    let pty = Pty::open();
    pty.resize(24, 100);
    let mut child = spawn_child(&pty, "active_turn");

    // Wait for the SPINNER first — braille frames on the wire mean a live
    // ephemeral writer, which is the precondition this scenario needs. Waiting
    // for raw mode instead would race: the frame takes raw only later.
    let mut all = String::new();
    let saw_spinner = {
        let deadline = Instant::now() + REACH_TIMEOUT;
        loop {
            all.push_str(&pty.screen());
            if all.chars().any(|c| ('\u{2800}'..='\u{28FF}').contains(&c)) {
                break true;
            }
            if Instant::now() >= deadline {
                break false;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    };
    assert!(
        saw_spinner,
        "no spinner frames appeared — the scenario never had a live writer to \
         be interrupted by, so it would prove nothing; screen={all:?}"
    );

    // Keep draining (and answering the viewport's cursor query) until the
    // child has answered and exited.
    let mut answered = 0usize;
    let mut raw_during = false;
    let deadline = Instant::now() + REACH_TIMEOUT;
    while Instant::now() < deadline {
        all.push_str(&pty.screen());
        answer_cursor_report(&pty, &all, &mut answered);
        if pty.is_raw() {
            raw_during = true;
        }
        // The frame is up once it has queried the cursor AND drawn.
        if raw_during && all.contains("\u{1b}[6n") {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    // Let the frame settle, so the window under test contains real frames
    // rather than only the instant of its first draw.
    for _ in 0..25 {
        all.push_str(&pty.screen());
        answer_cursor_report(&pty, &all, &mut answered);
        std::thread::sleep(Duration::from_millis(20));
    }

    // The frame BEGINS at its cursor query: `suspend_for_prompt` has already
    // erased and quiesced every ephemeral writer by then, so any spinner glyph
    // from here on is a writer that woke up and painted over the frame.
    let frame_start = all.find("\u{1b}[6n").expect("the frame queried the cursor");

    pty.type_in(key);
    let mut tail = String::new();
    let _ = std::thread::scope(|scope| {
        let waiter = scope.spawn(|| wait_for_child(&mut child, EXIT_TIMEOUT));
        while !waiter.is_finished() {
            tail.push_str(&pty.screen());
            std::thread::sleep(Duration::from_millis(20));
        }
        waiter.join().expect("child reaper thread")
    });
    std::thread::sleep(Duration::from_millis(120));
    tail.push_str(&pty.screen());
    (all, frame_start, tail, raw_during, pty.is_raw())
}

/// **An interaction arriving mid-turn is not painted over by the turn.**
///
/// #1312 measured what this costs: a permission prompt rendered invisibly
/// underneath a spinner that overwrote it ~8x/second, and an operator with no
/// way to see what they were being asked. `prompt_visibility_test` pins it for
/// the plain prompt; this pins it for the rich frame, whose failure mode is
/// worse — a widget frame half-overwritten by braille is not merely hidden,
/// it is unreadable.
///
/// The assertion is the same one that tier established: **no spinner glyph
/// may appear once the frame is up.** `suspend_for_prompt` erases every
/// registered ephemeral writer and holds them quiesced for the window's
/// lifetime, so a single braille character after that point means a writer
/// woke up and painted over the frame.
#[serial_test::serial(interaction_pty)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_frame_opened_mid_turn_is_not_painted_over_by_the_spinner() {
    let (all, frame_start, tail, raw_during, raw_after) = drive_active_turn("d\r");

    assert!(raw_during, "the frame never took raw mode");
    assert!(!raw_after, "the terminal was left RAW");
    assert!(
        tail.contains("OUTCOME:"),
        "the frame never answered; tail={tail:?}"
    );

    // The window under test: everything the terminal was shown from the
    // frame's first cursor query onward. Before that point the spinner is
    // SUPPOSED to be painting, so including it would fail every run.
    let window = &all[frame_start..];

    // The frame is actually THERE — without this, a run where the frame never
    // drew would satisfy "no spinner glyphs" trivially.
    let grid = screen_grid(window).join(" ");
    assert!(
        grid.contains("run_command") || grid.contains("allow once"),
        "the frame did not draw over the spinner: {grid:?}"
    );
    // ...and the spinner really was running before it, or there was nothing
    // to be interrupted by.
    assert!(
        all[..frame_start]
            .chars()
            .any(|c| ('\u{2800}'..='\u{28FF}').contains(&c)),
        "no spinner ran before the frame opened; the scenario is vacuous"
    );

    let intruders: Vec<char> = window
        .chars()
        .filter(|c| ('\u{2800}'..='\u{28FF}').contains(c))
        .collect();
    assert!(
        intruders.is_empty(),
        "a spinner frame painted over the interaction frame after it opened — \
         the #1312 failure, where the operator cannot read what they are being \
         asked; intruders={intruders:?}"
    );
}