nano-coder 0.29.2

A 6MB coding agent for the terminal and for agent fleets: multi-provider, ACP, resumable sessions, plans.
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
//! App-owned frame renderer (approach (a) from #46).
//!
//! Instead of writing output into the terminal's scrollback and pinning the
//! status bar with a scroll region, this renderer *owns* the screen: every
//! render turns the current state into a `Vec<String>` of lines at the current
//! width (the transcript, then the input editor, then the status bar as the
//! last line), diffs it against the previous frame and rewrites only what
//! changed. A width change clears the screen and scrollback and redraws every
//! line at the new width — this is what makes history "reflow" while keeping the
//! bar and editor stable, without relying on the terminal's own reflow.
//!
//! The "items → lines at a width" layer ([`Item`], [`render_item`],
//! [`transcript_lines`], [`editor_lines`], [`compose`]) is deliberately
//! independent of the screen mode, so an alternate-screen mode (approach (b))
//! could reuse it later. Only [`FrameRenderer`] knows about escape sequences.

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

use serde::{Deserialize, Serialize};
use unicode_width::UnicodeWidthChar;

use crate::plan::{Plan, Status};

/// Which renderer the interactive CLI drives.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RendererMode {
    /// The scroll-region renderer: the terminal owns scrollback and reflow.
    Legacy,
    /// The app-owned frame renderer: nano-coder re-renders on a width change.
    #[default]
    Frame,
}

impl RendererMode {
    pub const ALL: [RendererMode; 2] = [RendererMode::Legacy, RendererMode::Frame];

    pub fn describe(self) -> &'static str {
        match self {
            RendererMode::Legacy => "terminal owns scrollback and reflow (scroll region)",
            RendererMode::Frame => "app re-renders the frame on a width change",
        }
    }
}

impl std::fmt::Display for RendererMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            RendererMode::Legacy => "legacy",
            RendererMode::Frame => "frame",
        })
    }
}

impl std::str::FromStr for RendererMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        RendererMode::ALL
            .into_iter()
            .find(|m| m.to_string() == s.trim().to_lowercase())
            .ok_or_else(|| format!("unknown renderer {s:?} (legacy, frame)"))
    }
}

// Synchronized output: the terminal buffers everything between these and paints
// it in one go, so a half-drawn frame is never visible. Terminals that don't
// support the mode ignore it.
const SYNC_START: &str = "\x1b[?2026h";
const SYNC_END: &str = "\x1b[?2026l";

const DIM: &str = "\x1b[2m";
const BOLD: &str = "\x1b[1m";
const THINK: &str = "\x1b[38;5;245m";
const GREEN: &str = "\x1b[38;5;114m";
const RED: &str = "\x1b[38;5;203m";
const RESET: &str = "\x1b[0m";

/// Result-preview lines shown per tool result (matches the legacy renderer).
const PREVIEW_LINES: usize = 10;

// --- The transcript model: items → lines at a width -----------------------

/// Who produced a message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    User,
    Assistant,
}

/// One entry in the transcript. Rendering an item to lines is a pure function
/// of the item and the width, so a width change just re-renders every item.
#[derive(Debug, Clone)]
pub enum Item {
    /// A user or assistant message (plain text, wrapped to width).
    Message { role: Role, text: String },
    /// A finished reasoning block, shown collapsed as a one-line summary.
    Thinking { chars: usize, seconds: f64 },
    /// A tool invocation: the tool name and a one-line argument summary.
    ToolCall { name: String, summary: String },
    /// A tool result: its first line plus a "+N lines" count (or a preview
    /// when `verbose`).
    ToolResult { ok: bool, output: String, verbose: bool },
    /// The current plan checklist.
    Plan(Plan),
    /// A short diagnostic / lifecycle note.
    Note(String),
    /// Verbatim command / informational output (e.g. `/help`, `/context`),
    /// captured into the transcript so it can't corrupt the owned frame.
    Output(String),
    /// Verbatim machine-readable output (e.g. `/trajectory --json`), rendered
    /// byte-exact — no wrapping, sanitizing or width-fitting, which would
    /// corrupt JSON/Markdown. A raw export is printed once to scrollback and
    /// then kept here so the frame's restore redraw re-emits it instead of
    /// erasing it (a full redraw clears the screen and scrollback, so anything
    /// not in the frame is lost).
    Raw(String),
}

/// A transcript item paired with the timestamp prefix captured when it was
/// created (empty when timestamps are off). Pairing the stamp with the item —
/// rather than storing it per-variant — keeps every transcript item (messages,
/// tool calls, results, plans, thinking, notes, and command output) stamped
/// consistently, mirroring the legacy renderer's `ui::stamp_block`.
#[derive(Debug, Clone)]
pub struct StampedItem {
    pub stamp: String,
    pub item: Item,
}

/// Render one stamped transcript item: its content at the reduced width, with
/// the timestamp on the first row and continuation rows indented under it
/// (mirroring the legacy `ui::stamp_block`). Every assembled row is bounded to
/// `width` so an extremely narrow frame can't overflow and wrap natively. With
/// timestamps off the stamp is empty, so this collapses to plain `render_item`.
pub fn render_stamped(si: &StampedItem, width: usize) -> Vec<String> {
    let width = width.max(1);
    // Raw machine-readable output renders byte-exact: no stamp, no wrapping,
    // no width-fitting — any of those would corrupt JSON/Markdown. Lines wider
    // than the terminal wrap natively (the same bytes a plain `println!` would
    // produce), and `sanitize` inside `fit` would strip legitimate escape
    // sequences from the export, so this arm must bypass them both.
    if let Item::Raw(text) = &si.item {
        return text.split('\n').map(str::to_string).collect();
    }
    let stamp_w = visible_width(&si.stamp);
    let inner = width.saturating_sub(stamp_w).max(1);
    let pad = " ".repeat(stamp_w);
    render_item(&si.item, inner)
        .into_iter()
        .enumerate()
        .map(|(i, line)| {
            let row = if i == 0 { format!("{}{line}", si.stamp) } else { format!("{pad}{line}") };
            fit(&row, width)
        })
        .collect()
}

