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
//! #1670 (meta-scroller Layer 2): the RichTUI transcript pager.
//!
//! A full-screen, on-demand view of the whole retained conversation where the
//! **conversation spine** — the operator's `›` prompts and the model's `▸`
//! replies — is the primary structure: jump message-to-message, scroll freely,
//! and fold/unfold the grey per-turn tool blocks between the green messages.
//! The top grows over the entire stored transcript, not a fixed viewport.
//!
//! Charter: alt-screen surfaces are permitted on the feature-gated RICH tier
//! only (`docs/decisions/plain_scroller_tui.md`, 2026-08-11 amendment). The
//! lean surface answers `/transcript` with a plain printed spine instead
//! (`conversation_show_message` — no scroll regions, ever).
//!
//! Grey depth note: the store deliberately retains tool **summaries** only
//! (`ToolEvent` — name/ok/duration, never raw output; the privacy stance in
//! `conversation.rs`). So a fold's body is the turn's tool-call summary lines.
//! Retaining bounded tool-output bodies for the pager is the tracked follow-up
//! on #1670 — it needs its own session-retention design, not a store change.
//!
//! The row model is PURE (no TTY, no ratatui types) so navigation, folding,
//! and jump targets are unit-tested; only `run_pager` touches the terminal.

use newt_core::ConversationTurn;

/// Read-only navigation shared by retained output and pending-request inspection.
/// No key can produce an interaction answer or model input.
#[cfg(feature = "rich-tui")]
pub(crate) struct OutputView {
    lines: Vec<String>,
    scroll: usize,
    horizontal: u16,
    query: Option<String>,
    search: String,
    search_match: Option<usize>,
}

#[cfg(feature = "rich-tui")]
impl OutputView {
    pub(crate) fn new(lines: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        Self {
            lines: lines
                .into_iter()
                .map(|line| {
                    line.as_ref()
                        .chars()
                        .flat_map(|c| {
                            if c.is_control() {
                                c.escape_default().collect::<Vec<_>>()
                            } else {
                                vec![c]
                            }
                        })
                        .collect()
                })
                .collect(),
            scroll: 0,
            horizontal: 0,
            query: None,
            search: String::new(),
            search_match: None,
        }
    }

    pub(crate) fn draw(&mut self, frame: &mut ratatui::Frame, area: ratatui::layout::Rect) {
        let rows = usize::from(area.height.saturating_sub(1));
        self.scroll = self
            .scroll
            .min(self.lines.len().saturating_sub(rows.max(1)));
        let visible = self
            .lines
            .iter()
            .skip(self.scroll)
            .take(rows)
            .map(|line| ratatui::text::Line::raw(line.clone()))
            .collect::<Vec<_>>();
        frame.render_widget(
            ratatui::widgets::Paragraph::new(visible).scroll((0, self.horizontal)),
            ratatui::layout::Rect::new(area.x, area.y, area.width, rows as u16),
        );
        let hint = self.query.as_ref().map_or_else(
            || "Esc back · arrows scroll · / search · n next".to_string(),
            |query| format!("/{query} · Enter search · Esc cancel search"),
        );
        if area.height > 0 {
            frame.render_widget(
                ratatui::widgets::Paragraph::new(hint),
                ratatui::layout::Rect::new(area.x, area.bottom() - 1, area.width, 1),
            );
        }
    }

    /// Returns true only to close the inspector, never to approve its contents.
    pub(crate) fn key(&mut self, key: crossterm::event::KeyEvent, rows: usize) -> bool {
        use crossterm::event::{KeyCode, KeyEventKind, KeyModifiers};
        if key.kind != KeyEventKind::Press {
            return false;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return true;
        }
        if let Some(query) = &mut self.query {
            match key.code {
                KeyCode::Esc => self.query = None,
                KeyCode::Enter => {
                    self.search = self.query.take().unwrap_or_default();
                    self.search_match = None;
                    self.find(false);
                }
                KeyCode::Backspace => {
                    query.pop();
                }
                KeyCode::Char(c)
                    if !key
                        .modifiers
                        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
                {
                    query.push(c);
                }
                _ => {}
            }
            return false;
        }
        let rows = rows.max(1);
        let max = self.lines.len().saturating_sub(rows);
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::F(4) => return true,
            KeyCode::Up | KeyCode::Char('k') => self.scroll = self.scroll.saturating_sub(1),
            KeyCode::Down | KeyCode::Char('j') => self.scroll = (self.scroll + 1).min(max),
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.scroll = self.scroll.saturating_sub((rows / 2).max(1));
            }
            KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.scroll = self.scroll.saturating_add((rows / 2).max(1)).min(max);
            }
            KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(rows),
            KeyCode::PageDown => self.scroll = self.scroll.saturating_add(rows).min(max),
            KeyCode::Home | KeyCode::Char('g') => self.scroll = 0,
            KeyCode::End | KeyCode::Char('G') => self.scroll = max,
            KeyCode::Left => self.horizontal = self.horizontal.saturating_sub(8),
            KeyCode::Right => self.horizontal = self.horizontal.saturating_add(8),
            KeyCode::Char('/') => self.query = Some(String::new()),
            KeyCode::Char('n') => self.find(true),
            _ => {}
        }
        false
    }

    fn find(&mut self, next: bool) {
        if self.search.is_empty() || self.lines.is_empty() {
            return;
        }
        let start = if next {
            self.search_match.unwrap_or(self.scroll) + 1
        } else {
            self.scroll
        };
        if let Some(index) = (0..self.lines.len())
            .map(|i| (start + i) % self.lines.len())
            .find(|&i| self.lines[i].contains(&self.search))
        {
            self.search_match = Some(index);
            self.scroll = index;
            if let Some(byte) = self.lines[index].find(&self.search) {
                self.horizontal =
                    u16::try_from(newt_core::tty::str_width(&self.lines[index][..byte]))
                        .unwrap_or(u16::MAX);
            }
        }
    }
}

/// What a flattened pager row is, for styling and for jump targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RowKind {
    /// First line of a turn's operator prompt — the `›` anchor jumps land on.
    PromptHead,
    /// Continuation line of a prompt.
    Prompt,
    /// First line of the model reply (`▸`).
    ReplyHead,
    /// Continuation line of a reply.
    Reply,
    /// The grey fold header: `⚙ N tool calls …` — Enter/Space toggles.
    ToolFold,
    /// One tool-call summary line inside an unfolded block.
    Tool,
    /// Blank separator between turns.
    Blank,
}

