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
//! TTY renderer for the turn-scoped active-tool spill viewport.

use crate::completed_spill::CompletedSpillArchive;
use crate::spill_view::{SpillStream, SpillView};
use crossterm::cursor::{MoveDown, MoveTo, MoveToColumn, MoveUp};
use crossterm::queue;
use crossterm::style::{Color, ContentStyle, Print, ResetColor, SetForegroundColor, StyledContent};
use crossterm::terminal::{Clear, ClearType};
use newt_core::{LiveToolOutput, ToolOutputStream};
// #1640: CompletedSpillRenderer trait for Rich TUI completed spill rendering
use newt_core::agentic::{write_file_change_row, CompletedSpillRenderer, FileChangePresentation};
use newt_core::tty::{blank_rows, OnCollision, Placement, RegionLease, Terminal};
use std::io::Write;
#[cfg(any(unix, test))]
use std::sync::atomic::AtomicBool;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, TryLockError};

const HISTORY_LINES: usize = 4_096;
const LINE_CHARS: usize = 4_096;

struct RenderState {
    geometry: Box<dyn Fn() -> Option<(usize, usize)> + Send + Sync>,
    view: Option<SpillView>,
    file_change: Option<RichFileChange>,
    columns: usize,
    terminal_rows: usize,
    collapsed_rows: usize,
    max_rows: usize,
    desired_rows: usize,
    drawable: bool,
    color: bool,
    generation: Option<u64>,
}

struct RichFileChange {
    change: Arc<FileChangePresentation>,
    prefix: String,
    suffix: String,
    rows: Vec<Vec<StyledContent<String>>>,
}