/// Render one transcript item's content to lines at `width` (without its
/// timestamp; see [`render_stamped`]).
pub fn render_item(item: &Item, width: usize) -> Vec<String> {
    let width = width.max(1);
    match item {
        Item::Message { role, text } => {
            let prefix = match role {
                Role::User => "› ",
                Role::Assistant => "",
            };
            // Reserve the `› ` marker column for the first line so no row
            // overflows `width`; continuation rows start at column 0.
            let inner = width.saturating_sub(prefix.chars().count()).max(1);
            let body = wrap_block(text, inner);
            body.into_iter()
                .enumerate()
                .map(
                    |(i, line)| {
                        if i == 0 && !prefix.is_empty() { format!("{DIM}{prefix}{RESET}{line}") } else { line }
                    },
                )
                .collect()
        }
        Item::Thinking { chars, seconds } => {
            vec![fit(&format!("{THINK}∴ Thought for {seconds:.1}s{RESET}{DIM} · {chars} chars{RESET}"), width)]
        }
        Item::ToolCall { name, summary } => {
            let used = name.chars().count() + 4;
            let summary = fit(summary, width.saturating_sub(used));
            vec![fit(&format!("{GREEN}●{RESET} {BOLD}{name}{RESET} {DIM}{summary}{RESET}"), width)]
        }
        Item::ToolResult { ok, output, verbose } => tool_result_lines(*ok, output, *verbose, width),
        Item::Plan(plan) => plan_lines(plan, width),
        Item::Note(text) => wrap_block(text, width).into_iter().map(|line| format!("{DIM}{line}{RESET}")).collect(),
        Item::Output(text) => wrap_block(text, width),
        // Normally rendered by the dedicated arm in `render_stamped` (which
        // also skips the timestamp); this keeps a direct `render_item` call
        // byte-exact too.
        Item::Raw(text) => text.split('\n').map(str::to_string).collect(),
    }
}

fn tool_result_lines(ok: bool, output: &str, verbose: bool, width: usize) -> Vec<String> {
    let lines: Vec<&str> = output.trim_end().lines().collect();
    let (mark, color) = if ok { ("⎿", DIM) } else { ("⎿ error:", RED) };
    // The prefix is two leading spaces, the marker, and one space; reserve its
    // real width so the longer `⎿ error:` marker can't overflow `width` and
    // wrap onto extra rows. Both result formats below use the same `body`.
    let body = width.saturating_sub(mark.chars().count() + 3).max(1);
    if lines.is_empty() {
        return vec![fit(&format!("  {color}{mark} (no output){RESET}"), width)];
    }
    if verbose {
        let mut out = Vec::new();
        for (i, line) in lines.iter().take(PREVIEW_LINES).enumerate() {
            let lead = if i == 0 { mark } else { " " };
            out.push(fit(&format!("  {color}{lead} {}{RESET}", fit(line, body)), width));
        }
        if lines.len() > PREVIEW_LINES {
            out.push(fit(&format!("  {DIM}  … +{} lines{RESET}", lines.len() - PREVIEW_LINES), width));
        }
        return out;
    }
    let more = if lines.len() > 1 { format!(" (+{} lines)", lines.len() - 1) } else { String::new() };
    vec![fit(&format!("  {color}{mark} {}{more}{RESET}", fit(lines[0], body.saturating_sub(more.len()))), width)]
}

/// Plans longer than this show finished items as one summary line.
const PLAN_LINES: usize = 12;

fn plan_lines(plan: &Plan, width: usize) -> Vec<String> {
    let body = width.saturating_sub(4).max(1);
    let (done, total) = plan.progress();
    let mut out = vec![fit(&format!("{GREEN}●{RESET} {BOLD}Plan{RESET} {DIM}{done}/{total} done{RESET}"), width)];
    let live: Vec<&crate::plan::PlanItem> = plan.items.iter().filter(|i| i.status != Status::Dropped).collect();
    let collapse = live.len() > PLAN_LINES && done > 0;
    if collapse {
        out.push(fit(&format!("  {GREEN}✔{RESET} {DIM}{done} done{RESET}"), width));
    }
    let visible: Vec<&&crate::plan::PlanItem> =
        live.iter().filter(|i| !(collapse && i.status == Status::Done)).collect();
    for (shown, item) in visible.iter().enumerate() {
        if shown == PLAN_LINES {
            out.push(fit(&format!("  {DIM}… +{} more{RESET}", visible.len() - shown), width));
            break;
        }
        let title = fit(&item.title, body);
        let line = match item.status {
            Status::Done => format!("{GREEN}✔{RESET} {DIM}{title}{RESET}"),
            Status::InProgress => format!("{BOLD}◼ {title}{RESET}"),
            Status::Blocked => format!("{RED}! {title}{RESET}"),
            _ => format!("{DIM}☐{RESET} {title}"),
        };
        out.push(format!("  {line}"));
    }
    out
}

/// Every transcript item's lines, in order, at `width`.
pub fn transcript_lines(items: &[StampedItem], width: usize) -> Vec<String> {
    items.iter().flat_map(|item| render_stamped(item, width)).collect()
}

