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
use super::*;
use crate::cockpit::test_tty::{
    echoes, is_canonical, mode_diff, modes_equal, set_canonical_echo, termios_of, TestTty,
};

const CTRL_C: &[u8] = &[0x03];

/// Grounds the pager's row model and modal reservation in the real cockpit:
/// cursor-addressed rows must reach the operator tty, own input through resize,
/// and disappear before the restored composer accepts its next submission.
/// Primary-screen history must survive both unchanged and resized pager visits.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[cfg(feature = "live-spill")]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn completed_spill_pager_owns_the_terminal_through_resize_and_close() {
    crate::interaction_view_pty_test::drive_cockpit_pager();
}

#[cfg(feature = "live-spill")]
pub(crate) fn cockpit_pager_case() {
    // This disposable child owns the tty queried by Crossterm's geometry API.
    assert!(unsafe { libc::setsid() } >= 0);
    assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSCTTY as _, 0) }, 0);
    let before = termios_of(0);
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");
    cockpit
        .screen
        .insert_rows(vec![b"HISTORY_BEFORE_PAGER".to_vec()])
        .unwrap();
    cockpit.draw().unwrap();
    let (to_ui, requests) = std::sync::mpsc::sync_channel(8);
    let worker = std::thread::spawn(move || {
        let mut remote = crate::session_worker::RemoteSurface::new(to_ui);
        let archive = crate::completed_spill::CompletedSpillArchive::default();
        let body = (0..50)
            .map(|i| format!("spill-row-{i:02}\n"))
            .collect::<String>();
        let id = archive.retain(&body);
        crate::transcript_pager::run_output_pager(&archive.get(id).unwrap(), &mut remote, true)
            .unwrap();
        println!("PAGER_RETURNED");
        match remote.read_line("after pager").unwrap() {
            ReadOutcome::Line(line) => assert_eq!(line, "after-view", "modal keys leaked"),
            other => panic!("pager left the editor unusable: {other:?}"),
        }
    });
    cockpit.run(&requests).unwrap();
    worker.join().unwrap();
    assert!(
        modes_equal(&before, &termios_of(0)),
        "exact termios restore"
    );
    println!("PAGER_RESTORED");
    // Let the parent sample modes before session-leader exit hangs up the tty.
    std::io::stdin().read_line(&mut String::new()).unwrap();
}

/// #2489: `/psyche` once drew through its OWN inline viewport on the captured
/// stdout while the cockpit owned the screen — two writers, so the title
/// stacked and rows interleaved. Every other panel takes the presenter's lent
/// window; this pins that `/psyche` does too, on a real tty.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the seam test
/// `psyche_panel_uses_the_surface_window`, which is the fast-path gate.
#[cfg(feature = "rich-tui")]
#[serial_test::serial(tty_arbiter, prompt_stdin)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn psyche_panel_draws_once_in_the_lent_rows_under_the_cockpit() {
    crate::interaction_view_pty_test::drive_cockpit_psyche();
}

#[cfg(feature = "rich-tui")]
pub(crate) fn cockpit_psyche_case() {
    use crate::chat::InputSurface as _;
    // This disposable child owns the tty queried by Crossterm's geometry API.
    assert!(unsafe { libc::setsid() } >= 0);
    assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSCTTY as _, 0) }, 0);
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");
    cockpit.draw().unwrap();
    let (to_ui, requests) = std::sync::mpsc::sync_channel(8);
    let worker = std::thread::spawn(move || {
        let mut remote = crate::session_worker::RemoteSurface::new(to_ui);
        let window = remote.open_panel(crate::session_worker::PanelMode::Inline(
            crate::config_panel::PANEL_HEIGHT,
        ));
        assert!(window.is_some(), "the cockpit must lend rows for /psyche");
        let seed = crate::config_panel::PanelSeed {
            via: "/psyche",
            personas: Vec::new(),
            current_persona: None,
            backend: Some("sol".to_string()),
            base_initiative: newt_core::initiative::Initiative::default(),
            initiative_from_family: false,
            models: None,
            current_model: String::new(),
            personality: Default::default(),
        };
        let outcome = crate::config_panel::run(
            seed,
            |_, _, _| crate::config_panel::SaveResult::Failed("unused".into()),
            window,
        )
        .unwrap();
        println!("PSYCHE_RETURNED:{outcome:?}");
        match remote.read_line("after panel").unwrap() {
            ReadOutcome::Line(line) => assert_eq!(line, "after-psyche", "panel keys leaked"),
            other => panic!("panel left the editor unusable: {other:?}"),
        }
    });
    cockpit.run(&requests).unwrap();
    worker.join().unwrap();
    println!("PSYCHE_RESTORED");
    std::io::stdin().read_line(&mut String::new()).unwrap();
}

/// Grounds the mounted editor's submission and escape-ladder key tests in a
/// real tty: crossterm may already hold input after a terminal query or poll,
/// leaving the kernel fd empty. Both Enter and Ctrl-C must work without a
/// subsequent key, while another stdin owner must still keep those events.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn buffered_paste_enter_and_interrupt_do_not_need_another_key() {
    crate::interaction_view_pty_test::drive_cockpit_buffered_input();
}

pub(crate) fn cockpit_buffered_input_case() {
    let result = std::panic::catch_unwind(buffered_input_case);
    if let Err(error) = result {
        // The owned tty/capture have now restored stdout. Keep the actual
        // failing assertion visible to the parent disposable-process harness.
        let message = error
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| error.downcast_ref::<&str>().copied())
            .unwrap_or("non-text panic");
        println!("BUFFERED_INPUT_FAILURE:{message}");
        std::panic::resume_unwind(error);
    }
}