impl RichFileChange {
    fn reproject(&mut self, columns: usize) -> String {
        // SpillView reserves its gutter and the terminal's final column.
        self.rows = self
            .change
            .display_rows(&self.prefix, &self.suffix, columns.saturating_sub(3));
        self.rows
            .iter()
            .map(|row| {
                row.iter()
                    .map(|run| run.content().as_str())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// Where the frame's rows are: the arbiter's placement under the transcript
/// (`Terminal::lease_below_cursor_quiet`), held for as long as the frame is up.
struct Frame {
    /// The arbiter's registration of the rows; returned silently when the
    /// frame goes. `None` for the in-memory test renderers, which place
    /// against a screen model and register nothing.
    _lease: Option<RegionLease>,
    place: Placement,
    /// The width the frame was painted at. A frame erased at another width
    /// has been reflowed by the terminal, so its rows are no longer the ones
    /// the placement granted; see [`erase_output`].
    columns: usize,
    terminal_rows: usize,
}

/// Asks where `height` rows may open under the transcript. Production asks the
/// arbiter; the unit tier asks its screen model. `None` means the frame is
/// painted nowhere this time, never somewhere guessed.
type Placer = Box<dyn FnMut(u16) -> Option<(Option<RegionLease>, Placement)> + Send>;

/// The arbiter's placement: one cursor query with stdin's other reader
/// quiesced, the rows under it (the transcript scrolled by the deficit when
/// they do not fit), shifted above a holder exactly as a permission frame is.
fn arbiter_placer() -> Placer {
    Box::new(|height| {
        Terminal::lease_below_cursor_quiet(height, OnCollision::Shift)
            .ok()
            .flatten()
            .map(|(lease, place)| (Some(lease), place))
    })
}

struct OutputState {
    writer: TerminalWriter,
    /// The exact lines last painted, kept for the one erase that cannot use
    /// the placement: a frame whose width changed under it has been reflowed
    /// by the terminal, and only re-wrapping these at the NEW width recovers
    /// its rows. See [`physical_rows`].
    painted_lines: Vec<String>,
    painted_generation: Option<u64>,
    /// A visible frame was erased, but its replacement could not be placed.
    /// Keep this request until a watcher tick can retry, or its owner ends.
    placement_retry: Option<u64>,
    /// The rows the painted frame occupies, from the placer.
    frame: Option<Frame>,
    placer: Placer,
    /// Arbiter registration (#1410). Present for the real stdout viewport;
    /// `None` for the `#[cfg(test)]` in-memory renderers, which register
    /// explicitly (`register_for_test`) when a test wants the suspend gate.
    ///
    /// It lives HERE, behind the same mutex `paint_generation` already takes
    /// first, so the gate costs one check on a lock the paint path holds
    /// anyway — no new parameter threaded through `write`, and the handle's
    /// lifetime is exactly the renderer's.
    registration: Option<newt_core::tty::EphemeralRegistration>,
}

enum TerminalWriter {
    Stdout,
    #[cfg(test)]
    Other(Box<dyn Write + Send>),
}

impl TerminalWriter {
    fn write_batch(
        &mut self,
        bytes: &[u8],
        still_valid: impl FnOnce() -> bool,
    ) -> std::io::Result<bool> {
        match self {
            Self::Stdout => {
                let stdout = std::io::stdout();
                let mut stdout = stdout.lock();
                if !still_valid() {
                    return Ok(false);
                }
                stdout.write_all(bytes)?;
                stdout.flush()?;
            }
            #[cfg(test)]
            Self::Other(writer) => {
                if !still_valid() {
                    return Ok(false);
                }
                writer.write_all(bytes)?;
                writer.flush()?;
            }
        }
        Ok(true)
    }
}

/// Single stdout owner for one active tool's redraw region.
///
/// Width-shrink cleanup follows the primary-screen reflow used by mainstream
/// terminal emulators: a painted logical line is rewrapped at the new column
/// count. ANSI exposes no portable reflow capability query, so this is an
/// assumption, not a probe. Normal painting and unchanged-size cleanup use
/// exact absolute rows.
/// Height-only resize cleanup follows the retained cursor with bounded line
/// clears, then obtains a fresh placement before repainting.
///
/// **Reflow is a REQUIREMENT of the rich tier, not a caveat** (#1426, decided
/// 2026-07-27 — see `docs/decisions/lean_rich_tui_morphologies.md`). An emulator
/// that keeps old rows un-reflowed is a lean-tier terminal and should run
/// `--lean`, which has no redraw region and therefore no rewind to get wrong.
/// Assuming no-reflow instead would leave stale rows on *every* shrink in the
/// common case in order to be safe in the rare one.
///
/// The frame's rows come from the tty arbiter's placement under the
/// transcript (`Terminal::lease_below_cursor_quiet`): painted at absolute
/// rows, erased as exactly those rows at unchanged geometry, with the cursor
/// put back where the transcript ended. Resize cleanup follows the retained
/// cursor because the old absolute rows are no longer true. Width reflow still
/// uses `MoveUp` plus `Clear(FromCursorDown)`; it is not a bounded-row clear.
pub(crate) struct LiveSpillRenderer {
    state: Arc<Mutex<RenderState>>,
    output: Arc<Mutex<OutputState>>,
    abandoned_through: Arc<AtomicU64>,
    completed_archive: Option<Arc<CompletedSpillArchive>>,
    #[cfg(any(unix, test))]
    repaint_requested: Arc<AtomicU64>,
    #[cfg(any(unix, test))]
    repaint_running: Arc<AtomicBool>,
}

impl LiveSpillRenderer {
    /// The real stdout viewport, registered with the line arbiter (#1410).
    ///
    /// Returns an `Arc` because registration needs `Arc<dyn Ephemeral>`. The
    /// arbiter holds only a `Weak` and the handle stores only a `u64`, so this
    /// is not a reference cycle: the last `Arc` dropping runs `OutputState`'s
    /// drop, which deregisters.
    pub(crate) fn stdout(
        rows: usize,
        color: bool,
        completed_archive: Arc<CompletedSpillArchive>,
    ) -> Option<Arc<Self>> {
        let me = Arc::new(Self::with_output_and_geometry(
            TerminalWriter::Stdout,
            arbiter_placer(),
            rows,
            color,
            Some(completed_archive),
            || {
                crossterm::terminal::size()
                    .ok()
                    .map(|(columns, rows)| (usize::from(columns), usize::from(rows)))
            },
        )?);
        me.register_with_arbiter();
        Some(me)
    }

    /// Bind this viewport to the line arbiter so `suspend_for_prompt` erases it
    /// before a question and restores it after.
    fn register_with_arbiter(self: &Arc<Self>) {
        let ephemeral: Arc<dyn newt_core::tty::Ephemeral> = self.clone();
        let registration = newt_core::tty::Terminal::register_ephemeral(&ephemeral);
        self.output
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .registration = Some(registration);
    }

    /// Test-only registration: the in-memory renderers are constructed bare so
    /// the ~15 existing paint tests keep running with the gate inert. A test
    /// that wants to prove the gate opts in.
    #[cfg(test)]
    fn register_for_test(self: &Arc<Self>) {
        self.register_with_arbiter();
    }

    #[cfg(test)]
    fn with_writer(
        writer: impl Write + Send + 'static,
        placer: Placer,
        columns: usize,
        rows: usize,
        color: bool,
    ) -> Self {
        Self::with_writer_and_geometry(writer, placer, rows, color, move || {
            Some((columns, rows.saturating_add(3)))
        })
        .expect("fixed test geometry is drawable")
    }

    #[cfg(test)]
    fn with_writer_and_geometry(
        writer: impl Write + Send + 'static,
        placer: Placer,
        desired_rows: usize,
        color: bool,
        geometry: impl Fn() -> Option<(usize, usize)> + Send + Sync + 'static,
    ) -> Option<Self> {
        Self::with_output_and_geometry(
            TerminalWriter::Other(Box::new(writer)),
            placer,
            desired_rows,
            color,
            None,
            geometry,
        )
    }

    fn with_output_and_geometry(
        writer: TerminalWriter,
        placer: Placer,
        desired_rows: usize,
        color: bool,
        completed_archive: Option<Arc<CompletedSpillArchive>>,
        geometry: impl Fn() -> Option<(usize, usize)> + Send + Sync + 'static,
    ) -> Option<Self> {
        let (columns, terminal_rows) = geometry()?;
        let (collapsed_rows, max_rows) = viewport_geometry(desired_rows, columns, terminal_rows)?;
        Some(Self {
            state: Arc::new(Mutex::new(RenderState {
                geometry: Box::new(geometry),
                view: None,
                file_change: None,
                columns,
                terminal_rows,
                collapsed_rows,
                max_rows,
                desired_rows,
                drawable: true,
                color,
                generation: None,
            })),
            output: Arc::new(Mutex::new(OutputState {
                writer,
                painted_lines: Vec::new(),
                painted_generation: None,
                placement_retry: None,
                frame: None,
                placer,
                registration: None,
            })),
            abandoned_through: Arc::new(AtomicU64::new(0)),
            completed_archive,
            #[cfg(any(unix, test))]
            repaint_requested: Arc::new(AtomicU64::new(0)),
            #[cfg(any(unix, test))]
            repaint_running: Arc::new(AtomicBool::new(false)),
        })
    }

    #[cfg(any(unix, test))]
    pub(crate) fn scroll_up(&self) -> bool {
        self.scroll(SpillView::scroll_up)
    }

    #[cfg(any(unix, test))]
    pub(crate) fn scroll_down(&self) -> bool {
        self.scroll(SpillView::scroll_down)
    }

    #[cfg(any(unix, test))]
    pub(crate) fn toggle_expanded(&self) -> bool {
        self.scroll(SpillView::toggle_expanded)
    }

    /// #1704 (Ctrl-t): expand to half the console height.
    #[cfg(unix)]
    #[allow(dead_code)]
    pub(crate) fn expand_half(&self) -> bool {
        self.scroll(SpillView::expand_half)
    }

    /// #1704: is the user scrolled back off the tail (explore mode)?
    #[cfg(unix)]
    #[allow(dead_code)]
    pub(crate) fn is_exploring(&self) -> bool {
        let state = self.lock_state();
        state
            .view
            .as_ref()
            .is_some_and(|view| !view.is_following_tail())
    }

    /// #1704 (Esc while exploring): leave explore mode — snap back to the tail.
    #[cfg(unix)]
    #[allow(dead_code)]
    pub(crate) fn exit_explore(&self) -> bool {
        self.scroll(SpillView::scroll_to_bottom)
    }

    // #1303 step 5: editor-mode nav (vi `gg`/`G`/`C-d`/`C-u`, emacs paging),
    // each riding the same single-owner `scroll` write discipline. Reached ONLY
    // through the `#[cfg(unix)]` keyboard-watcher `SpillInput` impl (no test
    // calls them directly, unlike scroll_up/scroll_down/toggle_expanded) — so
    // gate them `unix`, not `any(unix, test)`, or the Windows `test` build
    // compiles them with their sole (unix-only) caller absent → dead_code.
    #[cfg(unix)]
    pub(crate) fn scroll_to_top(&self) -> bool {
        self.scroll(SpillView::scroll_to_top)
    }

    #[cfg(unix)]
    pub(crate) fn scroll_to_bottom(&self) -> bool {
        self.scroll(SpillView::scroll_to_bottom)
    }

    #[cfg(unix)]
    pub(crate) fn half_page_up(&self) -> bool {
        self.scroll(SpillView::half_page_up)
    }

    #[cfg(unix)]
    pub(crate) fn half_page_down(&self) -> bool {
        self.scroll(SpillView::half_page_down)
    }

    // The unix keyboard watcher checks geometry and pending replacements
    // between stdin polls; it must never block behind terminal output.
    #[cfg(unix)]
    pub(crate) fn refresh_geometry(&self) -> bool {
        let Some(mut state) = self.try_lock_state() else {
            return false;
        };
        if state.view.is_none() {
            return false;
        }
        let before = (
            state.columns,
            state.terminal_rows,
            state.collapsed_rows,
            state.max_rows,
            state.drawable,
        );
        let _ = sync_geometry(&mut state);
        let changed = before
            != (
                state.columns,
                state.terminal_rows,
                state.collapsed_rows,
                state.max_rows,
                state.drawable,
            );
        let generation = state.generation;
        let drawable = state.drawable;
        drop(state);
        // Never block the stdin watcher behind a paint that may itself be
        // waiting for its read token. A refused replacement remains pending
        // even after sync_geometry consumed the resize; the next tick retries.
        let retry = drawable
            && generation.is_some_and(|generation| !self.is_abandoned(generation))
            && self.output.try_lock().is_ok_and(|output| {
                output.placement_retry == generation
                    && !output
                        .registration
                        .as_ref()
                        .is_some_and(newt_core::tty::EphemeralRegistration::suspended)
            });
        if changed || retry {
            self.repaint_async();
        }
        true
    }

    #[cfg(any(unix, test))]
    fn scroll(&self, action: fn(&mut SpillView)) -> bool {
        // A terminal write may hold `output` indefinitely, but every renderer
        // path releases `state` before writing. Waiting for this short model
        // mutation therefore makes a keypress reliable without coupling input
        // responsiveness to terminal I/O.
        let mut state = self.lock_state();
        let Some(view) = state.view.as_mut() else {
            return false;
        };
        action(view);
        drop(state);
        self.repaint_async();
        true
    }

    #[cfg(any(unix, test))]
    fn repaint_async(&self) {
        self.repaint_requested.fetch_add(1, Ordering::Release);
        if self
            .repaint_running
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return;
        }
        let state = self.state.clone();
        let output = self.output.clone();
        let abandoned_through = self.abandoned_through.clone();
        let repaint_requested = self.repaint_requested.clone();
        let repaint_running = self.repaint_running.clone();
        if std::thread::Builder::new()
            .name("newt-live-spill-input".to_string())
            .spawn(move || {
                run_input_repaint(
                    &state,
                    &output,
                    &abandoned_through,
                    &repaint_requested,
                    &repaint_running,
                );
            })
            .is_err()
        {
            self.repaint_running.store(false, Ordering::Release);
        }
    }

    #[cfg(test)]
    pub(crate) fn is_active(&self) -> bool {
        self.lock_state().view.is_some()
    }

    #[cfg(test)]
    fn snapshot_lines(&self) -> Vec<String> {
        let state = self.lock_state();
        state
            .view
            .as_ref()
            .map(|view| fixed_frame_lines(view, state.generation == Some(COMPLETED_GENERATION)))
            .unwrap_or_default()
    }

    fn lock_state(&self) -> std::sync::MutexGuard<'_, RenderState> {
        self.state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn try_lock_state(&self) -> Option<std::sync::MutexGuard<'_, RenderState>> {
        match self.state.try_lock() {
            Ok(state) => Some(state),
            Err(TryLockError::Poisoned(poisoned)) => Some(poisoned.into_inner()),
            Err(TryLockError::WouldBlock) => None,
        }
    }

    fn is_abandoned(&self, generation: u64) -> bool {
        generation <= self.abandoned_through.load(Ordering::Acquire)
    }
}

/// #1410 — the viewport is the workspace's other cursor owner, so the arbiter
/// has to be able to get it off the screen before a question renders.
///
/// `arbiter.rs`'s own trait doc named this as an unfinished step, and named the
/// hazard: this renderer's `Clear(FromCursorDown)` rewind "can destroy rows it
/// does not own".
impl newt_core::tty::Ephemeral for LiveSpillRenderer {
    /// Erase whatever generation is currently painted.
    ///
    /// Idempotent by construction: `erase_output` clears both
    /// `painted_lines` and `painted_generation`, and the guard below then
    /// makes every subsequent call write zero bytes — the same shape as
    /// `LineLease::erase`.
    ///
    /// The lock is **blocking**, deliberately. A `try_lock` that gave up would
    /// return having written nothing while `painted_generation` is still set,
    /// and the *next* `erase_output` would then rewind from a cursor now below
    /// the question and the operator's typed answer, deleting both. A wedged
    /// stdout blocks everything anyway; a skipped erase corrupts.
    fn erase(&self) {
        // Re-sync both dimensions before cleanup. A height-only resize can
        // scroll the placement even when frame height is unchanged; a width
        // resize reflows the painted lines. Finish takes the same precaution.
        //
        // Scoped so `state` is released before `output` is taken: every other
        // path here locks state-then-output and drops state in between.
        let (columns, terminal_rows) = {
            let mut state = self.lock_state();
            let _ = sync_geometry(&mut state);
            (state.columns, state.terminal_rows)
        };
        let mut output = self
            .output
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(generation) = output.painted_generation {
            erase_output(
                &mut output,
                columns,
                terminal_rows,
                &self.abandoned_through,
                generation,
            );
        }
    }

    /// Repaint the frame the prompt displaced.
    ///
    /// **Synchronous**, not `repaint_async`. `PromptWindow::drop` documents
    /// that the terminal mode goes back "only after the screen is whole
    /// again"; an async restore returns before the frame exists, and the
    /// spawned repaint would then race the caller's canonical output — landing
    /// the frame *after* a denial message, recording rows it does not own, and
    /// leaving the next erase to rewind through that message.
    ///
    /// Unwind-guarded because a panic here escapes through
    /// `suspend_for_prompt`, which would leave the arbiter's `suspended` flag
    /// set with no `PromptWindow` ever constructed — silencing every spinner in
    /// the process for good. A viewport that fails to repaint is a cosmetic
    /// loss; that is not.
    fn restore(&self) {
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let generation = self.lock_state().generation;
            if let Some(generation) = generation {
                paint_generation(
                    &self.state,
                    &self.output,
                    &self.abandoned_through,
                    generation,
                );
            }
        }));
    }
}