/// The input editor as wrapped lines with a reverse-video cursor marker at
/// `cursor` (a character index into `text`). Newlines in `text` become their
/// own wrapped rows.
pub fn editor_lines(prompt: &str, text: &str, cursor: usize, width: usize) -> Vec<String> {
    let width = width.max(1);
    let cursor = cursor.min(text.chars().count());
    // Mark the cursor with a sentinel that survives wrapping, then swap it for a
    // reverse-video block once the lines are laid out. `cell_width` reserves one
    // cell for it so a full row leaves room for the block.
    const MARK: char = CURSOR_MARK;
    let mut marked = String::new();
    for (i, c) in text.chars().enumerate() {
        if i == cursor {
            marked.push(MARK);
        }
        marked.push(c);
    }
    if cursor >= text.chars().count() {
        marked.push(MARK);
    }
    // The prompt may carry a timestamp with ANSI colour codes, so reserve its
    // on-screen width by visible cells rather than raw `char` count.
    let inner = width.saturating_sub(visible_width(prompt)).max(1);
    let mut lines: Vec<String> = Vec::new();
    for (i, logical) in marked.split('\n').enumerate() {
        let wrapped = if i == 0 { wrap_ansi(logical, inner) } else { wrap_ansi(logical, width) };
        for line in wrapped {
            lines.push(line);
        }
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines[0] = format!("{BOLD}{prompt}{RESET}{}", lines[0]);
    lines
        .into_iter()
        // The prompt (which may carry a timestamp) is prepended after wrapping,
        // so bound every assembled row to `width`: when the terminal is narrower
        // than the prompt, the row would otherwise native-wrap and push the
        // status bar off the last line. `fit` counts the cursor sentinel as one
        // cell, so this preserves it whenever it fits.
        .map(|line| fit(&line, width).replace(MARK, "\x1b[7m \x1b[27m"))
        .collect()
}

/// Compose the whole frame: the transcript, then the editor, then the status
/// bar as the **last** line. The bar isn't absolutely positioned and there is
/// no scroll region — it is simply the final line of the frame.
pub fn compose(transcript: &[String], editor: &[String], status: &str) -> Vec<String> {
    let mut frame = Vec::with_capacity(transcript.len() + editor.len() + 1);
    frame.extend(transcript.iter().cloned());
    frame.extend(editor.iter().cloned());
    frame.push(status.to_string());
    frame
}

/// The dim queue indicator row shown under the editor in frame mode, mirroring
/// the legacy status line's `⏸N queued · /queue to edit` hint. Returns `None`
/// when nothing is queued.
pub fn queue_indicator(queued: usize, width: usize) -> Option<String> {
    (queued > 0).then(|| fit(&format!("{DIM}⏸{queued} queued · /queue to edit{RESET}"), width.max(1)))
}

/// A transient hint rendered in place of the status bar (e.g. "(Ctrl-C again
/// to exit)"), so cursor-relevant feedback is seen where the cursor is rather
/// than as a transcript row that triggers a full-screen clear. Plain dim text,
/// bounded to `width`.
pub fn transient_status(text: &str, width: usize) -> String {
    fit(&format!("{DIM}{text}{RESET}"), width.max(1))
}

/// The index of the first line that differs between two frames, or `None` when
/// they are identical. A shorter/longer frame differs at its first extra or
/// missing line.
pub fn first_diff(prev: &[String], next: &[String]) -> Option<usize> {
    let common = prev.len().min(next.len());
    for i in 0..common {
        if prev[i] != next[i] {
            return Some(i);
        }
    }
    (prev.len() != next.len()).then_some(common)
}

// --- Width-aware wrapping --------------------------------------------------

/// The zero-width sentinel `editor_lines` injects at the cursor position; it is
/// swapped for a one-cell reverse-video block after wrapping.
const CURSOR_MARK: char = '\u{0}';

/// A single character's terminal-cell width, treating the editor cursor
/// sentinel as one cell. `CURSOR_MARK` is a control character (nominally zero
/// width) but is replaced by a one-cell reverse-video block after layout, so
/// reserving a cell for it here keeps a full editor row from spilling past the
/// frame width and pushing the status bar down.
fn cell_width(c: char) -> usize {
    if c == CURSOR_MARK { 1 } else { UnicodeWidthChar::width(c).unwrap_or(0) }
}

/// Visible width in terminal cells, ignoring ANSI escape sequences. CJK
/// characters and many emoji occupy two columns and combining marks zero, so
/// this uses Unicode cell width rather than a raw scalar-value count.
fn visible_width(text: &str) -> usize {
    let mut count = 0;
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            if chars.peek() == Some(&'[') {
                chars.next();
                for n in chars.by_ref() {
                    if ('@'..='~').contains(&n) {
                        break;
                    }
                }
            }
            continue;
        }
        count += cell_width(c);
    }
    count
}

/// Truncate a (possibly ANSI-coloured) string to `width` terminal cells,
/// appending an ellipsis and a reset when it overflows.
/// [`fit`] for callers outside the frame layer (e.g. the command menu rows).
pub fn fit_line(text: &str, width: usize) -> String {
    fit(text, width)
}

fn fit(text: &str, width: usize) -> String {
    let expanded = sanitize(text);
    let text = expanded.as_str();
    if visible_width(text) <= width {
        return text.to_string();
    }
    let keep = width.saturating_sub(1);
    let mut out = String::new();
    let mut seen = 0;
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            out.push(c);
            if chars.peek() == Some(&'[') {
                out.push(chars.next().unwrap());
                while let Some(&n) = chars.peek() {
                    out.push(chars.next().unwrap());
                    if ('@'..='~').contains(&n) {
                        break;
                    }
                }
            }
            continue;
        }
        let w = cell_width(c);
        if seen + w > keep {
            break;
        }
        out.push(c);
        seen += w;
    }
    out.push('…');
    out.push_str(RESET);
    out
}

/// Wrap plain (uncoloured) text to `width`, splitting on whitespace and hard
/// breaking words longer than the width. Existing newlines start new lines.
fn wrap_block(text: &str, width: usize) -> Vec<String> {
    text.split('\n').flat_map(|line| wrap_ansi(line, width)).collect()
}

/// Prepare a logical line for width-accurate, layout-safe composition: expand
/// tabs to 8-column stops and strip terminal controls that could escape the
/// frame. A literal `\t` has no `UnicodeWidthChar` width but the terminal
/// advances it to the next tab stop, so leaving tabs in place lets tool output,
/// model text, or pasted input emit rows wider than `width`. More dangerously,
/// content can carry cursor-movement / erase CSI sequences, OSC strings, or
/// stray C0 controls (carriage returns, backspaces, …) that move the cursor or
/// clear content *outside* the intended row. Only SGR styling — a CSI sequence
/// ending in `m` — is preserved; every other escape and control character is
/// dropped so it can't violate the frame layout. The editor cursor sentinel
/// (`CURSOR_MARK`) is kept (it is swapped for a reverse-video block after
/// layout).
fn sanitize(line: &str) -> String {
    const TAB: usize = 8;
    let mut out = String::new();
    let mut col = 0usize;
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Collect a CSI sequence and keep it only when it is SGR styling;
            // cursor-movement / erase CSI, OSC, and other escapes are dropped.
            if chars.peek() == Some(&'[') {
                let mut seq = String::from(c);
                seq.push(chars.next().unwrap()); // '['
                let mut final_byte = None;
                while let Some(&n) = chars.peek() {
                    seq.push(chars.next().unwrap());
                    if ('@'..='~').contains(&n) {
                        final_byte = Some(n);
                        break;
                    }
                }
                if final_byte == Some('m') {
                    out.push_str(&seq);
                }
            }
            // A bare ESC or non-CSI escape is dropped; any trailing bytes are
            // handled as ordinary characters on the next iterations.
            continue;
        }
        if c == '\t' {
            let spaces = TAB - (col % TAB);
            for _ in 0..spaces {
                out.push(' ');
            }
            col += spaces;
            continue;
        }
        if c == CURSOR_MARK {
            out.push(c);
            col += 1;
            continue;
        }
        // Other C0/DEL/C1 controls have no cell width but move the cursor or
        // erase, so they'd break the frame's exact column accounting: drop them.
        if c.is_control() {
            continue;
        }
        out.push(c);
        col += cell_width(c);
    }
    out
}