fn buffered_input_case() {
    let tty = TestTty::install();
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");
    let prefetch = |bytes: &[u8]| {
        let _stdin = newt_core::tty::try_watch_stdin().expect("prefetch owns stdin");
        tty.type_bytes(bytes);
        assert!(event::poll(Duration::from_secs(1)).unwrap());
        let mut fd = libc::pollfd {
            fd: libc::STDIN_FILENO,
            events: libc::POLLIN,
            revents: 0,
        };
        // SAFETY: fd 0 is the test's owned tty. This observes readiness only.
        assert_eq!(
            unsafe { libc::poll(&mut fd, 1, 0) },
            0,
            "input must already be buffered by crossterm"
        );
    };

    let (reply, received) = std::sync::mpsc::sync_channel(1);
    cockpit
        .handle_request(SurfaceRequest::ReadLine {
            prompt: "buffered input".into(),
            reply,
        })
        .unwrap();
    prefetch(b"\x1b[200~atomic paste\x1b[201~\r");
    cockpit.poll_keys().unwrap();
    assert!(
        matches!(received.try_recv(), Ok(Ok(ReadOutcome::Line(line))) if line == "atomic paste"),
        "buffered paste and Enter must submit without another terminal byte"
    );

    let cancel = Arc::new(AtomicBool::new(false));
    cockpit
        .handle_request(SurfaceRequest::TurnStarted {
            cancel: Arc::clone(&cancel),
        })
        .unwrap();
    // Grounds the archive snapshot and read-only key tests in a real tty:
    // F4 during an active turn, Enter to inspect, q back, q close must leave
    // the mounted draft, pending read, and cancellation flag untouched.
    #[cfg(feature = "live-spill")]
    {
        let archive = Arc::new(crate::completed_spill::CompletedSpillArchive::default());
        archive.retain("operator inspection payload");
        cockpit
            .handle_request(SurfaceRequest::SetSpillArchive(archive))
            .unwrap();
        let (reply, inspected) = std::sync::mpsc::sync_channel(1);
        cockpit
            .handle_request(SurfaceRequest::ReadLine {
                prompt: "inspect".into(),
                reply,
            })
            .unwrap();
        cockpit
            .on_event(Event::Paste("unsent draft".into()))
            .unwrap();
        let draft = cockpit.editor.draft();
        prefetch(b"\x1bOS\rqq");
        cockpit.poll_keys().unwrap();
        assert_eq!(cockpit.editor.draft(), draft);
        assert!(cockpit.queued.is_empty());
        assert!(matches!(
            inspected.try_recv(),
            Err(std::sync::mpsc::TryRecvError::Empty)
        ));
        assert!(!cancel.load(Ordering::SeqCst));
    }
    prefetch(CTRL_C);
    {
        let _other_reader = newt_core::tty::try_watch_stdin().expect("another reader owns stdin");
        cockpit.poll_keys().unwrap();
        assert!(
            !cancel.load(Ordering::SeqCst),
            "the cockpit must respect stdin ownership"
        );
    }
    cockpit.poll_keys().unwrap();
    assert!(
        cancel.load(Ordering::SeqCst),
        "buffered Ctrl-C must interrupt without another terminal byte"
    );

    // An invalid tty must fail before crossterm can enter its EOF read loop.
    // Restore the owned fd before checking the result or dropping the cockpit.
    let saved = unsafe { libc::dup(libc::STDIN_FILENO) };
    assert!(saved >= 0);
    assert_eq!(unsafe { libc::close(libc::STDIN_FILENO) }, 0);
    let closed = cockpit.poll_keys();
    assert_eq!(unsafe { libc::dup2(saved, libc::STDIN_FILENO) }, 0);
    unsafe { libc::close(saved) };
    assert!(matches!(closed, Err(error) if error.kind() == io::ErrorKind::BrokenPipe));
}

/// #2540 round 2 item 2 (red first): the clarification modal's real terminal
/// input path — the tier that caught NOTHING before this round, because
/// `clarification_modal`'s own unit tests drive `FreeTextInput` with
/// synthetic `Event::Key`/`Event::Paste` values, never a real device. Driven
/// live (Herdr pane, release build) the modal rendered correctly and then
/// could neither be answered nor left: a paste echoed as literal
/// `^[[200~…^[[201~`, Enter as literal `^M`, Esc/Ctrl-C/Ctrl-U did nothing.
/// This types an ordinal answer + Enter, pastes a bracketed `/discuss …` +
/// Enter, presses Esc, and checks `stty -g` afterward — the four things
/// measured broken live.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn the_clarification_modal_can_be_answered_pasted_into_and_escaped() {
    crate::interaction_view_pty_test::drive_cockpit_clarification_input();
}

pub(crate) fn cockpit_clarification_input_case() {
    let result = std::panic::catch_unwind(clarification_input_case);
    if let Err(error) = result {
        let message = error
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| error.downcast_ref::<&str>().copied())
            .unwrap_or("non-text panic");
        println!("CLARIFICATION_INPUT_FAILURE:{message}");
        std::panic::resume_unwind(error);
    }
}

fn clarification_input_case() {
    let tty = TestTty::install();
    let before = termios_of(0);
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");

    // 1: a typed ordinal answer + Enter must reach the clarification path.
    // A unique batch marker per round, so `type_when_painted`'s whole-buffer
    // scan (the painted transcript only ever grows across these three
    // rounds) cannot fire early on a marker an EARLIER round already drew.
    let (reply, received) = std::sync::mpsc::sync_channel(1);
    let typer = tty.type_when_painted("CLAR_ROUND_ONE", b"1: keep the index\r");
    cockpit
        .handle_request(SurfaceRequest::PresentClarification {
            batch: "CLAR_ROUND_ONE\n1: keep the index\n2: rebuild it".into(),
            hint: "ordinal locks it".into(),
            prompt: String::new(),
            color: false,
            verbose: false,
            reply,
        })
        .unwrap();
    assert!(
        typer.join().expect("round-one prompt watcher"),
        "the modal must reach the real terminal before input is sent"
    );
    assert!(
        matches!(received.try_recv(), Ok(Ok(ReadOutcome::Line(line))) if line == "1: keep the index"),
        "a typed ordinal + Enter must reach the clarification path, not \
         literal bytes: {:?}",
        received.try_recv()
    );

    // 2: a bracketed paste of `/discuss …` + Enter must reach the path too —
    // decoded as ONE `Event::Paste`, not the escape markers themselves typed
    // character by character.
    let (reply2, received2) = std::sync::mpsc::sync_channel(1);
    let typer2 = tty.type_when_painted(
        "CLAR_ROUND_TWO",
        b"\x1b[200~/discuss why the plan changed\x1b[201~\r",
    );
    cockpit
        .handle_request(SurfaceRequest::PresentClarification {
            batch: "CLAR_ROUND_TWO\n1: keep the index".into(),
            hint: "ordinal locks it".into(),
            prompt: String::new(),
            color: false,
            verbose: false,
            reply: reply2,
        })
        .unwrap();
    assert!(
        typer2.join().expect("round-two prompt watcher"),
        "the modal must reach the real terminal before input is sent"
    );
    assert!(
        matches!(received2.try_recv(), Ok(Ok(ReadOutcome::Line(line))) if line == "/discuss why the plan changed"),
        "a bracketed paste + Enter must reach the clarification path, not \
         raw escape bytes: {:?}",
        received2.try_recv()
    );

    // 3: Esc must dismiss — the caller gets an ordinary answer back, not a
    // modal the operator cannot leave.
    let (reply3, received3) = std::sync::mpsc::sync_channel(1);
    let typer3 = tty.type_when_painted("CLAR_ROUND_THREE", b"\x1b");
    cockpit
        .handle_request(SurfaceRequest::PresentClarification {
            batch: "CLAR_ROUND_THREE\n1: keep the index".into(),
            hint: "ordinal locks it".into(),
            prompt: String::new(),
            color: false,
            verbose: false,
            reply: reply3,
        })
        .unwrap();
    assert!(
        typer3.join().expect("round-three prompt watcher"),
        "the modal must reach the real terminal before input is sent"
    );
    assert!(
        matches!(received3.try_recv(), Ok(Ok(ReadOutcome::Line(line))) if line.is_empty()),
        "Esc must dismiss to an ordinary (empty) answer, not trap the \
         operator: {:?}",
        received3.try_recv()
    );

    drop(cockpit);
    // 4: the terminal must come back byte-for-byte itself after all three
    // rounds — `stty -g` identical to before the first modal opened.
    assert!(
        modes_equal(&before, &termios_of(0)),
        "exact termios restore after the clarification modal"
    );
    println!("CLARIFICATION_INPUT_RESTORED");
}

/// Grounds surface forwarding in a real foreground terminal: the external
/// command reads operator input, receives its own interrupt/EOF, and gives
/// the keyboard and exact terminal mode back to the mounted editor.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn bang_commands_lend_the_terminal_and_restore_the_editor() {
    crate::interaction_view_pty_test::drive_cockpit_bang();
}