impl LiveToolOutput for LiveSpillRenderer {
    fn start(&self, generation: u64) {
        if self.is_abandoned(generation) {
            return;
        }
        let mut state = self.lock_state();
        let _ = sync_geometry(&mut state);
        let mut view = SpillView::with_limits(
            state.columns,
            state.collapsed_rows,
            HISTORY_LINES,
            LINE_CHARS,
        );
        view.resize(state.columns, state.collapsed_rows, state.max_rows);
        state.view = Some(view);
        state.file_change = None;
        state.generation = Some(generation);
    }

    fn write(&self, generation: u64, stream: ToolOutputStream, chunk: &[u8]) {
        if chunk.is_empty() {
            return;
        }
        if self.is_abandoned(generation) {
            return;
        }
        let mut state = self.lock_state();
        if state.generation != Some(generation) {
            return;
        }
        let Some(view) = state.view.as_mut() else {
            return;
        };
        let stream = match stream {
            ToolOutputStream::Stdout => SpillStream::Stdout,
            ToolOutputStream::Stderr => SpillStream::Stderr,
        };
        view.push_stream_bytes(stream, chunk);
        let _ = sync_geometry(&mut state);
        drop(state);
        paint_generation(
            &self.state,
            &self.output,
            &self.abandoned_through,
            generation,
        );
    }