/// One flattened, styled-by-kind pager row. Long lines are CLIPPED by the
/// renderer, not wrapped: the pager is a navigation surface, and exact
/// row-per-line math is what keeps scrolling and jump targets testable.
///
/// Where the full text lives, stated accurately (#1677 review): for turns THIS
/// terminal printed, it is in normal scrollback. For a **resumed** conversation
/// it is not — those turns were never printed here — so the fallback for full
/// text is `/conversation show <id>`, or `/transcript` on the LEAN surface,
/// which prints the spine unclipped. The pager offers no wrap toggle and no
/// horizontal scroll; a wrap mode is follow-up work on #1672. Saying
/// "scrollback always has it" would be false for exactly the case this command
/// exists to serve.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PagerRow {
    pub kind: RowKind,
    /// Which turn this row belongs to (separator rows belong to the turn
    /// ABOVE them).
    pub turn: usize,
    pub text: String,
}

/// The pure pager state: the record's turns flattened against per-turn fold
/// flags, plus one scroll position. The "current" turn is DERIVED from the
/// scroll (the last prompt head at or above the top row), so there is no
/// second cursor to drift.
pub(crate) struct PagerState {
    turns: Vec<TurnRows>,
    folded: Vec<bool>,
    /// Top visible flattened-row index.
    pub scroll: usize,
    pub title: String,
}

/// One turn's pre-split lines (fold state applied at flatten time).
struct TurnRows {
    prompt: Vec<String>,
    reply: Vec<String>,
    tools: Vec<String>,
}

/// `⚙ name · ✓/✗ · 12ms` — the same vocabulary as the inline tool header, so
/// the fold body reads as the familiar grey.
fn tool_line(event: &newt_core::ToolEvent) -> String {
    let ok = if event.ok { "✓" } else { "✗" };
    match event.duration_ms {
        Some(ms) => format!("⚙ {} · {ok} · {ms}ms", event.tool),
        None => format!("⚙ {} · {ok}", event.tool),
    }
}

fn split_lines(text: &str) -> Vec<String> {
    let lines: Vec<String> = text.lines().map(str::to_string).collect();
    if lines.is_empty() {
        vec![String::new()]
    } else {
        lines
    }
}

impl PagerState {
    /// Build from a stored conversation's title + turns (the only record
    /// fields the pager reads — taking them directly keeps this model
    /// decoupled from `ConversationRecord`'s width). Tool blocks start
    /// FOLDED — the spine is the point; the grey is one keypress away.
    pub(crate) fn new(title: &str, turns: &[ConversationTurn]) -> Self {
        let turns: Vec<TurnRows> = turns.iter().map(TurnRows::from_turn).collect();
        let folded = vec![true; turns.len()];
        Self {
            turns,
            folded,
            scroll: 0,
            title: title.to_string(),
        }
    }

    /// Flatten turns + fold flags into styled rows. O(total lines) — fine for
    /// a keypress-driven redraw of a stored conversation.
    pub(crate) fn rows(&self) -> Vec<PagerRow> {
        let mut out = Vec::new();
        for (i, turn) in self.turns.iter().enumerate() {
            if i > 0 {
                out.push(PagerRow {
                    kind: RowKind::Blank,
                    turn: i - 1,
                    text: String::new(),
                });
            }
            for (n, line) in turn.prompt.iter().enumerate() {
                let (kind, sigil) = if n == 0 {
                    (RowKind::PromptHead, "› ")
                } else {
                    (RowKind::Prompt, "  ")
                };
                out.push(PagerRow {
                    kind,
                    turn: i,
                    text: format!("{sigil}{line}"),
                });
            }
            if !turn.tools.is_empty() {
                let state = if self.folded[i] { "▸" } else { "▾" };
                out.push(PagerRow {
                    kind: RowKind::ToolFold,
                    turn: i,
                    // Honest about depth (#1677): folded invites the
                    // keypress; UNFOLDED says what the reader is actually
                    // getting. The store keeps tool SUMMARIES only —
                    // `ToolEvent` has no output field — so a header that
                    // said just "N tool calls" would imply bodies that were
                    // never retained. Bounded output retention is the
                    // tracked #1672 follow-up.
                    text: format!(
                        "{state} ⚙ {} tool call{}{}",
                        turn.tools.len(),
                        if turn.tools.len() == 1 { "" } else { "s" },
                        if self.folded[i] {
                            " — Enter unfolds"
                        } else {
                            " — summaries only; tool output is not retained"
                        }
                    ),
                });
                if !self.folded[i] {
                    for line in &turn.tools {
                        out.push(PagerRow {
                            kind: RowKind::Tool,
                            turn: i,
                            text: format!("  {line}"),
                        });
                    }
                }
            }
            for (n, line) in turn.reply.iter().enumerate() {
                let (kind, sigil) = if n == 0 {
                    (RowKind::ReplyHead, "▸ ")
                } else {
                    (RowKind::Reply, "  ")
                };
                out.push(PagerRow {
                    kind,
                    turn: i,
                    text: format!("{sigil}{line}"),
                });
            }
        }
        out
    }

    fn max_scroll(&self, page_rows: usize) -> usize {
        self.rows().len().saturating_sub(page_rows.max(1))
    }

    pub(crate) fn scroll_by(&mut self, delta: isize, page_rows: usize) {
        let max = self.max_scroll(page_rows);
        self.scroll = self.scroll.saturating_add_signed(delta).min(max);
    }

    /// Re-clamp the scroll position to the end rail for a `page_rows`-tall
    /// viewport (#1677). The renderer calls this every frame, so a RESIZE —
    /// the one viewport change the keyboard cannot produce — can never leave
    /// the view stranded past the rail that `end()`/`scroll_by()` enforce.
    pub(crate) fn clamp_scroll(&mut self, page_rows: usize) {
        self.scroll = self.scroll.min(self.max_scroll(page_rows));
    }

    pub(crate) fn home(&mut self) {
        self.scroll = 0;
    }

    pub(crate) fn end(&mut self, page_rows: usize) {
        self.scroll = self.max_scroll(page_rows);
    }

    /// The turn whose prompt head is nearest AT or ABOVE the top visible row —
    /// what jumps and folds operate on. Turn 0 before any head is visible.
    pub(crate) fn current_turn(&self) -> usize {
        let rows = self.rows();
        let mut current = 0;
        for row in rows.iter().take(self.scroll + 1) {
            if row.kind == RowKind::PromptHead {
                current = row.turn;
            }
        }
        current
    }