pub(crate) fn cockpit_bang_case() {
    // Only this disposable child owns the PTY. Job-control signals must be
    // generated by the terminal, not simulated by killing the subprocess.
    assert!(unsafe { libc::setsid() } >= 0);
    assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSCTTY as _, 0) }, 0);
    let before = termios_of(0);
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let cockpit = Presenter::open(surface).expect("cockpit");
    let (to_ui, requests) = std::sync::mpsc::sync_channel(8);
    let worker = std::thread::spawn(move || {
        let mut remote = crate::session_worker::RemoteSurface::new(to_ui);
        for step in 0..8 {
            let command = format!(
                "printf 'BANG_READY_{step}>'; IFS= read -r answer; result=$?; \
                 printf '\\nBANG_READ_{step}:%s:%s\\n' \"$result\" \"$answer\"; exit $result"
            );
            if step < 4 {
                remote.run_bang_escape(&command, false, false).unwrap();
            } else {
                // The configured-login path must lend the same real tty and
                // report failure/interrupt so the manager reconnects only on
                // success. Fixed fixture argv; no server-controlled shell.
                let success = remote
                    .run_login_argv(&["/bin/sh".into(), "-c".into(), command], false, false)
                    .unwrap();
                assert_eq!(success, matches!(step, 4 | 7));
            }
            assert_eq!(unsafe { libc::tcgetpgrp(0) }, unsafe { libc::getpgrp() });
            println!("BANG_RETURN_{step}");
            match remote.read_line("after bang").unwrap() {
                ReadOutcome::Line(line) => assert_eq!(line, format!("next-{step}")),
                other => panic!("bang left the editor unusable: {other:?}"),
            }
        }
    });
    cockpit.run(&requests).unwrap();
    worker.join().unwrap();
    assert!(
        modes_equal(&before, &termios_of(0)),
        "exact termios restore"
    );
    println!("BANG_RESTORED");
    // A controlling session's exit hangs up its tty on macOS. Let the parent
    // sample the restored device before that independent kernel transition.
    std::io::stdin().read_line(&mut String::new()).unwrap();
}

/// Grounds the mocked modal reservation geometry: a real panel may consume
/// resize events while the presenter is parked, so release must read the tty
/// dimensions before restoring the preserved draft.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[serial_test::serial(tty_arbiter, prompt_stdin)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn panel_release_resynchronizes_terminal_size_before_restoring_draft() {
    crate::interaction_view_pty_test::drive_cockpit_resize();
}

// Crossterm retains a process-global event source. Run the extra owned tty
// in the existing child harness so it cannot bind the next cockpit test's
// keyboard to a tty that this case has already closed.
pub(crate) fn panel_resize_case() {
    let _tty = TestTty::install();
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");
    cockpit
        .editor
        .on_event(
            Event::Paste("draft survives resize".into()),
            &mut cockpit.screen,
        )
        .unwrap();
    let draft = cockpit.editor.draft();
    let (reply, received) =
        std::sync::mpsc::sync_channel::<Option<crate::session_worker::PanelWindow>>(1);
    let panel = std::thread::spawn(move || {
        let window = received.recv().unwrap().expect("reserved panel");
        let size = libc::winsize {
            ws_row: 12,
            ws_col: 46,
            ws_xpixel: 0,
            ws_ypixel: 0,
        };
        // SAFETY: TestTty installed this test's owned slave on fd 0; no live
        // developer terminal is touched. The parent waits before dropping it.
        assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSWINSZ, &size) }, 0);
        drop(window);
    });
    cockpit
        .handle_request(SurfaceRequest::Panel {
            mode: PanelMode::Inline(8),
            reply,
        })
        .unwrap();
    panel.join().unwrap();
    assert_eq!((cockpit.screen.cols, cockpit.screen.rows), (46, 12));
    assert_eq!(cockpit.editor.draft(), draft);
    assert!(!cockpit.chat_inactive);
    assert!(cockpit.screen.viewport_rect().bottom() <= 12);
}

/// #2571: a panel follows the terminal while it is OPEN, not only on release.
/// Shrink then grow a real tty under a live inline panel; each re-measure must
/// hand back the panel's rows anchored at the new bottom, at the new width.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds `PanelWindow`'s mocked
/// remeasure tests and `panel::classify`, which cannot observe a real
/// terminal's size.
#[serial_test::serial(tty_arbiter, prompt_stdin)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn an_open_panel_follows_the_terminal_through_shrink_and_grow() {
    crate::interaction_view_pty_test::drive_cockpit_live_resize();
}

pub(crate) fn panel_live_resize_case() {
    let _tty = TestTty::install();
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");
    cockpit
        .editor
        .on_event(
            Event::Paste("draft survives a live resize".into()),
            &mut cockpit.screen,
        )
        .unwrap();
    let draft = cockpit.editor.draft();
    let (reply, received) =
        std::sync::mpsc::sync_channel::<Option<crate::session_worker::PanelWindow>>(1);
    let panel = std::thread::spawn(move || {
        let window = received.recv().unwrap().expect("reserved panel");
        let resize = |rows: u16, cols: u16| {
            let size = libc::winsize {
                ws_row: rows,
                ws_col: cols,
                ws_xpixel: 0,
                ws_ypixel: 0,
            };
            // SAFETY: TestTty installed this test's owned slave on fd 0; no
            // live developer terminal is touched.
            assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSWINSZ, &size) }, 0);
        };
        resize(12, 46);
        window.remeasure(None);
        assert_eq!(
            window.area(),
            ratatui::layout::Rect::new(0, 4, 46, 8),
            "shrink"
        );
        resize(30, 100);
        window.remeasure(None);
        assert_eq!(
            window.area(),
            ratatui::layout::Rect::new(0, 22, 100, 8),
            "grow"
        );
        window.remeasure(None);
        assert_eq!(
            window.area(),
            ratatui::layout::Rect::new(0, 22, 100, 8),
            "no change"
        );
        drop(window);
    });
    cockpit
        .handle_request(SurfaceRequest::Panel {
            mode: PanelMode::Inline(8),
            reply,
        })
        .unwrap();
    panel.join().unwrap();
    assert_eq!((cockpit.screen.cols, cockpit.screen.rows), (100, 30));
    assert_eq!(cockpit.editor.draft(), draft);
    assert!(!cockpit.chat_inactive);
    assert!(cockpit.screen.viewport_rect().bottom() <= 30);

    // #2574 review: an alternate-screen loan owns the whole screen. Its
    // resize contract is the presenter's own resize — re-measuring hands back
    // the whole NEW screen, and no inline rows are reserved for it.
    let (reply, received) =
        std::sync::mpsc::sync_channel::<Option<crate::session_worker::PanelWindow>>(1);
    let alternate = std::thread::spawn(move || {
        let window = received.recv().unwrap().expect("alternate-screen loan");
        let size = libc::winsize {
            ws_row: 20,
            ws_col: 70,
            ws_xpixel: 0,
            ws_ypixel: 0,
        };
        // SAFETY: as above — this test's own slave on fd 0.
        assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSWINSZ, &size) }, 0);
        window.remeasure(None);
        assert_eq!(window.area(), ratatui::layout::Rect::new(0, 0, 70, 20));
        window.remeasure(Some(5));
        assert_eq!(
            window.area(),
            ratatui::layout::Rect::new(0, 0, 70, 20),
            "a height request does not shrink a full-screen loan"
        );
        drop(window);
    });
    cockpit
        .handle_request(SurfaceRequest::Panel {
            mode: PanelMode::AlternateScreen,
            reply,
        })
        .unwrap();
    alternate.join().unwrap();
    assert_eq!((cockpit.screen.cols, cockpit.screen.rows), (70, 20));
    assert_eq!(cockpit.editor.draft(), draft);
}