    fn finish(&self, generation: u64) {
        if self.is_abandoned(generation) {
            return;
        }
        let mut state = self.lock_state();
        if state.generation != Some(generation) {
            return;
        }
        if let Some(view) = state.view.as_mut() {
            view.finish();
        }
        let _ = sync_geometry(&mut state);
        let columns = state.columns;
        let terminal_rows = state.terminal_rows;
        // #1303 step 6 (DEFERRED — clean seam): the post-completion overlay
        // attaches HERE. Instead of dropping the finished `SpillView`, a
        // retain-overlay would move it (or its `lines` + `dropped_lines`) into a
        // generation-keyed slot on `RenderState`, beside `view`, reusing
        // `frame()`/`fixed_frame_lines` for a bounded reopenable viewer anchored
        // at the cursor (decision clause 3, grounding §4). The committed block is
        // still re-rendered from the authoritative envelope (`display.rs`), never
        // the live buffer; an abandoned generation is NOT retainable. Kept out of
        // v1 to preserve the single-owner hand-off below unchanged.
        state.view = None;
        state.file_change = None;
        state.generation = None;
        drop(state);
        erase_generation(
            &self.output,
            &self.abandoned_through,
            generation,
            columns,
            terminal_rows,
        );
    }

    fn abandon(&self, generation: u64) {
        // Leave the already-painted frame where it is: canonical output may
        // begin as soon as this fast invalidation returns. The next generation
        // discards this bookkeeping instead of rewinding from that new cursor.
        self.abandoned_through
            .fetch_max(generation, Ordering::AcqRel);
        if let Some(mut state) = self.try_lock_state() {
            if state.generation == Some(generation) {
                state.view = None;
                state.file_change = None;
                state.generation = None;
            }
        }
    }
}