/// Wrap one logical line to `width` visible columns, preserving ANSI escape
/// sequences (they take no columns) and breaking on spaces where possible.
fn wrap_ansi(line: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let line = sanitize(line);
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut vis = 0usize;
    // Byte offset in `cur` just after the most recent space, and the visible
    // width at that point — the preferred break for an overlong word.
    let mut brk: Option<usize> = None;
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            cur.push(c);
            if chars.peek() == Some(&'[') {
                cur.push(chars.next().unwrap());
                while let Some(&n) = chars.peek() {
                    cur.push(chars.next().unwrap());
                    if ('@'..='~').contains(&n) {
                        break;
                    }
                }
            }
            continue;
        }
        if c == ' ' {
            if vis >= width {
                // The line is full: end it here and drop the space.
                out.push(cur.trim_end().to_string());
                cur = String::new();
                vis = 0;
                brk = None;
                continue;
            }
            cur.push(' ');
            vis += 1;
            brk = Some(cur.len());
            continue;
        }
        if vis >= width {
            match brk {
                Some(byte) => {
                    let rest = cur.split_off(byte);
                    out.push(std::mem::take(&mut cur).trim_end().to_string());
                    cur = rest.trim_start_matches(' ').to_string();
                    vis = visible_width(&cur);
                }
                None => {
                    out.push(std::mem::take(&mut cur));
                    vis = 0;
                }
            }
            brk = None;
        }
        let w = cell_width(c);
        // A wide (2-cell) glyph that would spill past `width` starts a new row
        // even when the running width has not yet reached `width`.
        if w > 1 && vis + w > width && !cur.is_empty() {
            match brk {
                Some(byte) => {
                    let rest = cur.split_off(byte);
                    out.push(std::mem::take(&mut cur).trim_end().to_string());
                    cur = rest.trim_start_matches(' ').to_string();
                    vis = visible_width(&cur);
                }
                None => {
                    out.push(std::mem::take(&mut cur));
                    vis = 0;
                }
            }
            brk = None;
        }
        cur.push(c);
        vis += w;
    }
    out.push(cur);
    out
}

// --- The single writer -----------------------------------------------------

/// Owns the terminal and renders frames, diffing against the previous one. On a
/// width or height change it clears and redraws every line at the new size;
/// otherwise it rewrites only from the first changed line to the end. Every
/// write is wrapped in synchronized output.
pub struct FrameRenderer<W: Write> {
    out: W,
    prev: Vec<String>,
    width: usize,
    height: usize,
    started: bool,
}

impl<W: Write> FrameRenderer<W> {
    pub fn new(out: W) -> Self {
        Self { out, prev: Vec::new(), width: 0, height: 0, started: false }
    }

    /// Force the next [`render`](Self::render) to be a full redraw — used after
    /// a foreground picker (dialoguer) has written over the screen.
    pub fn invalidate(&mut self) {
        self.started = false;
    }

    /// Render `frame` (already composed to lines at `width`) at a terminal of
    /// `width` × `height`.
    pub fn render(&mut self, frame: &[String], width: usize, height: usize) -> std::io::Result<()> {
        let width = width.max(1);
        let height = height.max(1);
        if !self.started || width != self.width || height != self.height {
            // First frame, or a width/height change: re-emit every line at the
            // new size. A full redraw always clears scrollback — the frame holds
            // the entire transcript, so anything already in scrollback is a copy
            // of what is about to be written; keeping it would leave a duplicate
            // (stale) frame behind the fresh one.
            self.full_redraw(frame, width, height)?;
        } else {
            self.differential(frame, width, height)?;
        }
        self.prev = frame.to_vec();
        self.width = width;
        self.height = height;
        self.started = true;
        Ok(())
    }

    fn full_redraw(&mut self, frame: &[String], width: usize, height: usize) -> std::io::Result<()> {
        let mut buf = String::from(SYNC_START);
        // Drop any scroll region a prior renderer (e.g. `StatusLine::install`,
        // which pins DECSTBM to rows 1..rows-1) left set: this renderer owns
        // the whole screen, so `CRLF` scrolling must span every row or the
        // bottom status line can be pushed out of place.
        buf.push_str("\x1b[r");
        // Clear the screen AND scrollback: a full redraw re-emits the whole
        // transcript, so any surplus that scrolls off must not sit behind a
        // stale copy of the previous frame.
        buf.push_str("\x1b[H\x1b[2J\x1b[3J");
        // Bottom-anchor: when the frame is shorter than the screen, leave blank
        // rows at the top so the bar lands on the last row; when it is taller,
        // write from the top and let the surplus scroll into scrollback. Count
        // PHYSICAL rows, not logical lines: a raw export line wider than the
        // terminal wraps natively onto extra rows, and only the physical total
        // places the first line on the right row.
        let physical = physical_rows(frame, width);
        let start_row = if physical < height { height - physical + 1 } else { 1 };
        buf.push_str(&format!("\x1b[{start_row};1H"));
        for (i, line) in frame.iter().enumerate() {
            if i > 0 {
                buf.push_str("\r\n");
            }
            buf.push_str(line);
        }
        buf.push_str(SYNC_END);
        self.out.write_all(buf.as_bytes())?;
        self.out.flush()
    }