/// #2632 review finding 1: a same-size resize notification, and a
/// height-only shrink that still leaves the block room, must not move the
/// block away from the content it sits under — that is exactly how the
/// #2441 blank canyon reappeared with no terminal movement at all. Grounds
/// `resize_new_top`'s mocked arithmetic against a real `Presenter` and a
/// real terminal (`cockpit.screen.top`), which a pure-function test cannot
/// observe end to end.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY).
#[serial_test::serial(tty_arbiter, prompt_stdin)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_same_size_resize_does_not_move_the_block_away_from_its_content_2632() {
    let _tty = TestTty::install();
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");

    let content_top = cockpit.screen.top;
    let block_h = cockpit.screen.block_h;
    let (cols, rows) = (cockpit.screen.cols, cockpit.screen.rows);

    // A same-size resize notification: nothing moved on the real terminal,
    // so the block must stay exactly where the content ends.
    cockpit.on_event(Event::Resize(cols, rows)).unwrap();
    assert_eq!(
        cockpit.screen.top, content_top,
        "a same-size resize must not recreate the #2441 gap"
    );

    // A height-only shrink that still leaves room for the block at its old,
    // non-bottom position must not re-anchor it to the new bottom.
    let shrunk = rows - 2;
    assert!(
        content_top + block_h <= shrunk,
        "test precondition: the block still fits after the shrink"
    );
    cockpit.on_event(Event::Resize(cols, shrunk)).unwrap();
    assert_eq!(
        cockpit.screen.top, content_top,
        "a partial shrink that still fits must not re-anchor to the bottom"
    );
}

/// #2573 review: the whole panel path on a real terminal — the cockpit lends
/// rows, `panel::drive` runs a real panel through its own event loop, and the
/// parent resizes and types. Grounds `panel::classify`, `PanelWindow`'s
/// remeasure tests and `panel_erase_from`, none of which can observe a real
/// terminal's resize, rendered cells or restored modes.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load).
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_driven_panel_survives_resizes_keeps_its_selection_and_hands_back_the_draft() {
    crate::interaction_view_pty_test::drive_cockpit_panel_loop();
}

/// #2573 hardening: closing a panel leaves the transcript above it and none
/// of the panel (replayed with erases, no zoom, no resize).
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load).
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn closing_a_panel_leaves_the_transcript_above_it_and_none_of_the_panel() {
    crate::interaction_view_pty_test::drive_cockpit_panel_close();
}

pub(crate) fn cockpit_panel_loop_case() {
    // This disposable child owns the tty queried by Crossterm's geometry API.
    assert!(unsafe { libc::setsid() } >= 0);
    assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSCTTY as _, 0) }, 0);
    let before = termios_of(0);
    let surface = crate::rich_input::RichSurface::new(None).expect("rich surface");
    let mut cockpit = Presenter::open(surface).expect("cockpit");
    cockpit
        .screen
        .insert_rows(vec![b"HISTORY_ABOVE_PANEL".to_vec()])
        .unwrap();
    cockpit
        .editor
        .on_event(
            Event::Paste("draft-survives-the-panel".into()),
            &mut cockpit.screen,
        )
        .unwrap();
    cockpit.draw().unwrap();
    let (to_ui, requests) = std::sync::mpsc::sync_channel(8);
    let worker = std::thread::spawn(move || {
        let mut remote = crate::session_worker::RemoteSurface::new(to_ui);
        let window = crate::chat::InputSurface::open_panel(&mut remote, PanelMode::Inline(8));
        let rows = (0..30).map(|n| format!("panel-row-{n:02}")).collect();
        let mut panel = crate::lines_panel::LinesPanel::new("loop", rows);
        crate::panel::drive(&mut panel, 8, window.as_ref()).unwrap();
        drop(window);
        println!("PANEL_CLOSED");
        match remote.read_line("after panel").unwrap() {
            ReadOutcome::Line(line) => assert_eq!(line, "draft-survives-the-panel"),
            other => panic!("the panel lost the draft: {other:?}"),
        }
    });
    cockpit.run(&requests).unwrap();
    worker.join().unwrap();
    assert!(
        modes_equal(&before, &termios_of(0)),
        "exact termios restore"
    );
    println!("PANEL_LOOP_RESTORED");
    // Let the parent sample modes before session-leader exit hangs up the tty.
    std::io::stdin().read_line(&mut String::new()).unwrap();
}

/// The three properties #1744 turns on, proven on one real terminal with
/// one cockpit: Ctrl-C's two tiers, a modal occluding the composer, and the
/// terminal handed back exactly as it was found.
/// Grounds the modal reservation and interaction-renderer buffer tests in
/// real terminal output, including the frame visible before an answer.
/// Also grounds transcript style carry through the real captured stdout PTY.
///
/// #1959: also serialized on `prompt_stdin` — this test constructs a real
/// `PromptWindow` via `Terminal::suspend_for_prompt`, which bumps the same
/// process-global counter
/// `permission_prompt_tests::headless_and_piped_sessions_never_construct_a_prompt_window`
/// asserts is untouched.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[serial_test::serial(tty_arbiter, prompt_stdin)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn the_cockpit_owns_the_terminal_correctly_and_gives_it_back() {
    crate::interaction_view_pty_test::drive_cockpit_acceptance();
}

// The capture temporarily redirects process-wide stdout. Isolate its lifetime
// from libtest's parallel result writer: a blocked write to the undrained
// capture can otherwise keep dup2 from restoring fd 1 during teardown.
pub(crate) fn cockpit_acceptance_case() {
    let result = std::panic::catch_unwind(acceptance_case);
    if let Err(error) = result {
        // The inner fixture has restored stdout after unwinding its owned
        // terminal. Preserve the assertion for the parent, whose child stderr
        // is intentionally disconnected from the terminal under test.
        let message = error
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| error.downcast_ref::<&str>().copied())
            .unwrap_or("non-text panic");
        println!("COCKPIT_ACCEPTANCE_FAILURE:{message}");
        std::panic::resume_unwind(error);
    }
}