fn fixed_frame_lines(view: &SpillView, completed: bool) -> Vec<String> {
    let frame = if completed {
        view.completed_frame()
    } else {
        view.frame()
    };
    let rows = view.visible_rows();
    let mut lines = Vec::with_capacity(rows + 2);
    lines.push(frame.top.line);
    lines.extend(frame.content.into_iter().map(|row| row.line));
    while lines.len() < rows + 1 {
        lines.push(if completed { "⎴" } else { "▒" }.to_string());
    }
    lines.push(frame.bottom.line);
    lines
}

fn fixed_file_change_styles(
    view: &SpillView,
    change: &RichFileChange,
) -> Vec<Vec<StyledContent<String>>> {
    let frame = view.completed_frame();
    let dim = ContentStyle {
        foreground_color: Some(
            newt_core::tty::theme::active().color(newt_core::tty::theme::Role::Dim),
        ),
        ..ContentStyle::default()
    };
    let plain = |text: String| vec![dim.apply(text)];
    let mut lines = vec![plain(frame.top.line)];
    for row in frame.content {
        let source = row.source_line.and_then(|index| change.rows.get(index));
        let gutter = format!("{} ", row.gutter.glyph());
        let Some(source) = source.filter(|source| {
            row.line == format!("{gutter}{}", row.text)
                && source
                    .iter()
                    .map(|run| run.content().as_str())
                    .collect::<String>()
                    .starts_with(&row.text)
        }) else {
            lines.push(plain(row.line));
            continue;
        };
        let mut remaining = row.text.chars().count();
        let mut styled = plain(gutter);
        for run in source {
            if remaining == 0 {
                break;
            }
            let text: String = run.content().chars().take(remaining).collect();
            remaining -= text.chars().count();
            styled.push(run.style().apply(text));
        }
        lines.push(styled);
    }
    while lines.len() < view.visible_rows() + 1 {
        lines.push(plain("⎴".into()));
    }
    lines.push(plain(frame.bottom.line));
    lines
}

fn viewport_geometry(
    desired_rows: usize,
    columns: usize,
    terminal_rows: usize,
) -> Option<(usize, usize)> {
    // Two boundary rows plus the cursor row below the frame must fit. Very
    // small terminals stay on the canonical completion-only path.
    (desired_rows > 0 && columns >= 2 && terminal_rows >= 4).then(|| {
        let max_rows = terminal_rows - 3;
        (desired_rows.min(max_rows), max_rows)
    })
}

fn sync_geometry(state: &mut RenderState) -> bool {
    let Some((columns, terminal_rows)) = (state.geometry)() else {
        state.drawable = false;
        return false;
    };
    state.terminal_rows = terminal_rows;
    let Some((collapsed_rows, max_rows)) =
        viewport_geometry(state.desired_rows, columns, terminal_rows)
    else {
        state.columns = columns;
        state.drawable = false;
        return false;
    };

    if !state.drawable
        || state.columns != columns
        || state.collapsed_rows != collapsed_rows
        || state.max_rows != max_rows
    {
        state.columns = columns;
        state.collapsed_rows = collapsed_rows;
        state.max_rows = max_rows;
        let replacement = state
            .file_change
            .as_mut()
            .map(|change| change.reproject(columns));
        if let Some(view) = state.view.as_mut() {
            view.resize(columns, collapsed_rows, max_rows);
            if let Some(text) = replacement {
                view.replace_completed_text(&text);
            }
        }
    }
    state.drawable = true;
    true
}