    /// Jump so the NEXT turn's prompt head is the top row (no-op on the last).
    pub(crate) fn next_message(&mut self, page_rows: usize) {
        let target = self.current_turn() + 1;
        if let Some(row) = self.prompt_head_row(target) {
            self.scroll = row.min(self.max_scroll(page_rows));
        }
    }

    /// Jump to THIS turn's prompt head if we've scrolled past it, else the
    /// previous turn's — the pager twin of "go back to what I asked".
    pub(crate) fn prev_message(&mut self) {
        let current = self.current_turn();
        let head = self.prompt_head_row(current).unwrap_or(0);
        let target = if self.scroll > head {
            head
        } else {
            self.prompt_head_row(current.saturating_sub(1)).unwrap_or(0)
        };
        self.scroll = target;
    }

    fn prompt_head_row(&self, turn: usize) -> Option<usize> {
        self.rows()
            .iter()
            .position(|row| row.kind == RowKind::PromptHead && row.turn == turn)
    }

    /// Toggle the current turn's grey block. Folding above the viewport moves
    /// rows; keep the current prompt head pinned so the spine doesn't jump.
    pub(crate) fn toggle_fold(&mut self, page_rows: usize) {
        let turn = self.current_turn();
        if self.turns.get(turn).map(|t| t.tools.is_empty()) != Some(false) {
            return;
        }
        let head_before = self.prompt_head_row(turn).unwrap_or(0);
        let offset = self.scroll.saturating_sub(head_before);
        self.folded[turn] = !self.folded[turn];
        let head_after = self.prompt_head_row(turn).unwrap_or(0);
        self.scroll = (head_after + offset).min(self.max_scroll(page_rows));
    }

    /// `turn N/M` for the header bar.
    pub(crate) fn position(&self) -> String {
        format!(
            "turn {}/{}",
            self.current_turn() + 1,
            self.turns.len().max(1)
        )
    }
}

impl TurnRows {
    fn from_turn(turn: &ConversationTurn) -> Self {
        Self {
            prompt: split_lines(&turn.user),
            reply: split_lines(&turn.assistant),
            tools: turn.events.iter().map(tool_line).collect(),
        }
    }
}

// ---------------------------------------------------------------------------
// The modal terminal loop (the only part that touches the TTY).
//
// COMPILE-GATED to `rich-tui` (#1677 review). Everything above this line is the
// pure transcript VIEW MODEL — no terminal, no ratatui — and stays compiled and
// unit-tested in every configuration, including the lean/no-rich build. Only
// this half, which takes the terminal over (raw mode + alternate screen), is
// severed from lean. `ratatui`/`crossterm` are non-optional deps of this crate,
// so without this gate a lean binary would carry an alt-screen surface it can
// never legitimately enter — `plain_scroller_tui.md`: the lean path has no
// scroll regions, ever.
// ---------------------------------------------------------------------------
#[cfg(all(feature = "rich-tui", feature = "live-spill"))]
pub(crate) use terminal::run_output_pager;
#[cfg(feature = "rich-tui")]
pub(crate) use terminal::run_pager;
#[cfg(all(unix, feature = "rich-tui", feature = "live-spill"))]
pub(crate) use terminal::run_spill_picker;
/// Re-exported for the real-PTY acceptance test only (#1677): it drops the
/// guard mid-unwind in a child process to prove the restoration claim against
/// an actual terminal. Nothing in the shipping path constructs it directly —
/// `run_pager` owns its lifetime.
// unix as well as test: the sole consumer is `transcript_pager_pty_test`,
// which is itself `cfg(all(test, unix, feature = "rich-tui"))` because a pty
// pair is unix-only. Without the `unix` here the re-export is an unused
// import on Windows, and this repo runs `-D warnings`.
#[cfg(all(test, unix, feature = "rich-tui"))]
pub(crate) use terminal::AltScreenGuard;

#[cfg(feature = "rich-tui")]
mod terminal {
    use super::{PagerState, RowKind};
    use crate::inline_viewport::PanelOut;
    use crate::session_worker::{PanelMode, PanelWindow};
    use crate::InputSurface;