fn acceptance_case() {
    let tty = TestTty::install();
    // This disposable child owns the tty queried by Crossterm's geometry API.
    //
    // `Presenter::open` asks `crossterm::terminal::size()` FIRST, and crossterm
    // 0.28 resolves that to `open("/dev/tty")` directly (not stdin) in
    // `window_size()`. `/dev/tty` is the process's *controlling* terminal; the
    // parent hands this child fd 0/1 as a pty slave but does NOT make it the
    // controlling terminal (that needs `setsid` + `TIOCSCTTY`). Without one the
    // open returns ENXIO, `size()?` errors, `Presenter::open` fails, and the
    // child panics with "cockpit failed to open" — which is exactly the macOS
    // real-PTY failure (the self-hosted Linux ARC runner happens to have a
    // controlling terminal, so it passed; the macos-latest runner does not).
    //
    // The `setsid`/`TIOCSCTTY` MUST follow `TestTty::install()`, which puts the
    // fresh pty on fd 0: setting the controlling terminal on the inherited
    // slave instead would make crossterm report the inherited slave's 50x200
    // size rather than the 24x80 the app actually paints into. Every other PTY
    // child sets this up before opening the terminal; this one had to, and was
    // missing it. `setsid()` returns the new session id (its own pid) on
    // success, not 0, so `>= 0` is the same guard the other PTY cases use.
    assert!(
        unsafe { libc::setsid() } >= 0,
        "setsid for the controlling tty"
    );
    assert_eq!(unsafe { libc::ioctl(0, libc::TIOCSCTTY as _, 0) }, 0);
    // The child now owns the controlling terminal, so on exit the tty driver
    // sends SIGHUP to the session (the "session-leader exit hangs up its tty"
    // hazard the other cases dodge by blocking on a `read_line` tail so the
    // parent samples first). This case is driven by `drive_cockpit_case`, which
    // asserts the child exited *successfully* and only then drains the screen,
    // so the child must NOT die from that SIGHUP: ignore it so the child exits
    // with status 0 and the parent samples restoration from the already-written
    // pty buffer after the child is gone.
    unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
    newt_core::tty::set_interrupt_pending(false);

    // A shell's terminal: canonical, echoing.
    set_canonical_echo(0);
    let before = termios_of(0);
    assert!(
        is_canonical(0) && echoes(0),
        "precondition: the terminal starts as a shell hands it over"
    );

    let dir = std::env::temp_dir().join(format!("newt-cockpit-acceptance-{}", std::process::id()));
    let _ = std::fs::create_dir_all(&dir);
    let surface =
        crate::rich_input::RichSurface::new(Some(dir.join("history"))).expect("rich surface");

    {
        let mut cockpit = match Presenter::open(surface) {
            Ok(p) => p,
            Err(e) => panic!(
                "cockpit failed to open: {e}; master saw {:?}",
                tty.painted()
            ),
        };

        // ---- the terminal is genuinely taken ----
        assert!(!is_canonical(0), "the cockpit runs the terminal raw");
        assert!(!echoes(0), "and the kernel is not echoing over the editor");

        use crossterm::style::{Attribute, Color};
        use newt_core::tty::theme::{self, Role, Theme};
        let mut custom = Theme::builtin().overlaid(
            "test",
            &[
                (
                    Role::Thinking,
                    Color::Rgb {
                        r: 12,
                        g: 34,
                        b: 56,
                    },
                ),
                (
                    Role::AgentText,
                    Color::Rgb {
                        r: 78,
                        g: 90,
                        b: 123,
                    },
                ),
            ],
        );
        let mut thinking = custom.style(Role::Thinking);
        thinking.attributes.set(Attribute::Italic);
        custom.set_style(Role::Thinking, thinking);
        let first_style = custom.ansi(Role::Thinking);
        let answer_style = custom.ansi(Role::AgentText);
        theme::set_active(custom);
        let before_transcript = tty.painted().len();
        newt_core::tty::Notice::new(
            newt_core::tty::Level::Thinking,
            "",
            "THOUGHT_FIRST\n\nTHOUGHT_SECOND\nThought for 5s",
        )
        .emit(
            newt_core::tty::LineCaps::Own,
            newt_core::tty::Sink::Stdout,
            true,
        );
        writeln!(
            io::stdout(),
            "{}",
            newt_core::agentic::render_markdown(
                "FINAL_RESPONSE",
                newt_core::agentic::RenderOpts {
                    color: true,
                    cols: 80
                },
            )
        )
        .unwrap();
        io::stdout().flush().unwrap();
        let deadline = Instant::now() + Duration::from_secs(2);
        loop {
            cockpit.drain_pty().expect("drain styled transcript");
            if tty.wait_for_painted_after(
                before_transcript,
                "FINAL_RESPONSE\x1b[0m",
                Duration::from_millis(5),
            ) {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "styled transcript was not painted"
            );
        }
        let painted = tty.painted();
        let transcript = &painted[before_transcript..];
        assert!(transcript.contains(&format!("{first_style}THOUGHT_FIRST\x1b[0m")));
        for thought in ["THOUGHT_SECOND", "Thought for 5s"] {
            assert!(
                transcript.contains(&format!("\x1b[3;38;2;12;34;56m{thought}\x1b[0m")),
                "thought style lost for {thought}: {transcript:?}"
            );
        }
        assert!(transcript.contains(&format!("{answer_style}FINAL_RESPONSE\x1b[0m")));

        // ---- Ctrl-C: every press trips the cancel and is counted ----
        let cancel = Arc::new(AtomicBool::new(false));
        cockpit
            .handle_request(SurfaceRequest::TurnStarted {
                cancel: Arc::clone(&cancel),
            })
            .expect("a turn starts");

        tty.type_bytes(CTRL_C);
        cockpit.poll_keys().expect("first Ctrl-C");
        assert!(
            cancel.load(Ordering::SeqCst),
            "first press trips the cancel the session races against"
        );
        // Operator-observable: this is the count the spinner reads to swap
        // its stage label, so the press is acknowledged on screen.
        assert_eq!(
            newt_core::tty::interrupt_presses(),
            1,
            "first press raises the acknowledgment the operator sees"
        );

        tty.type_bytes(CTRL_C);
        cockpit.poll_keys().expect("second Ctrl-C");
        // #2010: the second press is HEARD — it bumps the count the
        // spinner renders, so it is visibly different from the first
        // instead of being absorbed into a flag read after the turn.
        assert_eq!(
            newt_core::tty::interrupt_presses(),
            2,
            "the second press is acknowledged at press time"
        );

        cockpit
            .handle_request(SurfaceRequest::TurnEnded)
            .expect("the turn ends");
        assert!(
            !newt_core::tty::interrupt_pending(),
            "ending the turn clears the acknowledgment, so the next turn \
                 does not open already showing it"
        );

        // ---- a modal is visible before an answer while the cockpit owns
        //      the terminal, then focus and the draft return to chat ----
        // Push the mounted block to the bottom, then queue a chrome change
        // that grows it by one row without drawing in between. `run`
        // drains requests in exactly that order; the interaction must
        // synchronize the pending layout before reserving its own rows.
        cockpit
            .screen
            .insert_rows(vec![b"transcript row".to_vec(); 24])
            .expect("push the cockpit block to the bottom");
        cockpit.draw().expect("seat the bottom-anchored block");
        let stale_top = cockpit.screen.top;
        {
            let (editor, screen) = (&mut cockpit.editor, &mut cockpit.screen);
            editor
                .on_event(Event::Paste("draft survives".into()), screen)
                .expect("prefill the mounted draft");
        }
        let draft = cockpit.editor.draft();
        cockpit
            .handle_request(SurfaceRequest::SetBackgroundJobs(vec![
                crate::chat::BackgroundJob::start("indexing repository"),
            ]))
            .expect("queue a chrome row before the modal");
        assert!(cockpit.dirty, "the queued chrome has not drawn yet");
        let expected_status_rows = cockpit.status_rows();
        let expected_editor_rows = cockpit.editor.wanted_rows(
            cockpit.screen.cols,
            cockpit.screen.rows,
            &cockpit.surface.chrome(),
        );
        let expected_block_h =
            (expected_editor_rows + expected_status_rows).clamp(1, cockpit.screen.rows.max(1));
        let expected_top = if stale_top + expected_block_h > cockpit.screen.rows {
            cockpit.screen.rows - expected_block_h
        } else {
            stale_top
        };
        assert!(
            expected_top < stale_top,
            "the regression needs the pending chrome row to move the block: \
                 stale={stale_top}, expected={expected_top}"
        );
        let definition = crate::permissions::free_text_form("Cockpit modal visible?");
        let interaction = newt_core::interaction_surface::SurfaceInteraction::blocking(definition);
        let requested_rows =
            crate::interaction_view::requested_rows(&interaction, cockpit.screen.cols);
        let expected_reservation =
            plan_modal_reservation(expected_top, cockpit.screen.rows, requested_rows);
        assert!(
            !expected_reservation.chat_visible,
            "the modal must occlude the composer: {expected_reservation:?}"
        );
        // Where THIS round's bytes begin. The assertions below ask what
        // the modal wrote, and the buffer also holds what everything
        // before it wrote — including, when the harness orders the two
        // serialized cockpit tests the other way round (which coverage
        // instrumentation does), the previous test's terminal RESTORE.
        // That restore legitimately re-enables line wrap, so a whole-buffer
        // scan for `EnableLineWrap` was reading another test's teardown as
        // this modal's behavior.
        let before_modal_round = tty.painted().len();
        let (reply, answer) = std::sync::mpsc::sync_channel(1);
        let (saw_box, while_modal) = std::thread::scope(|scope| {
            let typer = scope.spawn(|| {
                // The bottom-right corner is the final cell of the box.
                // Capture the entire initial frame BEFORE delivering input,
                // so the restored editor cannot satisfy this evidence.
                let saw_prompt = tty.wait_for_painted_after(
                    before_modal_round,
                    "visible?",
                    std::time::Duration::from_secs(2),
                );
                let prompt_end = tty.painted()[before_modal_round..]
                    .find("visible?")
                    .map_or(before_modal_round, |at| {
                        before_modal_round + at + "visible?".len()
                    });
                let saw_box = saw_prompt
                    && tty.wait_for_painted_after(
                        prompt_end,
                        "╯",
                        std::time::Duration::from_secs(2),
                    );
                let painted = tty.painted();
                tty.type_bytes(b"yes\r");
                (saw_box, painted)
            });
            cockpit
                .handle_request(SurfaceRequest::Interact {
                    interaction: Box::new(interaction),
                    reply,
                })
                .expect("present the interaction");
            typer.join().expect("prompt watcher")
        });
        assert!(
            saw_box,
            "the modal must reach the real terminal before input is sent; painted: {while_modal:?}"
        );
        let modal_delta = &while_modal[before_modal_round..];
        // The pure cleanup test pins this sequence; here the real terminal
        // must receive it before the dialog is painted.
        let erase = modal_cleanup_bytes(expected_reservation.start).expect("modal erase bytes");
        let erase = String::from_utf8(erase).expect("erase bytes are UTF-8");
        let erased_at = modal_delta.find(&erase).unwrap_or_else(|| {
            panic!("the modal must erase the covered composer before painting its box: {modal_delta:?}")
        });
        // screen_grid intentionally handles cursor positioning, not erase.
        // Start at the verified erase so a pending pre-modal chat repaint
        // cannot be mistaken for text still visible inside the window.
        let modal_grid = tests_pty::screen_grid(&modal_delta[erased_at..]);
        let modal_visible = modal_grid.join("\n");
        for text in ["╭", "╮", "╰", "╯", "Cockpit modal visible?"] {
            assert!(
                modal_visible.contains(text),
                "the blocking question must be enclosed and readable before input; missing {text:?}: {modal_visible}"
            );
        }
        assert!(
            !modal_visible.contains("draft survives"),
            "the normal composer must not be drawn into the blocking window: {modal_visible}"
        );
        assert_eq!(
            answer.recv().expect("interaction answer"),
            newt_core::HumanQuestionOutcome::Answer("yes".into())
        );
        assert_eq!(cockpit.editor.draft(), draft, "the chat draft survives");
        assert!(!cockpit.chat_inactive, "keyboard focus returns to chat");
        assert_eq!(
            cockpit.screen.top, expected_top,
            "the pending layout is applied before modal reservation"
        );
        let provisional = tty.painted();
        let prompt_at = provisional
            .find("visible?")
            .expect("modal body reached the terminal");
        let mut show = Vec::new();
        queue!(show, crossterm::cursor::Show).expect("show-cursor bytes");
        let show = String::from_utf8(show).expect("show bytes are UTF-8");
        // #1959 (post-rebase flake): the modal's OPENING is already
        // synchronized (the observer above waits for the completed box
        // before typing), but the repaint that restores the
        // chat cursor when it CLOSES is the last thing this round
        // writes, with no synchronization point before the snapshot
        // below — unlike input, `painted()` has no way to know the
        // responder thread (which drains the pty master on its own
        // thread) has caught up with a write that already returned.
        // Proved directly, not assumed: 15 concurrent runs of this exact
        // test, 6 failed here, each truncated at a DIFFERENT byte
        // offset — the signature of a drain race, not a fixed defect.
        // Waiting for the exact evidence the assertion below checks for
        // changes WHEN it is safe to read, not WHAT is asserted.
        assert!(
            tty.wait_for_painted_after(prompt_at, &show, std::time::Duration::from_secs(2)),
            "the chat cursor was not restored after the modal closed (waited 2s): {:?}",
            tty.painted()
        );
        let painted = tty.painted();
        let mut expected_move = Vec::new();
        queue!(expected_move, MoveTo(0, expected_reservation.start))
            .expect("cursor-placement bytes");
        let expected_move = String::from_utf8(expected_move).expect("cursor bytes are UTF-8");
        assert!(
                painted[..prompt_at].contains(&expected_move),
                "the modal was not placed over the composer; expected {expected_move:?}, painted: {painted:?}"
            );
        let mut hide = Vec::new();
        queue!(hide, crossterm::cursor::Hide).expect("hide-cursor bytes");
        let hide = String::from_utf8(hide).expect("hide bytes are UTF-8");
        let before_modal = &painted[..prompt_at];
        assert!(
            before_modal.rfind(&hide) > before_modal.rfind(&show),
            "the mounted chat cursor must recede before the modal takes focus: {painted:?}"
        );
        assert!(
            painted[prompt_at..].contains(&show),
            "the chat cursor was not restored after the modal closed: {painted:?}"
        );
        let mut enable_wrap = Vec::new();
        queue!(enable_wrap, EnableLineWrap).expect("enable-wrap bytes");
        let enable_wrap = String::from_utf8(enable_wrap).expect("wrap bytes are UTF-8");
        // Held off from the modal's erase until it is answered: `modal_delta`
        // is the snapshot taken just before the answer is typed.
        assert!(
            !modal_delta[erased_at..].contains(&enable_wrap),
            "a modal must keep terminal autowrap disabled so a long answer cannot spill into chat: {:?}",
            &modal_delta[erased_at..]
        );
        // At rest the terminal must have wrap on again, or its next resize
        // truncates the transcript instead of reflowing it.
        assert!(
            painted[prompt_at..].contains(&enable_wrap),
            "autowrap must be restored once the modal closes: {:?}",
            &painted[prompt_at..]
        );

        // A slash command entered in a modal backs out to chat and leaves
        // corrective guidance in durable transcript space. The old path
        // wrote this notice through PromptWindow on the first chat row;
        // the immediate cockpit repaint then erased it.
        let slash_definition = crate::permissions::free_text_form("Slash commands stay in chat?");
        let slash_top = cockpit.screen.top;
        let slash_block_h = cockpit.screen.block_h;
        let slash_rows = cockpit.screen.rows;
        let slash_cols = cockpit.screen.cols;
        let before_slash = tty.painted().len();
        let slash_typer = tty.type_when_painted("chat?", b"/help\r");
        let (slash_reply, slash_answer) = std::sync::mpsc::sync_channel(1);
        cockpit
            .handle_request(SurfaceRequest::Interact {
                interaction: Box::new(
                    newt_core::interaction_surface::SurfaceInteraction::blocking(slash_definition),
                ),
                reply: slash_reply,
            })
            .expect("present the slash-command interaction");
        assert!(
            slash_typer.join().expect("slash prompt watcher"),
            "the slash-command prompt must be visible before input"
        );
        assert_eq!(
            slash_answer.recv().expect("slash-command outcome"),
            newt_core::HumanQuestionOutcome::Cancelled,
            "a slash command is chat intent, not a modal answer"
        );

        let notice_row = crate::permissions::SLASH_COMMAND_PROMPT_NOTICE
            .as_bytes()
            .to_vec();
        let notice_rows = wrap_row(&notice_row, usize::from(slash_cols));
        let (committed_notice, _) =
            render_insert(slash_top, slash_block_h, slash_rows, &notice_rows)
                .expect("durable notice insertion plan");
        let committed_notice = String::from_utf8(committed_notice).expect("notice bytes are UTF-8");
        // #1959 (post-rebase flake, same shape as the cursor-restore wait
        // above): the notice-commit repaint is the last thing this round
        // writes, with no synchronization point before a snapshot taken
        // right after `handle_request` returns. Wait for the exact
        // evidence the assertion below checks for.
        assert!(
            tty.wait_for_painted_after(
                before_slash,
                &committed_notice,
                std::time::Duration::from_secs(2)
            ),
            "slash guidance was not committed above the cockpit viewport (waited 2s): {:?}",
            &tty.painted()[before_slash..]
        );
        let painted_after_slash = tty.painted();
        let slash_delta = &painted_after_slash[before_slash..];
        assert!(
            slash_delta.contains(&committed_notice),
            "slash guidance was not committed above the cockpit viewport: {slash_delta:?}"
        );
        assert_eq!(
            cockpit.editor.draft(),
            draft,
            "backing out of a modal keeps the mounted chat draft"
        );

        // The modal's raw reader still composes with the cockpit's own
        // raw-mode guard. This checks termios directly, independently of
        // the visibility assertion above.
        // The integration #1770 could not prove alone: that fix made the
        // modal take raw mode from the real termios instead of crossterm's
        // global, and the cockpit is exactly the second raw-mode owner
        // that broke it. Here the cockpit genuinely holds fd 0/1.
        let window = newt_core::tty::Terminal::suspend_for_prompt(
            newt_core::tty::TerminalTaker::RichSurfaceModal,
        );
        {
            let _reader = newt_core::tty::modal_prompt_controls(&window)
                .expect("the modal takes the terminal from under the cockpit");
            assert!(
                !is_canonical(0),
                "the modal's read must be non-canonical, or a keypress \
                     waits for Enter the operator does not know to press"
            );
            assert!(
                !echoes(0),
                "the kernel must not echo the answer over the prompt"
            );
        }
        drop(window);
        // The modal restored what it found: the cockpit still has a raw
        // terminal to go on painting into.
        assert!(
            !is_canonical(0),
            "the cockpit's raw mode survives the modal"
        );

        // ---- and a PANEL is lent rows on the REAL terminal ----
        //
        // The `/backends` defect, at the level only a real terminal can
        // show it: a panel that draws to fd 1 under a mounted cockpit
        // paints into the pty CAPTURE, not onto the screen, and comes back
        // as flattened transcript rows. Nothing mocked can observe that,
        // because the mock IS the capture. Here the panel draws through the
        // window the presenter lends it, and the bytes must appear on the
        // terminal the operator is looking at.
        //
        // The painter runs on its own thread because `handle_request` PARKS
        // until the window drops — that parking is the mechanism keeping
        // two writers off one terminal, so the test has to exercise it
        // rather than sidestep it.
        let (panel_reply, panel_window) =
            std::sync::mpsc::sync_channel::<Option<crate::session_worker::PanelWindow>>(1);
        let painter = std::thread::spawn(move || {
            let window = panel_window
                .recv()
                .expect("the presenter answers the panel request")
                .expect("a mounted cockpit has rows to lend");
            let mut term = window.terminal().expect("a terminal over the lent rows");
            term.draw(|f| {
                f.render_widget(
                    ratatui::widgets::Paragraph::new("PANEL BODY ON THE REAL TERMINAL"),
                    f.area(),
                );
            })
            .expect("the panel paints");
            drop(term);
            // Dropping the window is the release; the presenter is parked
            // on it.
            drop(window);
        });
        let panel_plan = plan_modal_reservation(cockpit.screen.top, cockpit.screen.rows, 6);
        assert!(
            !panel_plan.chat_visible,
            "a blocking panel must occlude the normal composer: {panel_plan:?}"
        );
        let before_panel = tty.painted().len();
        cockpit
            .handle_request(SurfaceRequest::Panel {
                mode: PanelMode::Inline(6),
                reply: panel_reply,
            })
            .expect("the presenter lends the panel its rows");
        painter.join().expect("panel painter");
        // #1959 (same shape as the cursor-restore and notice-commit waits
        // above): `join` proves the painter's `write` returned, not that
        // the responder thread — the pty master's sole reader — has drained
        // those bytes into `painted`. This is what failed on #2069, a PR
        // that touched a command parser and the slash registry and has no
        // path to cockpit terminal ownership: the delta held the
        // reservation scroll and the chat repaint that precedes the panel,
        // and simply stopped before the panel body.
        //
        // `TERMINAL` is the LAST word the panel paints — ratatui emits
        // cells in row-major order — so once it has landed, every earlier
        // byte of this round is present by stream ordering: the other three
        // words and the presenter's reservation `MoveTo` alike. Waiting on
        // the last evidence changes WHEN the snapshot is safe to read, not
        // WHAT any assertion below demands of it.
        assert!(
            tty.wait_for_painted_after(before_panel, "TERMINAL", std::time::Duration::from_secs(2)),
            "the panel's bytes never reached the real terminal (waited 2s): {:?}",
            &tty.painted()[before_panel..]
        );
        let panel_delta = tty.painted()[before_panel..].to_string();
        // Ratatui emits a cursor move per painted run, so the body arrives
        // as words rather than one string. What matters is that they
        // arrive AT ALL (they would be swallowed by the capture) and that
        // they land in the rows the presenter reserved.
        let mut panel_move = Vec::new();
        queue!(panel_move, MoveTo(0, panel_plan.start)).expect("panel cursor bytes");
        let panel_move = String::from_utf8(panel_move).expect("panel cursor bytes are UTF-8");
        assert!(
            panel_delta.contains(&panel_move),
            "the panel must be placed in its reserved rows over chat; \
                 expected {panel_move:?}, painted: {panel_delta:?}"
        );
        for word in ["PANEL", "BODY", "REAL", "TERMINAL"] {
            assert!(
                panel_delta.contains(word),
                "the panel's bytes must reach the real terminal, not the \
                     cockpit's fd 1 capture; missing {word:?}: {panel_delta:?}"
            );
        }
        assert!(
            !cockpit.chat_inactive,
            "keyboard focus returns to chat when the panel window drops"
        );
        assert_eq!(
            cockpit.editor.draft(),
            draft,
            "the chat draft survives a panel"
        );
        assert!(
            !is_canonical(0),
            "the cockpit's raw mode survives the panel"
        );

        // ---- the rows come back on the paths nobody plans for ----
        //
        // Release-on-drop is the whole synchronization mechanism, so the
        // paths worth proving are the ones with no drawing in them at all:
        // a panel that fails before its first frame, and a session that
        // vanishes between asking for rows and taking them. Either would
        // strand the presenter parked on rows nobody will release, which
        // presents as a frozen cockpit rather than as an error.
        for mode in [PanelMode::Inline(6), PanelMode::AlternateScreen] {
            let (early_reply, early_window) =
                std::sync::mpsc::sync_channel::<Option<crate::session_worker::PanelWindow>>(1);
            let early = std::thread::spawn(move || {
                // Took the rows, drew nothing, gave them straight back — the
                // shape of a panel whose seed was empty or whose terminal
                // failed to build.
                drop(early_window.recv().expect("the presenter answers"));
            });
            cockpit
                .handle_request(SurfaceRequest::Panel {
                    mode,
                    reply: early_reply,
                })
                .expect("an undrawn panel still returns");
            early.join().expect("early-drop panel");
            assert!(
                !cockpit.chat_inactive,
                "focus returns when a panel drops its window without drawing"
            );

            // And the session that disappears mid-ask: the reply send fails,
            // which must undo the reservation rather than park on it.
            let (orphan_reply, orphan_window) =
                std::sync::mpsc::sync_channel::<Option<crate::session_worker::PanelWindow>>(1);
            drop(orphan_window);
            cockpit
                .handle_request(SurfaceRequest::Panel {
                    mode,
                    reply: orphan_reply,
                })
                .expect("a vanished session is not a presenter error");
            assert!(
                !cockpit.chat_inactive,
                "a panel request nobody received must not leave chat dimmed"
            );
        }
        assert_eq!(
            cockpit.editor.draft(),
            draft,
            "the chat draft survives both panel failure paths"
        );
        // **The block is still LIVE after both failure paths** — it takes
        // input and paints it, rather than being stuck in the geometry the
        // failed panel reserved.
        //
        // Proven by typing something new, not by `dirty = true` + a length
        // comparison. Ratatui diffs its buffer: a redraw of unchanged
        // content emits a handful of trailing bytes and nothing else, so
        // the length check was asserting almost nothing — and what little
        // it did assert raced the responder thread's drain, which is how
        // it failed under coverage instrumentation. New text can only
        // reach the terminal through a live block, and
        // `wait_for_painted_after` reads at a point where the drain has
        // caught up.
        let before_repaint = tty.painted().len();
        {
            let (editor, screen) = (&mut cockpit.editor, &mut cockpit.screen);
            editor
                .on_event(Event::Paste(" and still alive".into()), screen)
                .expect("the mounted editor still takes input");
        }
        cockpit
            .draw()
            .expect("the cockpit still paints after a failed panel");
        assert!(
            tty.wait_for_painted_after(before_repaint, "alive", std::time::Duration::from_secs(2)),
            "the cockpit block is still live after the panel failure paths \
                 (waited 2s): {:?}",
            &tty.painted()[before_repaint..]
        );
    }

    // ---- and the terminal comes back, exactly ----
    assert!(is_canonical(0), "canonical mode restored on teardown");
    assert!(echoes(0), "echo restored on teardown");
    assert!(
        modes_equal(&before, &termios_of(0)),
        "every termios mode field restored exactly, not approximately — \
             this is the assertion an emitted-escape-bytes check cannot make; \
             differs: {}",
        mode_diff(&before, &termios_of(0))
    );
}