    fn differential(&mut self, frame: &[String], width: usize, height: usize) -> std::io::Result<()> {
        let Some(diff) = first_diff(&self.prev, frame) else {
            return Ok(());
        };
        let plen = self.prev.len();
        // Row addressing must count PHYSICAL rows: a raw export line wider than
        // the terminal wraps natively onto extra rows, so a logical line index
        // is not a screen row. Compare physical totals to decide the fallback
        // and to locate the first on-screen row.
        let prev_physical = physical_rows(&self.prev, width);
        let new_physical = physical_rows(frame, width);
        // The first on-screen logical line index of the previous frame;
        // anything before it has scrolled into scrollback and can't be
        // rewritten in place.
        let prev_top = plen.saturating_sub(height);
        if prev_physical != new_physical || diff < prev_top {
            // Physical row count changed, or the change is already in
            // scrollback: fall back to a full redraw. It clears scrollback so
            // re-emitting the whole transcript can't stack a duplicate copy
            // behind the frame.
            return self.full_redraw(frame, width, height);
        }
        // The screen row of the changed line is its cumulative physical offset
        // within the frame, anchored against the bottom (the status bar is the
        // last physical row).
        let before: usize = frame[..diff].iter().map(|l| line_physical_rows(l, width)).sum();
        let row = if new_physical <= height {
            (height - new_physical) + before + 1
        } else {
            before - (new_physical - height) + 1
        };
        let mut buf = String::from(SYNC_START);
        buf.push_str(&format!("\x1b[{row};1H"));
        for (i, line) in frame[diff..].iter().enumerate() {
            if i > 0 {
                buf.push_str("\r\n");
            }
            buf.push_str("\x1b[2K");
            buf.push_str(line);
        }
        buf.push_str(SYNC_END);
        self.out.write_all(buf.as_bytes())?;
        self.out.flush()
    }
}

/// The number of physical terminal rows a single composed line occupies once
/// written: a line wider than `width` wraps natively onto extra rows (an empty
/// line still takes one). ANSI escape sequences are ignored, so this measures
/// what the terminal actually advances, not the byte length.
///
/// Terminal wrapping is sequence-sensitive, not just `ceil(width / width)`: a
/// wide (2-cell) glyph cannot start in the last column, so it moves wholly to
/// the next row and leaves that cell blank. Count cells incrementally and start
/// a new row whenever the next glyph would cross the column boundary, as
/// [`wrap_ansi`] does — `ceil(total_width / width)` undercounts CJK/emoji lines.
fn line_physical_rows(line: &str, width: usize) -> usize {
    let width = width.max(1);
    let mut rows = 1usize;
    let mut col = 0usize;
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Skip a CSI escape sequence (`\x1b[...<final>`); it advances no cell.
            if chars.peek() == Some(&'[') {
                chars.next();
                for n in chars.by_ref() {
                    if ('@'..='~').contains(&n) {
                        break;
                    }
                }
            }
            continue;
        }
        let w = cell_width(c);
        if w == 0 {
            continue;
        }
        // A wide glyph that would cross the boundary starts a new row — but not
        // on an empty row (a glyph wider than `width` still occupies one row
        // rather than wrapping forever).
        if col + w > width && col > 0 {
            rows += 1;
            col = 0;
        }
        col += w;
    }
    rows
}

/// The total physical terminal rows a composed frame occupies: the sum over
/// every line of its wrapped height. Cursor addressing must use this count —
/// logical line indices undercount whenever a raw export line wraps past the
/// terminal width.
fn physical_rows(frame: &[String], width: usize) -> usize {
    frame.iter().map(|l| line_physical_rows(l, width)).sum()
}

// --- Resize debounce -------------------------------------------------------

/// Collapses a burst of resize events (a window drag) into a single render at
/// the final size: after the last event, wait for `quiet` of no further events
/// before rendering.
pub struct Debouncer {
    last: Option<Instant>,
    quiet: Duration,
}

impl Debouncer {
    pub fn new(quiet: Duration) -> Self {
        Self { last: None, quiet }
    }

    /// Record that a resize happened at `now`.
    pub fn record(&mut self, now: Instant) {
        self.last = Some(now);
    }

    /// Whether enough quiet time has passed since the last resize to render.
    pub fn ready(&self, now: Instant) -> bool {
        self.last.is_none_or(|last| now.duration_since(last) >= self.quiet)
    }

    /// Consume the pending resize once rendered.
    pub fn clear(&mut self) {
        self.last = None;
    }