fn paint_generation(
    state: &Mutex<RenderState>,
    output: &Mutex<OutputState>,
    abandoned_through: &AtomicU64,
    generation: u64,
) {
    if is_abandoned(abandoned_through, generation) {
        return;
    }
    let mut output = output
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    // #1410 — THE PAINT GATE. Registration alone is not enough: it guarantees
    // the frame is erased *before* a question renders, not that nothing paints
    // *over* it a moment later. Two painters would:
    //
    //   * the `newt-live-output-{gen}` worker, on the next tool chunk; and
    //   * `run_input_repaint`, because `watch_for_interrupt_fd` calls
    //     `refresh_geometry()` every 10 ms while a prompt owns stdin
    //     (lib.rs) — so a terminal RESIZE during a permission question
    //     repaints on top of it, with no tool call-ordering involved.
    //
    // Worse, `suspend_for_prompt`'s erase clears `painted_generation`, so a
    // paint that slipped through would skip the erase-previous branch below and
    // land at the cursor — i.e. directly under the question — and the following
    // `restore()` would rewind `MoveUp + Clear(FromCursorDown)` straight
    // through it. That is the 8x/second overwrite bug with a 4-row frame.
    //
    // Checked under the `output` lock that the whole paint holds, so a paint
    // that beat the flag is still undone by the erase that follows it.
    if output
        .registration
        .as_ref()
        .is_some_and(newt_core::tty::EphemeralRegistration::suspended)
    {
        return;
    }
    if is_abandoned(abandoned_through, generation) {
        discard_generation(&mut output, generation);
        return;
    }
    let snapshot = {
        let state = state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        (state.generation == Some(generation)).then(|| {
            (
                state.drawable.then(|| {
                    state
                        .view
                        .as_ref()
                        .map(|view| fixed_frame_lines(view, generation == COMPLETED_GENERATION))
                        .unwrap_or_default()
                }),
                state.color,
                state.columns,
                state.terminal_rows,
                state
                    .file_change
                    .as_ref()
                    .zip(state.view.as_ref())
                    .map(|(change, view)| fixed_file_change_styles(view, change)),
            )
        })
    };
    let Some((lines, color, columns, terminal_rows, styles)) = snapshot else {
        return;
    };
    if is_abandoned(abandoned_through, generation) {
        discard_generation(&mut output, generation);
        return;
    }

    // The frame plus the row the cursor parks on below it, so canonical
    // output after an abandon lands under the residue, never inside it.
    let height = u16::try_from(lines.as_ref().map_or(0, Vec::len)).unwrap_or(u16::MAX);
    let wanted = height.saturating_add(1);
    // Repaint IN PLACE when the frame is already up at this size and width:
    // every tool chunk comes through here, and a cursor query per chunk
    // would be a round trip per chunk. Anything else (first paint, a
    // resize, an expand, a frame left by another generation) erases what is
    // up and places afresh.
    let replacing =
        output.painted_generation == Some(generation) || output.placement_retry == Some(generation);
    let in_place = match (&output.frame, output.painted_generation) {
        (Some(frame), Some(previous)) => {
            previous == generation
                && !is_abandoned(abandoned_through, previous)
                && frame.place.height == wanted
                && frame.columns == columns
                && frame.terminal_rows == terminal_rows
        }
        _ => false,
    };
    if !in_place {
        if let Some(previous) = output.painted_generation {
            if is_abandoned(abandoned_through, previous) {
                discard_generation(&mut output, previous);
            } else {
                erase_output(
                    &mut output,
                    columns,
                    terminal_rows,
                    abandoned_through,
                    previous,
                );
            }
        }
    }
    let Some(lines) = lines else {
        return;
    };
    let (lease, place) = if in_place {
        let frame = output.frame.take().expect("checked above");
        (frame._lease, frame.place)
    } else {
        let Some(placed) = (output.placer)(wanted) else {
            // First placement still reports failure for the caller's plain
            // output fallback. Only an erased viewport owes a replacement.
            output.placement_retry = replacing.then_some(generation);
            return;
        };
        placed
    };
    // A partial transcript row can clamp the grant below the requested size.
    // Decline before scrolling or painting: the whole frame AND its blank
    // parking row must fit, including when canonical output follows abandon.
    if place.height < wanted {
        output.placement_retry = None;
        return;
    }

    // `painted_lines` is kept for the reflow erase; see `OutputState`.
    let mut batch = Vec::new();
    if !in_place && place.scroll > 0 {
        let _ = queue!(&mut batch, MoveTo(0, place.rows.saturating_sub(1)));
        for _ in 0..place.scroll {
            let _ = queue!(&mut batch, Print("\n"));
        }
    }
    if color {
        let _ = queue!(&mut batch, SetForegroundColor(Color::DarkGrey));
    }
    for (index, line) in lines.iter().enumerate() {
        let row = place
            .top
            .saturating_add(u16::try_from(index).unwrap_or(u16::MAX));
        let _ = queue!(&mut batch, MoveTo(0, row), Clear(ClearType::CurrentLine));
        if let Some(styled) = styles
            .as_ref()
            .filter(|_| color)
            .and_then(|rows| rows.get(index))
        {
            let _ = write_file_change_row(&mut batch, styled);
        } else {
            let _ = queue!(&mut batch, Print(line));
        }
    }
    if color {
        let _ = queue!(&mut batch, ResetColor);
    }
    // Park on the row under the frame, inside the placement.
    let _ = queue!(&mut batch, MoveTo(0, place.top.saturating_add(height)));
    let wrote = output
        .writer
        .write_batch(&batch, || !is_abandoned(abandoned_through, generation))
        .unwrap_or(false);
    if !wrote || is_abandoned(abandoned_through, generation) {
        discard_generation(&mut output, generation);
        return;
    }
    output.placement_retry = None;
    output.painted_lines.clone_from(&lines);
    output.painted_generation = Some(generation);
    output.frame = Some(Frame {
        _lease: lease,
        place,
        columns,
        terminal_rows,
    });
}

#[cfg(any(unix, test))]
fn run_input_repaint(
    state: &Mutex<RenderState>,
    output: &Mutex<OutputState>,
    abandoned_through: &AtomicU64,
    repaint_requested: &AtomicU64,
    repaint_running: &AtomicBool,
) {
    loop {
        let observed = repaint_requested.load(Ordering::Acquire);
        let generation = state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .generation;
        if let Some(generation) = generation {
            paint_generation(state, output, abandoned_through, generation);
        }
        if repaint_requested.load(Ordering::Acquire) != observed {
            continue;
        }

        repaint_running.store(false, Ordering::Release);
        if repaint_requested.load(Ordering::Acquire) == observed
            || repaint_running
                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                .is_err()
        {
            break;
        }
    }
}

#[allow(dead_code)]
fn erase_generation(
    output: &Mutex<OutputState>,
    abandoned_through: &AtomicU64,
    generation: u64,
    columns: usize,
    terminal_rows: usize,
) {
    let mut output = output
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if is_abandoned(abandoned_through, generation) {
        discard_generation(&mut output, generation);
        return;
    }
    if output.placement_retry == Some(generation) {
        output.placement_retry = None;
    }
    if output.painted_generation == Some(generation) {
        erase_output(
            &mut output,
            columns,
            terminal_rows,
            abandoned_through,
            generation,
        );
    }
}