/// Acceptance (#1744): the same restoration through an ABNORMAL exit.
///
/// Proven against the modes guard itself rather than a second cockpit: the
/// guard is the mechanism (`Presenter::open` binds it before the fallible
/// capture install precisely so a `?` or a panic cannot strand the
/// terminal), and one cockpit per process is a harness limit, not a reason
/// to leave the unwind path unproven.
///
/// Real-PTY tier: `#[ignore]`d in the unit run (it opens a real PTY or a real
/// subprocess and races libtest under load). Grounds the presenter's mocked row-model and mode-guard tests, which cannot observe a real terminal's modes, foreground group or size.
#[serial_test::serial(tty_arbiter)]
#[test]
#[ignore = "real-PTY acceptance tier; weekly, release, and scoped PTY CI only"]
fn a_panic_restores_the_real_termios_through_the_modes_guard() {
    let _tty = TestTty::install();
    // Clear crossterm's saved-mode static FIRST. It is process-global, so
    // an earlier test in this binary may have populated it.
    //
    // #1925 is what makes this belt and braces rather than load-bearing:
    // the presenter takes raw through `RawModeGuard`, which captures the
    // real termios and never consults that static. The hazard this line
    // guards against — restoring an OLDER baseline than the one this test
    // set — is the very defect the swap removes. Kept because other tests
    // in this binary still populate the static.
    let _ = crossterm::terminal::disable_raw_mode();
    set_canonical_echo(0);
    let before = termios_of(0);

    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let result = std::panic::catch_unwind(|| {
        // Model the PRESENTER'S OWN FIELD PAIR, in its declaration order
        // (#1925). A struct, not two locals, and deliberately: struct
        // fields drop in declaration order while locals drop in REVERSE,
        // so two `let`s here would exercise the opposite order to the one
        // the presenter has and prove nothing about it.
        struct Held {
            _restore: crate::RestoreOnDrop<fn()>,
            _raw: newt_core::tty::raw_mode::RawModeGuard,
        }
        let _held = Held {
            _restore: crate::RestoreOnDrop {
                restore: restore_terminal_modes,
            },
            _raw: newt_core::tty::raw_mode::RawModeGuard::enter().expect("raw"),
        };
        assert!(!is_canonical(0), "precondition: raw mode taken");
        panic!("turn exploded while the terminal was raw");
    });
    std::panic::set_hook(hook);

    assert!(
        result.is_err(),
        "the panic must propagate, not be swallowed"
    );
    assert!(
        is_canonical(0),
        "canonical mode restored through the unwind"
    );
    assert!(echoes(0), "echo restored through the unwind");
    assert!(
        modes_equal(&before, &termios_of(0)),
        "every termios mode field restored exactly after a panic; differs: {}",
        mode_diff(&before, &termios_of(0))
    );
}