    /// Whether a resize is waiting to be rendered.
    pub fn pending(&self) -> bool {
        self.last.is_some()
    }
}

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

    fn strip(text: &str) -> String {
        let mut out = String::new();
        let mut chars = text.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\x1b' {
                if chars.peek() == Some(&'[') {
                    chars.next();
                    for n in chars.by_ref() {
                        if ('@'..='~').contains(&n) {
                            break;
                        }
                    }
                }
                continue;
            }
            out.push(c);
        }
        out
    }

    #[test]
    fn parses_and_displays_renderer_mode() {
        assert_eq!("frame".parse::<RendererMode>(), Ok(RendererMode::Frame));
        assert_eq!("Legacy".parse::<RendererMode>(), Ok(RendererMode::Legacy));
        assert!("fancy".parse::<RendererMode>().is_err());
        assert_eq!(RendererMode::default(), RendererMode::Frame);
        assert_eq!(RendererMode::Frame.to_string(), "frame");
    }

    #[test]
    fn wraps_words_at_the_width() {
        assert_eq!(wrap_ansi("the quick brown fox", 9), vec!["the quick", "brown fox"]);
        // A word longer than the width is hard-broken.
        assert_eq!(wrap_ansi("abcdefghij", 4), vec!["abcd", "efgh", "ij"]);
        // Every wrapped line stays within the width.
        for line in wrap_ansi("one two three four five six seven", 7) {
            assert!(visible_width(&line) <= 7, "{line:?}");
        }
    }

    #[test]
    fn width_counts_terminal_cells_not_scalars() {
        // CJK glyphs take two cells; combining marks take none.
        assert_eq!(visible_width("你好"), 4);
        assert_eq!(visible_width("e\u{0301}"), 1);
        // Wrapping a run of wide glyphs never overflows the column budget.
        for line in wrap_ansi("你好世界你好世界", 5) {
            assert!(visible_width(&line) <= 5, "{line:?}");
        }
        // `fit` truncates on cells, so a wide-glyph string can't exceed width.
        assert!(visible_width(&fit("你好世界", 5)) <= 5);
    }

    #[test]
    fn cursor_marker_reserves_a_cell_on_a_full_row() {
        // A line exactly filling the inner width with the cursor mid-row: the
        // sentinel is replaced by a one-cell reverse-video block, so the row
        // must be laid out reserving a cell for it and never exceed the width.
        let width = 12;
        let text: String = "abcdefghijklmnopqrstuvwxyz".chars().take(40).collect();
        for cursor in 0..text.chars().count() {
            for line in editor_lines("› ", &text, cursor, width) {
                assert!(
                    visible_width(&line) <= width,
                    "row overflows at cursor {cursor}: {line:?} (w={})",
                    visible_width(&line)
                );
            }
        }
    }

    #[test]
    fn tabs_are_expanded_so_rows_never_overflow_the_width() {
        // A literal tab has no `UnicodeWidthChar` width but the terminal
        // advances it to the next tab stop; leaving it in would let a row emit
        // wider than `width` and wrap natively. Expanded content must never
        // exceed the width and must contain no tabs.
        let text = "a\tb\tcategory\tvalue\tand some more trailing words here";
        for width in 3..40 {
            for line in wrap_ansi(text, width) {
                assert!(
                    visible_width(&line) <= width,
                    "row overflows at width {width}: {line:?} (w={})",
                    visible_width(&line)
                );
                assert!(!line.contains('\t'), "tab survived layout: {line:?}");
            }
        }
        // Tabs advance to 8-column stops from the current column.
        assert_eq!(sanitize("a\tb"), "a       b");
        assert_eq!(sanitize("\tx"), "        x");
        assert_eq!(sanitize("no tabs"), "no tabs");
    }

    #[test]
    fn unsafe_terminal_controls_are_stripped_from_layout() {
        // SGR styling is preserved, but cursor-movement / erase CSI sequences,
        // OSC strings, and stray C0 controls (carriage returns, backspaces) are
        // dropped so content can't move the cursor or clear rows outside itself.
        assert_eq!(sanitize("\x1b[31mred\x1b[0m"), "\x1b[31mred\x1b[0m");
        assert_eq!(sanitize("a\x1b[2Jb"), "ab"); // erase screen dropped
        assert_eq!(sanitize("a\x1b[Hb"), "ab"); // cursor home dropped
        assert_eq!(sanitize("a\rb"), "ab"); // carriage return dropped
        assert_eq!(sanitize("a\x08b"), "ab"); // backspace dropped
        assert_eq!(sanitize("a\x07b"), "ab"); // BEL dropped
        // A malicious control sequence can't survive into a laid-out row.
        for line in wrap_ansi("evil\x1b[2K\x1b[1;1Hclear", 40) {
            assert!(!line.contains('\x1b') || !line.contains('H'));
            assert!(!line.contains('\x1b') || !line.contains('K'));
            assert!(!line.contains('\r'));
        }
    }

    #[test]
    fn message_stamp_is_shown_and_rows_stay_within_width() {
        // A stamped message renders the timestamp on the first line, keeps every
        // row within the width, and indents continuation rows under the stamp.
        let stamp = format!("{DIM}12:34:56{RESET} ");
        let item = StampedItem {
            stamp: stamp.clone(),
            item: Item::Message {
                role: Role::User,
                text: "a fairly long user question that wraps onto several rows".into(),
            },
        };
        for width in 4..40 {
            let lines = render_stamped(&item, width);
            for line in &lines {
                assert!(
                    visible_width(line) <= width,
                    "row overflows at width {width}: {line:?} (w={})",
                    visible_width(line)
                );
            }
        }
        let lines = render_stamped(&item, 30);
        assert!(strip(&lines[0]).starts_with("12:34:56 › "), "{:?}", lines[0]);
        // With timestamps off (empty stamp) the first row keeps the bare marker.
        let bare = StampedItem { stamp: String::new(), item: Item::Message { role: Role::User, text: "hi".into() } };
        assert_eq!(strip(&render_stamped(&bare, 30)[0]), "› hi");
    }

    #[test]
    fn plan_header_is_bounded_to_the_width() {
        let plan = Plan::default();
        // Even at a pathologically narrow width the header row never exceeds it,
        // so native terminal wrapping can't push the editor/status rows down.
        for width in 3..20 {
            for line in plan_lines(&plan, width) {
                assert!(visible_width(&line) <= width, "row overflows at {width}: {line:?}");
            }
        }
    }

    #[test]
    fn tool_result_count_rows_are_bounded_to_the_width() {
        // A tool result whose count/summary row ("… +N lines" / "(+N lines)")
        // could itself exceed a narrow frame and wrap, pushing later rows down.
        let output = (0..40).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
        for width in 3..24 {
            for verbose in [false, true] {
                for line in tool_result_lines(true, &output, verbose, width) {
                    assert!(visible_width(&line) <= width, "row overflows at {width}: {line:?}");
                }
            }
        }
    }

    #[test]
    fn queue_indicator_shows_only_when_queued() {
        assert_eq!(queue_indicator(0, 40), None);
        let line = queue_indicator(2, 40).unwrap();
        assert!(strip(&line).contains("⏸2 queued · /queue to edit"), "{line:?}");
        // The indicator is fit to the width like every other frame row.
        assert!(visible_width(&queue_indicator(3, 6).unwrap()) <= 6);
    }

    #[test]
    fn wrapping_preserves_ansi_but_not_its_width() {
        let coloured = format!("{GREEN}hello world again{RESET}");
        let lines = wrap_ansi(&coloured, 11);
        assert_eq!(lines.iter().map(|l| strip(l)).collect::<Vec<_>>(), vec!["hello world", "again"]);
        // The colour codes survived even though they cost no columns.
        assert!(lines[0].contains(GREEN));
    }

    #[test]
    fn composes_transcript_editor_then_status_last() {
        let transcript = vec!["a".to_string(), "b".to_string()];
        let editor = vec!["› hi".to_string()];
        let frame = compose(&transcript, &editor, "STATUS");
        assert_eq!(frame, vec!["a", "b", "› hi", "STATUS"]);
        assert_eq!(frame.last().unwrap(), "STATUS", "the bar must be the last line");
    }

    #[test]
    fn diffs_frames_line_by_line() {
        let a = vec!["one".into(), "two".into(), "three".into()];
        let b = vec!["one".into(), "TWO".into(), "three".into()];
        assert_eq!(first_diff(&a, &b), Some(1));
        assert_eq!(first_diff(&a, &a), None);
        // A grown frame differs at the first extra line.
        let c = vec!["one".into(), "two".into(), "three".into(), "four".into()];
        assert_eq!(first_diff(&a, &c), Some(3));
    }

    #[test]
    fn raw_items_render_byte_exact() {
        // A raw export must survive the frame verbatim: no timestamp prefix,
        // no wrapping, no width-fitting, no sanitizing — any of those would
        // corrupt JSON/Markdown.
        let json = "{\n  \"session_id\": \"s\",\n  \"long\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n}";
        let items = vec![StampedItem { stamp: format!("{DIM}12:34:56{RESET} "), item: Item::Raw(json.to_string()) }];
        let lines = transcript_lines(&items, 20);
        assert_eq!(lines, json.split('\n').collect::<Vec<_>>(), "raw lines must be byte-exact");
        // `render_item` direct agrees (no stamp path).
        assert_eq!(render_item(&Item::Raw(json.to_string()), 20), lines);
    }

    #[test]
    fn renders_items_within_the_width() {
        let items = vec![
            StampedItem {
                stamp: format!("{DIM}12:34:56{RESET} "),
                item: Item::Message {
                    role: Role::Assistant,
                    text: "a fairly long assistant answer that should wrap".into(),
                },
            },
            StampedItem {
                stamp: format!("{DIM}12:34:56{RESET} "),
                item: Item::ToolCall {
                    name: "bash".into(),
                    summary: "ls -la /some/very/long/path/that/overflows".into(),
                },
            },
            StampedItem {
                stamp: format!("{DIM}12:34:56{RESET} "),
                item: Item::ToolResult { ok: true, output: "line1\nline2\nline3".into(), verbose: false },
            },
            StampedItem {
                stamp: String::new(),
                item: Item::Note("a note that is also rather long and needs wrapping".into()),
            },
        ];
        for line in transcript_lines(&items, 20) {
            assert!(visible_width(&line) <= 20, "{line:?} ({} cols)", visible_width(&line));
        }
        // The single-line tool result summarises the extra lines.
        let result = render_item(&Item::ToolResult { ok: true, output: "a\nb\nc".into(), verbose: false }, 40);
        assert_eq!(result.len(), 1);
        assert!(strip(&result[0]).contains("(+2 lines)"));
    }

    #[test]
    fn editor_marks_the_cursor_and_wraps() {
        let lines = editor_lines("› ", "hello", 5, 20);
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("\x1b[7m"), "cursor marker present");
        // A long line wraps under the width.
        let long = editor_lines("› ", &"x".repeat(50), 50, 10);
        assert!(long.len() > 1);
        for line in &long {
            assert!(visible_width(line) <= 10, "{line:?}");
        }
    }

    #[test]
    fn plan_item_wraps_and_marks_status() {
        let plan = Plan {
            goal: String::new(),
            items: vec![
                PlanItem {
                    id: 1,
                    title: "do the first thing".into(),
                    status: Status::Done,
                    notes: vec![],
                    after: vec![],
                },
                PlanItem {
                    id: 2,
                    title: "do the second thing".into(),
                    status: Status::InProgress,
                    notes: vec![],
                    after: vec![],
                },
            ],
        };
        let lines = plan_lines(&plan, 30);
        assert!(strip(&lines[0]).contains("1/2 done"));
        assert!(lines.len() >= 3);
    }

    #[test]
    fn debouncer_waits_for_quiet() {
        let mut d = Debouncer::new(Duration::from_millis(40));
        let t0 = Instant::now();
        d.record(t0);
        assert!(d.pending());
        assert!(!d.ready(t0 + Duration::from_millis(10)));
        assert!(d.ready(t0 + Duration::from_millis(40)));
        d.clear();
        assert!(!d.pending());
        assert!(d.ready(t0));
    }
}