    use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
    use crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen};
    use newt_core::tty::raw_mode::RawModeGuard;
    use ratatui::backend::CrosstermBackend;
    use ratatui::style::{Color, Modifier, Style};
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;
    use std::io;

    #[cfg(feature = "live-spill")]
    use crate::completed_spill::CompletedSpill;

    /// Restore the primary screen + cooked mode on EVERY exit path — error or
    /// panic included. Leaking the alternate screen would strand the whole
    /// session invisible, a worse failure than any pager bug.
    ///
    /// `pub(crate)` solely for `transcript_pager_pty_test` (#1677): the real-PTY
    /// error-path test drops this guard mid-unwind in a child process to prove
    /// the restoration claim above against an actual terminal.
    ///
    /// **Composed onto [`RawModeGuard`] (#1905).** The alternate screen is
    /// this type's own; raw mode is the shared, nesting-aware owner held as a
    /// field. Rust drops fields AFTER the `Drop::drop` body, so the screen is
    /// left before raw mode is released — the order this guard already had.
    pub(crate) struct AltScreenGuard {
        out: PanelOut,
        /// **The whole screen, held (#1980).** Entering the alternate screen IS
        /// taking every row, and until now the arbiter did not know: an inline
        /// surface could mint the bottom rows while the pager owned the screen.
        ///
        /// DECLARATION ORDER IS THE CONTRACT, as for `_raw`. Fields drop AFTER
        /// `Drop::drop`, so the screen is left first and only then are the rows
        /// returned — a lease released while the pager was still drawing would
        /// advertise rows it had not finished with.
        _region: newt_core::tty::RegionLease,
        _raw: RawModeGuard,
        // Release the cockpit only after leaving the alternate screen and
        // restoring raw mode. Until then its input/output loop stays parked.
        _window: Option<PanelWindow>,
    }

    impl AltScreenGuard {
        fn for_surface(
            surface: &mut dyn InputSurface,
            terminal_owns_turn: bool,
        ) -> io::Result<Self> {
            let window = surface.open_panel(PanelMode::AlternateScreen);
            if terminal_owns_turn && window.is_none() {
                return Err(io::Error::other(
                    "the terminal owner could not lend the pager its screen",
                ));
            }
            Self::enter(window)
        }

        pub(crate) fn enter(window: Option<PanelWindow>) -> io::Result<Self> {
            let out = match window.as_ref() {
                Some(window) => PanelOut::Tty(window.output()?),
                None => PanelOut::Stdout(io::stdout()),
            };
            Self::enter_on(out, window)
        }

        fn enter_on(out: PanelOut, window: Option<PanelWindow>) -> io::Result<Self> {
            let raw = RawModeGuard::enter()?;
            // `SuspendHolder`, and it is the honest policy rather than the
            // convenient one: the alternate screen genuinely DOES suspend
            // whatever is beneath it — the primary screen is preserved and
            // restored by the terminal itself. It therefore never fails, so
            // this adds no new refusal path and changes no behaviour here.
            // What changes is elsewhere: a surface minting `Refuse` or `Shift`
            // now sees that the screen is taken.
            let region = newt_core::tty::Terminal::lease_region(
                newt_core::tty::Region::WholeScreen,
                newt_core::tty::OnCollision::SuspendHolder,
            )
            .ok_or_else(|| io::Error::other("the screen could not be leased"))?;
            // Bind the guard BEFORE the fallible `execute!`, so Drop owns the
            // restore from this point on — the same shape `SplashScreenGuard`
            // uses (lib.rs), whose doc records that the hand-rolled rollback
            // this replaces "was itself one of the three leaks" (#1411).
            //
            // The asymmetry mattered: `execute!` queues into `io::stdout()`'s
            // LineWriter and then flushes, and a FAILED flush RETAINS the
            // unwritten `?1049h` in that process-global buffer. The old
            // rollback could give raw mode back but could never emit
            // `?1049l` — so the next print (the caller's own "transcript
            // pager error: …" line) flushed the retained bytes and put the
            // session on the alternate screen with no owner alive to leave
            // it, for the rest of its life. Reviewer-reproduced against real
            // crossterm on a would-block fd (#1677 review).
            let mut guard = Self {
                out,
                _region: region,
                _raw: raw,
                _window: window,
            };
            crossterm::execute!(&mut guard.out, EnterAlternateScreen)?;
            Ok(guard)
        }
    }

    impl Drop for AltScreenGuard {
        fn drop(&mut self) {
            // Screen only; raw mode is released by `_raw` after this returns.
            let _ = crossterm::execute!(&mut self.out, LeaveAlternateScreen);
        }
    }

    fn row_style(kind: RowKind, theme: &newt_core::tty::theme::Theme) -> Style {
        match kind {
            // The spine uses default foreground except HumanText on human headers;
            // both human and model headers stay bold.
            RowKind::PromptHead => Style::default()
                .fg(crate::theme::to_ratatui(
                    theme.color(crate::theme::Role::HumanText),
                ))
                .add_modifier(Modifier::BOLD),
            RowKind::ReplyHead => Style::default().add_modifier(Modifier::BOLD),
            RowKind::Prompt | RowKind::Reply => Style::default(),
            // The grey is secondary — exactly the inline vocabulary.
            RowKind::ToolFold | RowKind::Tool => Style::default().fg(Color::DarkGray),
            RowKind::Blank => Style::default(),
        }
    }

    /// Run the pager until the operator quits (q / Esc). Blocking; owns the
    /// terminal for its lifetime and restores it on return.
    pub(crate) fn run_pager(
        state: &mut PagerState,
        surface: &mut dyn InputSurface,
        terminal_owns_turn: bool,
    ) -> io::Result<()> {
        let mut guard = AltScreenGuard::for_surface(surface, terminal_owns_turn)?;
        let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(&mut guard.out))?;
        terminal.clear()?;
        loop {
            let mut page_rows = 1usize;
            terminal.draw(|f| {
            let title = if state.title.is_empty() {
                "transcript"
            } else {
                state.title.as_str()
            };
            let body = crate::modal::frame(
                f,
                f.area(),
                &crate::modal::Chrome {
                    title,
                    subtitle: Some(format!("· {}", state.position())),
                    hint: Some(
                        "q quit · ↑↓ scroll · PgUp/PgDn page · n/p message · Enter fold · g/G top/bottom",
                    ),
                },
            );
            page_rows = body.height.max(1) as usize;

            // #1677: re-clamp to the SAME end rail the keyboard uses. The
            // renderer's own clamp used to be `len - 1`, one rail past the
            // model's `len - page_rows`, so GROWING the terminal could strand
            // the view in a position no keystroke can produce.
            state.clamp_scroll(page_rows);
            let rows = state.rows();
            let theme = crate::theme::active();
            let visible = rows
                .iter()
                .skip(state.scroll)
                .take(page_rows)
                .map(|row| Line::from(Span::styled(row.text.clone(), row_style(row.kind, &theme))))
                .collect::<Vec<_>>();
            f.render_widget(Paragraph::new(visible), body);
        })?;

            let Event::Key(key) = event::read()? else {
                continue;
            };
            if key.kind != KeyEventKind::Press {
                continue;
            }
            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
            let half = (page_rows / 2).max(1) as isize;
            match key.code {
                KeyCode::Char('q') | KeyCode::Esc => return Ok(()),
                KeyCode::Char('c') if ctrl => return Ok(()),
                KeyCode::Up | KeyCode::Char('k') => state.scroll_by(-1, page_rows),
                KeyCode::Down | KeyCode::Char('j') => state.scroll_by(1, page_rows),
                KeyCode::PageUp => state.scroll_by(-(page_rows as isize), page_rows),
                KeyCode::PageDown => state.scroll_by(page_rows as isize, page_rows),
                KeyCode::Char('u') if ctrl => state.scroll_by(-half, page_rows),
                KeyCode::Char('d') if ctrl => state.scroll_by(half, page_rows),
                KeyCode::Char('g') | KeyCode::Home => state.home(),
                KeyCode::Char('G') | KeyCode::End => state.end(page_rows),
                KeyCode::Char('n') => state.next_message(page_rows),
                KeyCode::Char('p') => state.prev_message(),
                KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Tab => state.toggle_fold(page_rows),
                _ => {}
            }
        }
    }

    /// Open one retained completed-tool body. This deliberately shares the
    /// transcript pager's alternate-screen guard and navigation vocabulary,
    /// but has no folds: every retained line is immediately visible.
    #[cfg(feature = "live-spill")]
    pub(crate) fn run_output_pager(
        spill: &CompletedSpill,
        surface: &mut dyn InputSurface,
        terminal_owns_turn: bool,
    ) -> io::Result<()> {
        let mut guard = AltScreenGuard::for_surface(surface, terminal_owns_turn)?;
        run_spills(&mut guard, std::slice::from_ref(spill), false)
    }

    /// Called by the presenter itself: no RemoteSurface round trip or second
    /// stdin owner. The alternate-screen guard restores its saved real tty.
    #[cfg(all(unix, feature = "live-spill"))]
    pub(crate) fn run_spill_picker(
        spills: &[CompletedSpill],
        output: std::fs::File,
    ) -> io::Result<()> {
        let mut guard = AltScreenGuard::enter_on(PanelOut::Tty(output), None)?;
        run_spills(&mut guard, spills, true)
    }

    #[cfg(feature = "live-spill")]
    fn run_spills(
        guard: &mut AltScreenGuard,
        spills: &[CompletedSpill],
        picker: bool,
    ) -> io::Result<()> {
        let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(&mut guard.out))?;
        terminal.clear()?;
        let mut selected = 0usize;
        let mut view = if picker {
            None
        } else {
            spills.first().map(|s| super::OutputView::new(s.lines()))
        };
        loop {
            let mut page_rows = 1usize;
            terminal.draw(|f| {
                let title = if view.is_some() {
                    format!("spill {}", spills[selected].id())
                } else {
                    "inspect retained output".into()
                };
                let subtitle = view.as_ref().map(|_| {
                    let s = &spills[selected];
                    format!(
                        "{} of {} lines retained · sanitized display, not an authorization payload",
                        s.lines().len(),
                        s.lines().len() + s.dropped_lines()
                    )
                });
                let body = crate::modal::frame(
                    f,
                    f.area(),
                    &crate::modal::Chrome {
                        title: &title,
                        subtitle,
                        hint: Some("Esc back · ↑↓ select · Enter inspect"),
                    },
                );
                page_rows = usize::from(body.height.saturating_sub(1)).max(1);
                if let Some(view) = &mut view {
                    view.draw(f, body);
                } else {
                    let rows = if spills.is_empty() {
                        vec![Line::raw(
                            "No output retained in this session. Older entries may have expired.",
                        )]
                    } else {
                        let top = selected.saturating_sub(page_rows - 1);
                        spills
                            .iter()
                            .enumerate()
                            .skip(top)
                            .take(page_rows)
                            .map(|(i, s)| {
                                let preview =
                                    s.lines().first().map(String::as_str).unwrap_or("(empty)");
                                Line::styled(
                                    format!(
                                        "{} spill {} · {} lines · {}",
                                        if i == selected { ">" } else { " " },
                                        s.id(),
                                        s.total_lines(),
                                        preview
                                    ),
                                    if i == selected {
                                        Style::default().add_modifier(Modifier::REVERSED)
                                    } else {
                                        Style::default()
                                    },
                                )
                            })
                            .collect()
                    };
                    f.render_widget(Paragraph::new(rows), body);
                }
            })?;
            let Event::Key(key) = event::read()? else {
                continue;
            };
            if key.kind != KeyEventKind::Press {
                continue;
            }
            if let Some(current) = &mut view {
                if current.key(key, page_rows) {
                    if !picker {
                        return Ok(());
                    }
                    view = None;
                }
                continue;
            }
            match key.code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::F(4) => return Ok(()),
                KeyCode::Char('c' | 'd') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    return Ok(())
                }
                KeyCode::Up => selected = selected.saturating_sub(1),
                KeyCode::Down => selected = (selected + 1).min(spills.len().saturating_sub(1)),
                KeyCode::Enter => {
                    view = spills
                        .get(selected)
                        .map(|s| super::OutputView::new(s.lines()));
                }
                _ => {}
            }
        }
    }
    #[cfg(test)]
    mod tests {
        use super::*;

        /// #2701: human headers must not share the model header's bold default foreground.
        #[test]
        fn human_header_uses_human_text_while_reply_header_keeps_default_foreground() {
            use newt_core::tty::theme::{Role, Theme};
            let theme = Theme::builtin().overlaid(
                "pager-test",
                &[(
                    Role::HumanText,
                    crossterm::style::Color::Rgb {
                        r: 12,
                        g: 34,
                        b: 56,
                    },
                )],
            );
            let human = row_style(RowKind::PromptHead, &theme);
            let reply = row_style(RowKind::ReplyHead, &theme);

            assert_eq!(human.fg, Some(Color::Rgb(12, 34, 56)));
            assert!(human.add_modifier.contains(Modifier::BOLD));
            assert_eq!(reply.fg, None);
            assert!(reply.add_modifier.contains(Modifier::BOLD));
        }
    }
} // mod terminal (rich-tui only)

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

    #[cfg(feature = "rich-tui")]
    #[test]
    fn inspection_search_reaches_hidden_text_and_enter_is_not_an_answer() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        let mut view = OutputView::new(["first", "payload needle", "last"]);
        let key = |code| KeyEvent::new(code, KeyModifiers::NONE);
        assert!(!view.key(key(KeyCode::Char('/')), 1));
        for c in "needle".chars() {
            view.key(key(KeyCode::Char(c)), 1);
        }
        assert!(!view.key(key(KeyCode::Enter), 1));
        assert_eq!(view.scroll, 1);
        assert!(!view.key(key(KeyCode::Enter), 1));
        assert!(!view.key(key(KeyCode::Right), 1));
        assert!(view.horizontal > 0);
        assert!(view.key(key(KeyCode::Esc), 1));
    }

    #[cfg(feature = "rich-tui")]
    #[test]
    fn inspection_renders_controls_as_text_and_keeps_long_lines() {
        let long = format!("{}END", "x".repeat(10_000));
        let view = OutputView::new(["\x1b[2J", long.as_str()]);
        assert!(!view.lines[0].contains('\x1b'));
        assert!(view.lines[1].ends_with("END"));
        assert_eq!(view.lines[1].len(), long.len());
    }

    #[cfg(feature = "rich-tui")]
    #[test]
    fn inspection_next_match_advances_after_render_clamps_the_last_page() {
        let mut view = OutputView::new(["first", "needle one", "needle two"]);
        view.search = "needle".into();
        view.find(false);
        assert_eq!(view.scroll, 1);
        let mut terminal =
            ratatui::Terminal::new(ratatui::backend::TestBackend::new(40, 5)).unwrap();
        terminal
            .draw(|frame| view.draw(frame, frame.area()))
            .unwrap();
        view.find(true);
        assert_eq!(view.scroll, 2);
    }

    #[cfg(feature = "rich-tui")]
    #[test]
    fn cockpit_pager_refuses_a_missing_terminal_loan() {
        let mut surface = crate::lean_input::LeanSurface::new(None).unwrap();
        let mut state = PagerState::new("unavailable owner", &[]);
        let error = run_pager(&mut state, &mut surface, true).unwrap_err();
        assert!(error.to_string().contains("terminal owner could not lend"));
    }

    fn turn(user: &str, assistant: &str, tools: usize) -> ConversationTurn {
        ConversationTurn {
            user: user.into(),
            assistant: assistant.into(),
            events: (0..tools)
                .map(|n| {
                    newt_core::ToolEvent::from_call(
                        format!("tool{n}"),
                        &serde_json::json!({"path": "x"}),
                        true,
                        Some(12),
                    )
                })
                .collect(),
            phantom_reaches: Vec::new(),
            sources: Vec::new(),
            tokens_in: None,
            tokens_out: None,
        }
    }

    /// The flattened shape: spine rows carry the `›`/`▸` sigils, tool blocks
    /// start FOLDED behind a header, and turns are blank-separated.
    #[test]
    fn rows_flatten_the_spine_with_folded_grey() {
        let state = PagerState::new(
            "mesh docking",
            &[
                turn("first ask\nsecond line", "the answer", 2),
                turn("follow-up", "done", 0),
            ],
        );
        let rows = state.rows();
        let texts: Vec<&str> = rows.iter().map(|r| r.text.as_str()).collect();
        assert_eq!(
            texts,
            vec![
                "› first ask",
                "  second line",
                "▸ ⚙ 2 tool calls — Enter unfolds",
                "▸ the answer",
                "",
                "› follow-up",
                "▸ done",
            ]
        );
        assert_eq!(rows[0].kind, RowKind::PromptHead);
        assert_eq!(rows[2].kind, RowKind::ToolFold);
        // Folded: no Tool rows at all.
        assert!(rows.iter().all(|r| r.kind != RowKind::Tool));
    }

    /// Unfolding reveals the summary lines in the inline grey vocabulary
    /// (⚙ name · ✓ · ms) and refolding hides them again.
    #[test]
    fn toggle_fold_reveals_and_hides_tool_summaries() {
        let mut state = PagerState::new("mesh docking", &[turn("ask", "answer", 2)]);
        state.toggle_fold(10);
        let rows = state.rows();
        assert!(rows
            .iter()
            .any(|r| r.kind == RowKind::Tool && r.text.contains("⚙ tool0 · ✓ · 12ms")));
        assert!(rows.iter().any(|r| r.text.contains("▾")));
        state.toggle_fold(10);
        assert!(state.rows().iter().all(|r| r.kind != RowKind::Tool));
    }

    /// A turn with no tools has no fold row, and toggling is a no-op.
    #[test]
    fn no_tools_means_no_fold_row() {
        let mut state = PagerState::new("mesh docking", &[turn("ask", "answer", 0)]);
        assert!(state.rows().iter().all(|r| r.kind != RowKind::ToolFold));
        let before = state.rows();
        state.toggle_fold(10);
        assert_eq!(state.rows(), before);
    }

    /// n jumps land each successive prompt head on the top row; p walks back —
    /// first to the current head, then to the previous turn's.
    #[test]
    fn message_jumps_walk_the_spine() {
        let mut state = PagerState::new(
            "mesh docking",
            &[
                turn("one", "a", 1),
                turn("two", "b", 0),
                turn("three", "c", 0),
            ],
        );
        // A small page so every head is reachable as the top row (jumps clamp
        // to max_scroll, the end-of-content rail — see scroll_clamps test).
        let page = 2;
        assert_eq!(state.current_turn(), 0);
        state.next_message(page);
        assert_eq!(state.rows()[state.scroll].text, "› two");
        assert_eq!(state.current_turn(), 1);
        state.next_message(page);
        assert_eq!(state.rows()[state.scroll].text, "› three");
        // Exactly at a head, p walks to the PREVIOUS turn…
        state.prev_message();
        assert_eq!(state.rows()[state.scroll].text, "› two");
        // …and after scrolling past a head, p first RETURNS to it.
        state.scroll_by(1, page);
        state.prev_message();
        assert_eq!(state.rows()[state.scroll].text, "› two");
    }

    /// Scroll clamps to [0, rows - page] and home/end hit the rails.
    #[test]
    fn scroll_clamps_to_content() {
        let mut state =
            PagerState::new("mesh docking", &[turn("one", "a", 0), turn("two", "b", 0)]);
        let page = 3;
        state.scroll_by(-10, page);
        assert_eq!(state.scroll, 0);
        state.scroll_by(100, page);
        assert_eq!(state.scroll, state.rows().len() - page);
        state.home();
        assert_eq!(state.scroll, 0);
        state.end(page);
        assert_eq!(state.scroll, state.rows().len() - page);
    }

    /// Folding a block ABOVE the viewport must not teleport the spine: the
    /// current prompt head keeps its on-screen offset.
    #[test]
    fn toggle_fold_keeps_the_current_head_pinned() {
        let mut state = PagerState::new("mesh docking", &[turn("ask", "answer", 3)]);
        let page = 4;
        state.toggle_fold(page); // unfold: 3 extra rows appear
        let head = 0;
        state.scroll = head; // head at top
        state.toggle_fold(page); // refold from the head — offset 0 preserved
        assert_eq!(state.rows()[state.scroll].text, "› ask");
    }

    /// The header position tracks the derived current turn.
    #[test]
    fn position_names_the_current_turn() {
        let mut state =
            PagerState::new("mesh docking", &[turn("one", "a", 0), turn("two", "b", 0)]);
        assert_eq!(state.position(), "turn 1/2");
        state.next_message(2);
        assert_eq!(state.position(), "turn 2/2");
    }

    /// Empty prompts/replies still produce a head row (the spine never skips
    /// a turn), and an empty record renders no rows without panicking.
    #[test]
    fn empty_edges_are_safe() {
        let state = PagerState::new("mesh docking", &[turn("", "", 0)]);
        let rows = state.rows();
        assert_eq!(rows[0].text, "› ");
        assert_eq!(rows[1].text, "▸ ");

        let mut empty = PagerState::new("mesh docking", &[]);
        assert!(empty.rows().is_empty());
        empty.scroll_by(5, 3);
        assert_eq!(empty.scroll, 0);
        assert_eq!(empty.position(), "turn 1/1");
        empty.next_message(3);
        empty.prev_message();
        empty.toggle_fold(3);
    }
    // ── #1677 state-model stress ────────────────────────────────────────
    //
    // The pure model is where scroll/fold/jump correctness is decided, so the
    // awkward shapes get pinned HERE rather than through a terminal: resize
    // (the one viewport change no keystroke can produce), fold churn changing
    // the rail underfoot, the extremes, and text the renderer will clip.

    #[test]
    fn a_resize_smaller_then_larger_never_strands_the_view() {
        // Regression for the renderer/model rail mismatch (#1677): the draw
        // path clamped to `len - 1` while every model clamp uses
        // `len - page_rows`, so GROWING the terminal left the scroll beyond
        // the end rail — a position the keyboard cannot reach, and one that
        // renders a short final page with content scrolled off the top.
        let turns: Vec<_> = (0..12)
            .map(|i| turn(&format!("p{i}"), "reply", 0))
            .collect();
        let mut s = PagerState::new("t", &turns);
        let total = s.rows().len();

        // Small viewport, parked at the end rail.
        s.end(4);
        assert_eq!(s.scroll, total - 4);

        // Grow the terminal: the rail moves UP, so the position must follow.
        s.clamp_scroll(20);
        assert_eq!(
            s.scroll,
            total.saturating_sub(20),
            "growing the viewport must re-clamp to the new end rail"
        );

        // Shrink again: the rail moves down, and clamping must not *push* the
        // view (clamp is a ceiling, never a jump).
        let before = s.scroll;
        s.clamp_scroll(4);
        assert_eq!(s.scroll, before, "shrinking must not move a valid position");

        // A viewport taller than the content pins to the top.
        s.clamp_scroll(total + 50);
        assert_eq!(s.scroll, 0);
    }

    #[test]
    fn a_viewport_of_one_row_is_survivable() {
        // The degenerate terminal (a 1-row split) must not divide by zero or
        // strand: `max_scroll` floors page_rows at 1.
        let turns: Vec<_> = (0..3).map(|i| turn(&format!("p{i}"), "r", 0)).collect();
        let mut s = PagerState::new("t", &turns);
        let total = s.rows().len();
        s.end(1);
        assert_eq!(s.scroll, total - 1);
        s.scroll_by(50, 1);
        assert_eq!(s.scroll, total - 1, "still clamped at the last row");
        s.clamp_scroll(0); // a zero-height body is treated as one row
        assert!(s.scroll < total);
    }

    #[test]
    fn page_and_half_page_moves_walk_and_clamp() {
        let turns: Vec<_> = (0..30).map(|i| turn(&format!("p{i}"), "r", 0)).collect();
        let mut s = PagerState::new("t", &turns);
        let page = 10usize;
        let max = s.rows().len() - page;

        s.scroll_by(page as isize, page); // PageDown
        assert_eq!(s.scroll, page);
        s.scroll_by(-(page as isize), page); // PageUp
        assert_eq!(s.scroll, 0);
        s.scroll_by(-(page as isize), page); // PageUp at the top rail
        assert_eq!(s.scroll, 0, "saturates at the top, never wraps");
        s.scroll_by((page / 2) as isize, page); // Ctrl-D
        assert_eq!(s.scroll, page / 2);
        for _ in 0..50 {
            s.scroll_by(page as isize, page);
        }
        assert_eq!(s.scroll, max, "clamps at the end rail, never past it");
    }

    #[test]
    fn home_and_end_are_the_rails() {
        let turns: Vec<_> = (0..8).map(|i| turn(&format!("p{i}"), "r", 0)).collect();
        let mut s = PagerState::new("t", &turns);
        let page = 5usize;
        s.end(page);
        assert_eq!(s.scroll, s.rows().len() - page);
        s.home();
        assert_eq!(s.scroll, 0);
        // End on content SHORTER than the viewport stays at the top rather
        // than producing a negative rail.
        let short = vec![turn("only", "one", 0)];
        let mut s2 = PagerState::new("t", &short);
        s2.end(100);
        assert_eq!(s2.scroll, 0);
    }

    #[test]
    fn unfolding_moves_the_rail_and_scroll_stays_valid() {
        // Fold churn changes `rows().len()` underfoot, so every clamp must be
        // recomputed against the CURRENT flattening rather than a cached
        // length. Toggling is done on the turn the model says is current
        // (turn 0 at home) instead of walking to an arbitrary turn — see
        // `the_end_rail_bounds_how_far_the_spine_jumps_can_reach` for why a
        // walk to the LAST turn is not a thing the model promises.
        let turns: Vec<_> = (0..6).map(|i| turn(&format!("p{i}"), "r", 3)).collect();
        let mut s = PagerState::new("t", &turns);
        let page = 6usize;

        s.home();
        assert_eq!(s.current_turn(), 0);
        let folded_rows = s.rows().len();
        let folded_rail = {
            s.end(page);
            s.scroll
        };

        // Unfold turn 0: content grows by exactly its tool lines, so the end
        // rail moves DOWN by the same amount.
        s.home();
        s.toggle_fold(page);
        assert_eq!(
            s.rows().len(),
            folded_rows + 3,
            "unfolding adds exactly the turn's tool lines"
        );
        s.end(page);
        assert_eq!(
            s.scroll,
            folded_rail + 3,
            "the end rail tracks the new content length"
        );

        // Park at the rail, then RE-fold: the rail moves back up and the
        // parked position must be re-clamped rather than left past the end.
        s.home();
        s.toggle_fold(page);
        s.scroll = folded_rail + 3; // where the operator was before the fold
        s.clamp_scroll(page);
        assert_eq!(
            s.scroll, folded_rail,
            "re-folding pulls a stranded position back to the rail"
        );
    }

    #[test]
    fn the_end_rail_bounds_how_far_the_spine_jumps_can_reach() {
        // A PINNED LIMITATION, deliberately recorded rather than left as
        // folklore (#1677). `current_turn` is derived as "the last prompt head
        // at or above the top row", and `next_message` clamps its target to
        // the end rail. So when the final turn's head falls INSIDE the last
        // page, `n` cannot make that turn current: scroll parks at
        // `max_scroll`, the head sits below the top row, and the derivation
        // keeps naming the previous turn. The final turn is fully VISIBLE at
        // that point — this is a naming/targeting limit, not a scrolling one —
        // but two consequences follow that a reader should know about: the
        // position header under-reports at the bottom, and a fold keystroke
        // there targets the turn at the TOP of the view.
        //
        // Widening the derivation to "the last head visible in the viewport"
        // would fix both, and would also move fold targeting — which is a
        // behavior change, not a landing fix. Tracked as follow-up on #1672.
        let turns: Vec<_> = (0..4).map(|i| turn(&format!("p{i}"), "short", 0)).collect();
        let mut s = PagerState::new("t", &turns);
        let page = 8usize; // tall enough that the last heads sit inside it
        let rows = s.rows();
        let last_head = rows
            .iter()
            .rposition(|r| r.kind == RowKind::PromptHead)
            .expect("a head exists");
        assert!(
            last_head > s.max_scroll(page),
            "precondition: the final head lies beyond the end rail"
        );

        // Pressing `n` repeatedly converges and then STOPS, without spinning.
        s.home();
        let mut seen = Vec::new();
        for _ in 0..10 {
            s.next_message(page);
            seen.push(s.current_turn());
        }
        let reached = *seen.last().expect("jumped");
        assert!(
            reached < turns.len() - 1,
            "the final turn is not reachable as `current` from the end rail"
        );
        assert!(
            seen.windows(2).all(|w| w[1] >= w[0]),
            "jumps never move backwards: {seen:?}"
        );
        assert_eq!(
            s.scroll,
            s.max_scroll(page),
            "the view IS parked at the bottom — the last turn is on screen"
        );
    }

    #[test]
    fn the_current_turn_follows_the_scroll() {
        let turns: Vec<_> = (0..5)
            .map(|i| turn(&format!("prompt {i}"), "reply\nline\nline", 0))
            .collect();
        let mut s = PagerState::new("t", &turns);
        assert_eq!(s.current_turn(), 0);
        let rows = s.rows();
        // Park the top row exactly on the last turn's prompt head.
        let last_head = rows
            .iter()
            .rposition(|r| r.kind == RowKind::PromptHead)
            .expect("a prompt head exists");
        s.scroll = last_head;
        assert_eq!(
            s.current_turn(),
            4,
            "current is the last head at or above the top row"
        );
        s.home();
        assert_eq!(s.current_turn(), 0, "derived, not remembered");
    }

    #[test]
    fn wide_and_unicode_text_survives_the_model_intact() {
        // The model does not wrap or clip — the renderer does. What it must
        // guarantee is that the bytes it hands over are the stored bytes, so
        // a CJK/emoji transcript is never corrupted on the way to the screen.
        let cjk = "日本語のテキストです";
        let emoji = "🦎 newt 👀 spine";
        let turns = vec![turn(cjk, emoji, 0)];
        let s = PagerState::new("t", &turns);
        let rows = s.rows();
        assert!(
            rows.iter().any(|r| r.text.contains(cjk)),
            "wide text preserved: {rows:?}"
        );
        assert!(
            rows.iter().any(|r| r.text.contains(emoji)),
            "emoji preserved: {rows:?}"
        );
        // Row count is per LINE, not per display column — one line in, one
        // row out, regardless of how many columns it will occupy.
        assert_eq!(
            rows.iter()
                .filter(|r| r.kind == RowKind::PromptHead)
                .count(),
            1
        );
    }

    #[test]
    fn a_very_long_line_is_one_row_and_is_not_truncated_by_the_model() {
        let long = "x".repeat(20_000);
        let turns = vec![turn(&long, "r", 0)];
        let s = PagerState::new("t", &turns);
        let rows = s.rows();
        let head = rows
            .iter()
            .find(|r| r.kind == RowKind::PromptHead)
            .expect("head");
        assert!(head.text.len() >= 20_000, "the model never truncates");
        assert_eq!(
            rows.iter()
                .filter(|r| r.kind == RowKind::PromptHead)
                .count(),
            1,
            "one logical line is exactly one row (clipping is the renderer's job)"
        );
    }

    #[test]
    fn one_turn_and_many_turns_flatten_consistently() {
        let one = PagerState::new("t", &[turn("p", "r", 0)]);
        assert_eq!(
            one.rows()
                .iter()
                .filter(|r| r.kind == RowKind::Blank)
                .count(),
            0,
            "no separator before the first turn"
        );
        let many: Vec<_> = (0..25).map(|i| turn(&format!("p{i}"), "r", 0)).collect();
        let s = PagerState::new("t", &many);
        assert_eq!(
            s.rows().iter().filter(|r| r.kind == RowKind::Blank).count(),
            24,
            "exactly one separator BETWEEN each pair of turns"
        );
        assert_eq!(
            s.rows()
                .iter()
                .filter(|r| r.kind == RowKind::PromptHead)
                .count(),
            25
        );
    }

    #[test]
    fn a_ten_thousand_row_transcript_stays_linear() {
        // Long-transcript sanity (#1677). Deliberately asserts SHAPE, not
        // wall-clock: timing has no place in the mocked unit tier and would be
        // flaky under parallel CI load. What this pins is what a quadratic
        // regression would break — flattening is exactly one row per logical
        // line, the rails are computed from the current flattening, and a fold
        // adds exactly its own tool lines with no compounding. The measured
        // interactive timing is recorded in the PR body instead.
        // 2_000 turns x 6 rows each (prompt + 3 reply lines + fold header +
        // separator) clears the 10k bar the sanity check is specified at.
        let turns: Vec<_> = (0..2_000)
            .map(|i| turn(&format!("prompt {i}"), "reply\nsecond\nthird", 2))
            .collect();
        let mut s = PagerState::new("long", &turns);
        let rows = s.rows().len();
        assert!(rows > 10_000, "expected a 10k+ row transcript, got {rows}");

        let page = 40usize;
        s.end(page);
        assert_eq!(s.scroll, rows - page, "the end rail is exact at this size");
        s.home();
        assert_eq!(s.scroll, 0);

        // A bounded walk down the spine: each jump moves forward, and none of
        // them costs more than the flattening itself.
        let mut last = s.current_turn();
        for _ in 0..200 {
            s.next_message(page);
            let now = s.current_turn();
            assert!(now >= last, "jumps are monotonic on a long transcript");
            last = now;
        }
        assert!(last > 100, "200 jumps made real progress, reached {last}");

        // Folding at this size adds exactly the folded turn's tool lines.
        s.home();
        let before = s.rows().len();
        s.toggle_fold(page);
        assert_eq!(
            s.rows().len(),
            before + 2,
            "one unfold adds exactly its two tool lines, even at 10k rows"
        );
    }
}