/// Take the frame off the screen and put the cursor back where the
/// transcript ended.
///
/// At the screen size the frame was painted at, that is exactly the rows the
/// placement granted (`blank_rows`, never `ESC[J`, which would take whatever
/// holds the rows below) and a move to the placement's return point: the
/// arbiter's own release, on this writer. Height-only changes use bounded
/// cursor-relative line clears because the terminal may have scrolled. At any
/// other width the terminal
/// has reflowed the frame, its rows are no longer the granted ones, and the
/// cursor the terminal kept parked under the frame is the better guide:
/// rewind by the painted lines re-wrapped at the NEW width (the reflow rule
/// of the rich tier, #1426) and clear from there. The rows go back to the
/// arbiter either way, silently, when the frame drops.
#[allow(dead_code)]
fn erase_output(
    output: &mut OutputState,
    columns: usize,
    terminal_rows: usize,
    abandoned_through: &AtomicU64,
    generation: u64,
) {
    let Some(frame) = output.frame.take() else {
        output.painted_lines.clear();
        output.painted_generation = None;
        return;
    };
    if output.painted_lines.is_empty() {
        output.painted_generation = None;
        return;
    }
    let mut batch = Vec::new();
    if frame.columns == columns && frame.terminal_rows == terminal_rows {
        let _ = blank_rows(&mut batch, frame.place.top, frame.place.height);
        let (x, y) = frame.place.return_to;
        let _ = queue!(&mut batch, MoveTo(x, y));
    } else if frame.columns == columns {
        // Height-only resizing may scroll (or reveal scrollback). Absolute
        // rows are stale, but the cursor remains parked under the frame.
        // Clear only its surviving rows, then restore the transcript's
        // relative return point. No clear-to-screen-end on this path.
        let height = frame.place.height;
        let visible = height.min(u16::try_from(terminal_rows).unwrap_or(u16::MAX).max(1));
        if height > 1 {
            let _ = queue!(&mut batch, MoveUp(height - 1));
        }
        let _ = queue!(&mut batch, MoveToColumn(0));
        for row in 0..visible {
            let _ = queue!(&mut batch, Clear(ClearType::CurrentLine));
            if row + 1 < visible {
                let _ = queue!(&mut batch, MoveDown(1));
            }
        }
        let parked = frame.place.top.saturating_add(height.saturating_sub(1));
        let (x, y) = frame.place.return_to;
        if parked > y {
            let _ = queue!(&mut batch, MoveUp(parked - y));
        } else if y > parked {
            let _ = queue!(&mut batch, MoveDown(y - parked));
        }
        let _ = queue!(&mut batch, MoveToColumn(x));
    } else {
        let physical_rows = output
            .painted_lines
            .iter()
            .map(|line| physical_rows(line, columns))
            .sum::<usize>();
        let _ = queue!(
            &mut batch,
            MoveUp(u16::try_from(physical_rows).unwrap_or(u16::MAX)),
            MoveToColumn(0),
            Clear(ClearType::FromCursorDown)
        );
    }
    let _ = output
        .writer
        .write_batch(&batch, || !is_abandoned(abandoned_through, generation));
    output.painted_lines.clear();
    output.painted_generation = None;
}

/// Forget a frame without touching the terminal: its rows go back to the
/// arbiter and whatever is painted stays as residue.
fn discard_generation(output: &mut OutputState, generation: u64) {
    if output.placement_retry == Some(generation) {
        output.placement_retry = None;
    }
    if output.painted_generation == Some(generation) {
        output.painted_lines.clear();
        output.painted_generation = None;
        output.frame = None;
    }
}

fn is_abandoned(abandoned_through: &AtomicU64, generation: u64) -> bool {
    generation <= abandoned_through.load(Ordering::Acquire)
}

/// Terminal cells one character occupies. Combining marks attach to the
/// previous cell (0); ASCII and the frame's own glyph vocabulary are narrow;
/// everything else is assumed double-width.
fn char_cells(ch: char) -> usize {
    if matches!(
        ch,
        '\u{0300}'..='\u{036f}'
            | '\u{1ab0}'..='\u{1aff}'
            | '\u{1dc0}'..='\u{1dff}'
            | '\u{20d0}'..='\u{20ff}'
            | '\u{fe00}'..='\u{fe0f}'
            | '\u{fe20}'..='\u{fe2f}'
            | '\u{e0100}'..='\u{e01ef}'
    ) {
        0
    } else if ch.is_ascii() || matches!(ch, '…' | '▲' | '▼' | '▒' | '▓' | '⧉' | '▣' | '\u{fffd}')
    {
        1
    } else {
        2
    }
}

#[allow(dead_code)]
fn rendered_width(text: &str) -> usize {
    text.chars().map(char_cells).sum()
}

/// Physical rows one painted line occupies at `columns`, **by the terminal's
/// own wrapping rule**.
///
/// This replaced `width.div_ceil(columns)`, which is wrong for any line
/// carrying a double-width glyph: such a glyph cannot straddle the right
/// margin, so the terminal breaks the line EARLY and leaves a cell unused. The
/// arithmetic then under-counts, `MoveUp` lands inside the old frame, and the
/// rows above it are stranded forever — nothing else clears them, because the
/// erase discards its own bookkeeping unconditionally.
///
/// Found by the boundary legend: `⧉ Space to expand · ↑↓ scroll` is 32 cells
/// and reflows to FIVE rows at width 8, not the four `div_ceil` predicts,
/// because `↑` and `↓` each refuse to split. Two such lines in a frame stranded
/// exactly two rows. The previous legend was two cells shorter and happened to
/// wrap where the arithmetic agreed, so the defect sat behind a passing test.
fn physical_rows(text: &str, columns: usize) -> usize {
    let columns = columns.max(1);
    let mut rows = 1usize;
    let mut used = 0usize;
    for cells in text.chars().map(char_cells) {
        // A zero-width mark never forces a break; it rides the cell before it.
        // Nor does anything break an ALREADY-empty row: a glyph wider than the
        // whole terminal has nowhere further to go, and breaking before it
        // would count a row that never gets written.
        if cells > 0 && used > 0 && used + cells > columns {
            rows += 1;
            used = 0;
        }
        used += cells;
    }
    rows
}