/// Emulator tests: feed the renderer's bytes to a `vt100` terminal, resize it
/// and assert the whole screen — the bar is on the last row, the editor sits
/// directly above it, there are no duplicate bars, and history reflows to the
/// new width.
#[cfg(test)]
mod emulator {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;

    /// A `Write` that appends to a shared buffer, so a test can drain the bytes
    /// the renderer produced and feed them to the emulator.
    #[derive(Clone)]
    struct Shared(Rc<RefCell<Vec<u8>>>);

    impl Write for Shared {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.borrow_mut().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// A renderer wired to a `vt100` terminal of the given size.
    struct Emu {
        buf: Shared,
        renderer: FrameRenderer<Shared>,
        parser: vt100::Parser,
        rows: u16,
        cols: u16,
    }

    impl Emu {
        fn new(rows: u16, cols: u16) -> Self {
            let buf = Shared(Rc::new(RefCell::new(Vec::new())));
            Self {
                renderer: FrameRenderer::new(buf.clone()),
                parser: vt100::Parser::new(rows, cols, 0),
                buf,
                rows,
                cols,
            }
        }

        /// Resize the emulated terminal (as a real terminal would on a drag).
        fn resize(&mut self, rows: u16, cols: u16) {
            self.rows = rows;
            self.cols = cols;
            self.parser.set_size(rows, cols);
        }

        /// Render a frame and feed the produced bytes to the emulator.
        fn render(&mut self, frame: &[String]) {
            self.renderer.render(frame, self.cols as usize, self.rows as usize).unwrap();
            let bytes: Vec<u8> = self.buf.0.borrow_mut().drain(..).collect();
            self.parser.process(&bytes);
        }

        /// The visible screen, one trimmed string per row.
        fn screen(&self) -> Vec<String> {
            self.parser.screen().rows(0, self.cols).map(|row| row.trim_end().to_string()).collect()
        }
    }

    fn sample_frame(width: usize) -> Vec<String> {
        let transcript = transcript_lines(
            &[
                StampedItem {
                    stamp: String::new(),
                    item: Item::Message { role: Role::User, text: "please summarise the plan".into() },
                },
                StampedItem {
                    stamp: String::new(),
                    item: Item::Message {
                        role: Role::Assistant,
                        text: "here is a fairly long answer that is meant to wrap onto more than one row when the terminal is narrow".into(),
                    },
                },
            ],
            width,
        );
        let editor = editor_lines("› ", "my next question", 16, width);
        compose(&transcript, &editor, "MODEL  ctx 10% ")
    }

    #[test]
    fn bar_is_the_last_row_with_the_editor_above_and_no_duplicates() {
        let mut emu = Emu::new(24, 80);
        emu.render(&sample_frame(80));
        let screen = emu.screen();
        assert_eq!(screen.last().unwrap(), "MODEL  ctx 10%", "bar on the last row");
        // The editor row sits directly above the bar.
        let editor_row = &screen[screen.len() - 2];
        assert!(editor_row.contains("my next question"), "editor above the bar: {editor_row:?}");
        // Exactly one bar on screen.
        let bars = screen.iter().filter(|r| r.contains("ctx 10%")).count();
        assert_eq!(bars, 1, "no duplicate bars: {screen:?}");
    }

    #[test]
    fn a_width_change_reflows_history() {
        let mut emu = Emu::new(24, 80);
        emu.render(&sample_frame(80));
        // The long answer fits few rows when wide.
        let wide_answer_rows = emu.screen().iter().filter(|r| r.contains("fairly long answer")).count();

        // Shrink: the terminal (and renderer) both go narrow.
        emu.resize(24, 30);
        emu.render(&sample_frame(30));
        let narrow = emu.screen();
        // The bar is still the single last row.
        assert_eq!(narrow.last().unwrap(), "MODEL  ctx 10%");
        assert_eq!(narrow.iter().filter(|r| r.contains("ctx 10%")).count(), 1);
        // Every visible row now fits the new width.
        for row in &narrow {
            assert!(row.chars().count() <= 30, "row wider than 30: {row:?}");
        }
        // History reflowed: the long answer occupies more rows at the smaller
        // width than it did when wide.
        let narrow_answer_rows =
            narrow.iter().filter(|r| r.contains("fairly") || r.contains("answer") || r.contains("wrap")).count();
        assert!(
            narrow_answer_rows > wide_answer_rows,
            "history did not reflow ({wide_answer_rows} -> {narrow_answer_rows})"
        );
    }

    #[test]
    fn a_resize_drag_ends_on_a_stable_correct_frame() {
        let mut emu = Emu::new(24, 80);
        emu.render(&sample_frame(80));
        // 20 resizes in a row, as during a window drag.
        for i in 0..20 {
            let cols = 40 + (i % 40) as u16;
            emu.resize(24, cols);
            emu.render(&sample_frame(cols as usize));
        }
        // Settle at a final size and render the final frame twice: the second
        // render must be a no-op that leaves an identical, correct screen.
        emu.resize(24, 64);
        emu.render(&sample_frame(64));
        let first = emu.screen();
        emu.render(&sample_frame(64));
        let second = emu.screen();
        assert_eq!(first, second, "frame not stable after the drag");
        assert_eq!(second.last().unwrap(), "MODEL  ctx 10%");
        assert_eq!(second.iter().filter(|r| r.contains("ctx 10%")).count(), 1);
        assert!(second[second.len() - 2].contains("my next question"));
    }

    /// A frame whose transcript holds a raw export line far wider than the
    /// terminal: the line wraps natively onto extra rows, and the renderer must
    /// still land the editor and the status bar on the correct rows.
    fn wide_raw_frame(width: usize, marker: &str) -> Vec<String> {
        let long = "x".repeat(width * 3);
        let transcript = transcript_lines(
            &[
                StampedItem { stamp: String::new(), item: Item::Raw(format!("{{\"k\":\"{long}\"}}")) },
                StampedItem {
                    stamp: String::new(),
                    item: Item::Message { role: Role::Assistant, text: format!("answer {marker}") },
                },
            ],
            width,
        );
        let editor = editor_lines("› ", "next", 4, width);
        compose(&transcript, &editor, "BAR")
    }

    #[test]
    fn a_wrapping_raw_line_keeps_the_bar_on_the_last_row() {
        let mut emu = Emu::new(24, 40);
        emu.render(&wide_raw_frame(40, "a"));
        let screen = emu.screen();
        // The raw line wrapped onto several rows, but the bar is still the
        // single last row and the editor sits directly above it.
        assert_eq!(screen.last().unwrap(), "BAR", "bar pushed off the last row: {screen:?}");
        assert_eq!(screen.iter().filter(|r| r.contains("BAR")).count(), 1, "duplicate bars: {screen:?}");
        assert!(screen[screen.len() - 2].contains("next"), "editor not above the bar: {screen:?}");
    }

    #[test]
    fn a_differential_render_after_a_wrapping_raw_line_addresses_real_rows() {
        let mut emu = Emu::new(24, 40);
        emu.render(&wide_raw_frame(40, "a"));
        // Change only the trailing assistant text: a differential render must
        // rewrite that row in place, not the row a naive logical index picks.
        emu.render(&wide_raw_frame(40, "b"));
        let screen = emu.screen();
        assert_eq!(screen.last().unwrap(), "BAR");
        assert_eq!(screen.iter().filter(|r| r.contains("BAR")).count(), 1, "bar duplicated: {screen:?}");
        assert!(screen.iter().any(|r| r.contains("answer b")), "update lost: {screen:?}");
        assert!(!screen.iter().any(|r| r.contains("answer a")), "stale row left behind: {screen:?}");
    }

    #[test]
    fn physical_row_helpers_count_native_wraps() {
        // Empty and exactly-full lines take one row; wider lines wrap.
        assert_eq!(line_physical_rows("", 10), 1);
        assert_eq!(line_physical_rows("1234567890", 10), 1);
        assert_eq!(line_physical_rows("12345678901", 10), 2);
        assert_eq!(line_physical_rows(&"x".repeat(25), 10), 3);
        // ANSI styling adds no width.
        assert_eq!(line_physical_rows("\x1b[2m12345\x1b[0m", 10), 1);
        // The frame total is the per-line sum.
        let frame = vec!["abc".to_string(), "x".repeat(21), String::new()];
        assert_eq!(physical_rows(&frame, 10), 1 + 3 + 1);
    }

    #[test]
    fn line_physical_rows_counts_wide_glyphs_that_cannot_start_in_the_last_column() {
        // Cell widths 1,2,2,2,2,2,1,2,2,2,2 (2 ASCII + 9 CJK = 20 cells) at
        // width 10: the naive `ceil(20/10)` is 2, but a 2-cell glyph cannot
        // start in the last column, so the terminal actually uses 3 rows.
        // `visible_width` still sums to 20 — only the incremental count sees
        // the boundary.
        let line = "1\u{4e16}\u{4e16}\u{4e16}\u{4e16}\u{4e16}2\u{4e16}\u{4e16}\u{4e16}\u{4e16}";
        assert_eq!(visible_width(line), 20);
        assert_eq!(visible_width(line).div_ceil(10), 2);
        assert_eq!(line_physical_rows(line, 10), 3);
        // ANSI styling around the wide glyphs still advances no cell.
        let styled = format!("\x1b[2m{line}\x1b[0m");
        assert_eq!(line_physical_rows(&styled, 10), 3);
        // A glyph wider than the column still occupies exactly one row.
        assert_eq!(line_physical_rows("\u{4e16}", 1), 1);
    }
}