// ========================================================================
// #1640: CompletedSpillRenderer implementation for Rich TUI completed spill
// ========================================================================

/// The generation completed viewports paint under. Live generations count up
/// from 1 and `abandon` only ever raises `abandoned_through` to a live number,
/// so `u64::MAX` can never satisfy `generation <= abandoned_through` — the
/// abandonment gate stays open for completed frames without any bypass. (The
/// prior sentinel, 0, sat BELOW the floor and was abandoned by definition:
/// every completed paint and scroll repaint silently no-opped.)
const COMPLETED_GENERATION: u64 = u64::MAX;

impl LiveSpillRenderer {
    /// Render a completed tool result as an interactive spill viewport.
    ///
    /// Reuses the live SpillView frame logic — scrolling, expanding, and
    /// editor-mode navigation all ride the existing `SpillInput` routing,
    /// because the completed view IS `state.view`. Bounded to max 50% of the
    /// terminal height so a single spill can't flood a tmux.
    fn show_completed(
        &self,
        output: &str,
        width: usize,
        max_height: usize,
        mut change: Option<RichFileChange>,
    ) -> usize {
        {
            let mut state = self.lock_state();
            // Never stomp a LIVE viewport: the live hand-off (`finish`) clears
            // `generation` before completed rendering may take the screen. A
            // previous COMPLETED frame is ours to replace.
            if state
                .generation
                .is_some_and(|generation| generation != COMPLETED_GENERATION)
            {
                return 0;
            }
            if !sync_geometry(&mut state) {
                return 0;
            }
            let mut view =
                SpillView::with_limits(state.columns, max_height.max(1), HISTORY_LINES, LINE_CHARS);
            let rich_text = change
                .as_mut()
                .map(|change| change.reproject(state.columns));
            view.push_stream_bytes(
                SpillStream::Stdout,
                rich_text.as_deref().unwrap_or(output).as_bytes(),
            );
            view.finish();
            // Bounded by the caller's budget AND 50% of the terminal height.
            let (_, terminal_rows) = (state.geometry)().unwrap_or((width, 24));
            let max_allowed = (terminal_rows / 2).max(3).min(state.max_rows.max(1));
            let rows_to_show = view
                .retained_line_count()
                .clamp(1, max_allowed.min(max_height.max(1)));
            view.resize(state.columns, rows_to_show, max_allowed);
            state.view = Some(view);
            state.file_change = change;
            state.generation = Some(COMPLETED_GENERATION);
        }
        paint_generation(
            &self.state,
            &self.output,
            &self.abandoned_through,
            COMPLETED_GENERATION,
        );

        // Physical rows painted, for the caller's cursor accounting.
        let columns = self.lock_state().columns.max(1);
        let output_state = self
            .output
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if output_state.painted_generation != Some(COMPLETED_GENERATION) {
            return 0;
        }
        output_state
            .painted_lines
            .iter()
            .map(|line| physical_rows(line, columns))
            .sum()
    }
}

impl CompletedSpillRenderer for LiveSpillRenderer {
    fn retain_completed(&self, output: &str) -> Option<u64> {
        self.completed_archive
            .as_ref()
            .map(|archive| archive.retain(output))
    }

    fn render_completed(&self, output: &str, width: usize, max_height: usize) -> usize {
        self.show_completed(output, width, max_height, None)
    }

    fn render_file_change(
        &self,
        raw_output: &str,
        output: &str,
        change: Arc<FileChangePresentation>,
        width: usize,
        max_height: usize,
    ) -> usize {
        let surroundings = self
            .lock_state()
            .color
            .then(|| change.surrounding_display_text(raw_output, output))
            .flatten();
        let Some((prefix, suffix)) = surroundings else {
            return self.render_completed(output, width, max_height);
        };
        self.show_completed(
            output,
            width,
            max_height,
            Some(RichFileChange {
                change,
                prefix,
                suffix,
                rows: Vec::new(),
            }),
        )
    }

    /// Whether a COMPLETED viewport is on screen. A live viewport does not
    /// count — its lifecycle belongs to `LiveToolOutput`, not to dismissal.
    fn is_active(&self) -> bool {
        self.lock_state().generation == Some(COMPLETED_GENERATION)
    }

    /// Drop the completed viewport's bookkeeping without terminal writes —
    /// the completed twin of live `abandon`. The painted frame (if any) stays
    /// as inert residue; what this guarantees is that no LATER erase can
    /// replay a stale rewind from a cursor that has since moved.
    fn discard(&self) {
        {
            let mut state = self.lock_state();
            if state.generation != Some(COMPLETED_GENERATION) {
                return;
            }
            state.view = None;
            state.file_change = None;
            state.generation = None;
        }
        let mut output = self
            .output
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        discard_generation(&mut output, COMPLETED_GENERATION);
    }

    /// Erase the completed viewport — a pure rewind, releasing the model
    /// state so the next `start`/`render_completed` begins clean. The
    /// committed excerpt above the frame is the durable record. No-op when
    /// no completed viewport is up (never touches a live generation).
    fn erase(&self) {
        let (columns, terminal_rows) = {
            let mut state = self.lock_state();
            if state.generation != Some(COMPLETED_GENERATION) {
                return;
            }
            // Re-sync so the rewind divides by the terminal's CURRENT width —
            // the same stale-width hazard `Ephemeral::erase` documents.
            let _ = sync_geometry(&mut state);
            state.view = None;
            state.file_change = None;
            state.generation = None;
            (state.columns, state.terminal_rows)
        };
        erase_generation(
            &self.output,
            &self.abandoned_through,
            COMPLETED_GENERATION,
            columns,
            terminal_rows,
        );
    }
}

#[cfg(test)]
#[path = "live_spill_tests.rs"]
mod tests;