mindfork 0.13.0

A terminal AI chat written in Rust: local models via llama.cpp, or OpenAI, Anthropic, Gemini, Grok and OpenRouter in the cloud, with persistent memory, notes, RAG and tools.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
//! `shared` layer (FSD): small reusable TUI rendering helpers, independent of
//! the upper layers.

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

use ratatui::Frame;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Flex, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Clear, HighlightSpacing, List, ListState, Paragraph, Scrollbar, ScrollbarOrientation,
    ScrollbarState, Wrap,
};

use crate::shared::theme::{MONO_MARK, Palette};

/// Dims the whole screen (the `DIM` modifier on every buffer cell), so a popup
/// drawn on top doesn't blend into the background. Call **before**
/// `Clear`+rendering the popup: `Clear` then resets the popup's cells to the
/// default (non-dimmed) style, so only the background gets dimmed, while the
/// popup itself stays bright.
///
/// The `DIM` effect is terminal-dependent (Windows Terminal supports it,
/// conhost Windows 10 doesn't), so in compatibility mode (`palette.compat`,
/// spec §11.6) the background is dimmed **by color**: every cell's fg →
/// `palette.muted` (plus `BOLD` is dropped — in a 16-color mapping it gives a
/// "bright" variant and would cancel out the dimming).
pub fn dim_background(frame: &mut Frame, palette: &Palette) {
    let area = frame.area();
    let compat = palette.compat;
    let muted = palette.muted;
    let buf = frame.buffer_mut();
    for y in area.top()..area.bottom() {
        for x in area.left()..area.right() {
            let cell = &mut buf[(x, y)];
            if compat {
                cell.fg = muted;
                cell.modifier.remove(Modifier::BOLD);
            } else {
                cell.modifier |= Modifier::DIM;
            }
        }
    }
}

/// Puts the palette's canvas under a **finished** frame — the full colour mode
/// (spec §11.6, docs/history/theme-modes.md §4.2). Every cell whose background is
/// still the terminal's default gets the canvas, and every cell whose
/// foreground is gets the palette's text colour; a colour a widget set is left
/// exactly as it is. In the system mode the palette has no canvas and nothing
/// is touched.
///
/// Call it **last** — after the screen and after any overlay. That is the
/// point of doing this as a pass rather than as a base style under every
/// widget: a popup's `Clear` resets its cells to the terminal's default, the
/// logo and highlighted code never ask the palette, and the next widget
/// somebody writes will not remember either. Whatever reached the buffer
/// without a colour is caught here.
///
/// Attributes are not read: `REVERSED` over a filled cell swaps the canvas and
/// the text colour, which is what it did with the terminal's own two.
pub fn paint_canvas(buf: &mut Buffer, palette: &Palette) {
    let canvas = palette.canvas;
    if canvas == Color::Reset {
        return;
    }
    for cell in buf.content.iter_mut() {
        if cell.bg == Color::Reset {
            cell.bg = canvas;
        }
        if cell.fg == Color::Reset {
            cell.fg = palette.text;
        }
    }
}

/// Takes every colour and every text attribute off a **finished** frame — the
/// monochrome mode (spec §11.6, docs/history/theme-modes.md §9). What is left is the
/// terminal's own two colours, and reverse video on the cells a widget drew
/// on [`MONO_MARK`]: a text selection and a search match, the two things with
/// no glyph to fall back on. In any other mode nothing is touched.
///
/// A pass for the reason [`paint_canvas`] is one, only more so: attributes
/// never went through the palette at all — widgets set bold, dim, italic,
/// underline and reverse directly — and the logo and highlighted code bring
/// colours of their own. Stripping the frame is the one way that cannot miss
/// any of them, including the ones not written yet.
///
/// Reverse video is opt-in **by name**: a popup's `reversed()` row and an
/// unhighlighted code block lose theirs here like everything else. Which is
/// why the pass is only half of the mode — where styling was the only thing
/// saying something, the widget has to say it with a glyph
/// ([`Palette::mono`]).
pub fn strip_styles(buf: &mut Buffer, palette: &Palette) {
    if !palette.mono {
        return;
    }
    for cell in buf.content.iter_mut() {
        let marked = cell.bg == MONO_MARK;
        cell.fg = Color::Reset;
        cell.bg = Color::Reset;
        cell.underline_color = Color::Reset;
        cell.modifier = if marked {
            Modifier::REVERSED
        } else {
            Modifier::empty()
        };
    }
}

/// The passes over a finished frame, in one call: the canvas of the full
/// mode, the stripping of the monochrome one. Each is a no-op outside its
/// mode, and a palette is never in both. Call it **last** — after the screen
/// and after any overlay.
pub fn finish_frame(buf: &mut Buffer, palette: &Palette) {
    paint_canvas(buf, palette);
    strip_styles(buf, palette);
}

/// Gives a list the marker of its selected row where the mode needs one
/// ([`Palette::selected_mark`]): the rows that say which one is selected by
/// styling alone — a `highlight_style` and nothing else — say it with a
/// glyph in the monochrome mode. Every row gives up the marker's width, so
/// the list does not shift as the selection moves.
pub fn mark_selected<'a>(list: List<'a>, palette: &Palette) -> List<'a> {
    match palette.selected_mark() {
        Some(mark) => list
            .highlight_symbol(mark)
            .highlight_spacing(HighlightSpacing::Always),
        None => list,
    }
}

/// Erase the whole screen (`ED 2`). Terminals erase **with the current
/// background** — which is the whole reason [`set_background`] exists.
pub const ERASE_SCREEN: &str = "\x1b[2J";

/// Back to the terminal's default colours and attributes (`SGR 0`). ratatui's
/// backend assumes exactly that state at the start of every draw, so nothing
/// that sets a colour by hand may leave it set.
pub const RESET_STYLE: &str = "\x1b[0m";

/// The sequence that makes `canvas` the terminal's current background, or
/// nothing for `Color::Reset` (the terminal's own is already current).
///
/// Used once per change of canvas, around an erase: a cell the app never
/// writes keeps the colour the last erase gave it, and there is such a cell
/// behind every wide glyph — ratatui resets a wide glyph's trailing cell and
/// leaves it out of the diff, so a terminal that does not give it the
/// glyph's colours itself shows whatever was there. Windows 11's console host
/// does give them, measured (docs/history/theme-modes.md §8); this is the guard for
/// one that does not.
///
/// Built here and written by the caller, like `shared/osc52.rs`: that is what
/// lets a test assert the exact bytes.
pub fn set_background(canvas: Color) -> String {
    match canvas {
        Color::Rgb(r, g, b) => format!("\x1b[48;2;{r};{g};{b}m"),
        // A canvas is absolute or absent (`Palette::canvas`); anything else
        // has no business being painted, and saying nothing is the safe half.
        _ => String::new(),
    }
}

/// Primes the buffer for a **full redraw** of the next frame: makes every cell
/// provably different from whatever the frame will draw, so ratatui's
/// per-cell diff rewrites the whole screen — including spaces in empty spots —
/// and clears "hanging" terminal artifacts.
///
/// Called on a buffer that then moves into the back buffer via
/// `swap_buffers()` **without a screen flush**: the marker itself never
/// reaches the terminal, it's only a diff base. We don't use a plain clear
/// (`terminal.clear()`) — it sends `ESC[2J`, and the screen blanks for a
/// moment (flicker).
///
/// **Why a space + `HIDDEN`, not a placeholder character.** The marker used to
/// be the character `"\0"`, but that broke rows with VS16 emoji (`🗂️`,
/// `❤️`): for such a cluster `ratatui` **additionally sends its trailing
/// cell** (a workaround for terminals that don't clear the second half of a
/// wide glyph), but **only if its symbol changed** — and `"\0"` always changed
/// it. The `crossterm` backend tracks position by cell number, without
/// accounting for glyph width (`x == last.x + 1` → no `MoveTo`), so such a
/// trailing cell printed one column to the right and shifted the rest of the
/// row: the next wide glyph's right half got overwritten (the terminal wiped
/// it out entirely), the panel border drifted outward.
///
/// A space matches the content of the trailing cell (`ratatui` resets it to
/// default), so such cells don't land in the diff — and no shift occurs.
/// Everything else differs by the [`SENTINEL_MODIFIER`] modifier, which never
/// occurs in the interface (pinned by a test), so redraw completeness isn't
/// compromised.
pub fn prime_full_redraw(buf: &mut Buffer) {
    for cell in buf.content.iter_mut() {
        cell.set_symbol(" ");
        cell.modifier = SENTINEL_MODIFIER;
    }
}

/// Marker modifier for [`prime_full_redraw`]: unused in the interface (the
/// palette and widgets get by with `DIM`/`BOLD`/`ITALIC`/`UNDERLINED`/
/// `REVERSED`), so no cell of a real frame will ever match it.
const SENTINEL_MODIFIER: Modifier = Modifier::HIDDEN;

/// How long one spinner glyph stays up — and so how often an otherwise idle
/// screen writes to the terminal while a spinner runs, which is the number
/// that matters. Windows Terminal re-finds the URLs it detects in the text
/// only once its output has been quiet for 100 ms (`ControlCore`'s
/// `outputIdle`, a debounce). A spinner repainting every 50 ms tick never let
/// it: every detected link stayed on the row it held before the layout last
/// moved, so the indexing banner's own row pushed the feed up, and hovering
/// the line under a link underlined it and read its text as the URI
/// (`Invalid URI`). With the loop's 50 ms tick the frames land 150–250 ms
/// apart — a quiet gap longer than the debounce after each of them
/// (docs/journal/ui-feed.md, "the spinner leaves the terminal a quiet gap").
pub const SPINNER_STEP: Duration = Duration::from_millis(200);

/// A spinner's clock: the glyph it shows is a function of the time since it
/// started, not of the frames drawn, and the loop repaints for it only when
/// that glyph changes ([`Spinner::due`]). A frame counter got both wrong: the
/// spin sped up with every frame something else asked for (typing, a stream),
/// and the loop had to draw on every tick to move it at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Spinner {
    started: Instant,
    /// The step the last frame showed (`None` — not drawn yet).
    drawn: Option<u128>,
}

impl Default for Spinner {
    fn default() -> Self {
        Self::new()
    }
}

impl Spinner {
    /// A spinner starting now, on its first glyph.
    pub fn new() -> Self {
        Self::started_at(Instant::now())
    }

    fn started_at(started: Instant) -> Self {
        Self {
            started,
            drawn: None,
        }
    }

    /// Whole [`SPINNER_STEP`]s from the start to `now`.
    fn step_at(&self, now: Instant) -> u128 {
        now.saturating_duration_since(self.started).as_millis() / SPINNER_STEP.as_millis()
    }

    /// Whether a frame drawn now would show another glyph than the last one
    /// did — or none has been drawn yet.
    pub fn due(&self) -> bool {
        self.due_at(Instant::now())
    }

    fn due_at(&self, now: Instant) -> bool {
        self.drawn != Some(self.step_at(now))
    }

    /// The glyph of `frames` to draw now, recorded as drawn.
    pub fn glyph(&mut self, frames: &[char]) -> char {
        self.glyph_at(frames, Instant::now())
    }

    fn glyph_at(&mut self, frames: &[char], now: Instant) -> char {
        let step = self.step_at(now);
        self.drawn = Some(step);
        frames[(step % frames.len() as u128) as usize]
    }
}

/// Draws a vertical scrollbar in the **right column** of `area` when the
/// content doesn't fit by height (`total > viewport`); otherwise — a no-op
/// (the bar isn't drawn, so it doesn't clutter short content). `total` —
/// total content rows, `viewport` — visible ones, `position` — the first
/// visible row (the caller scrolls the content itself; the bar is a pure
/// indicator).
///
/// Panels with a border pass an area with a vertical margin of 1
/// (`area.inner(Margin::new(0, 1))`): the bar lands **on the right border
/// line**, without touching its corners and without taking width away from
/// the content. `focused` — which color the border under the bar is drawn in
/// (normal/focused): both the track and the thumb are drawn in that color, so
/// the scrollbar blends with the border, differing only by the `█` fill
/// (thumb) versus the thin `│` (track). The thumb follows the border's color
/// — a border-palette change automatically recolors it too.
pub fn render_scrollbar(
    frame: &mut Frame,
    area: Rect,
    total: usize,
    viewport: usize,
    position: usize,
    focused: bool,
    palette: &Palette,
) {
    if total <= viewport || area.width == 0 || area.height == 0 {
        return;
    }
    // `content_length` is the number of scroll POSITIONS (total − viewport +
    // 1), not rows: ratatui places the thumb's bottom at the end of the track
    // at position `content_length − 1`, i.e. exactly at full scroll (total −
    // viewport). With `content_length = total` the thumb wouldn't reach the
    // bottom.
    let mut state = ScrollbarState::new(total - viewport + 1)
        .position(position)
        .viewport_content_length(viewport);
    let bar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
        .begin_symbol(None)
        .end_symbol(None)
        .track_symbol(Some("│"))
        .thumb_symbol("█")
        .track_style(palette.border_style(focused))
        .thumb_style(palette.border_style(focused));
    frame.render_stateful_widget(bar, area, &mut state);
}

/// A list's scroll position, kept **between frames**.
///
/// ratatui moves a list's offset only as far as it must to bring the selection
/// into view, so a `ListState` built inside a `render` function recomputes the
/// offset from zero on every draw — which reads as "scroll until the selection
/// is the *last* visible row". Downward that looks like a window correctly
/// following the selection; upward the list scrolls on every press and the
/// selection never walks up to the top row (docs/lessons.md §5). The offset is
/// state, not decoration: the widget owns one of these and calls
/// [`ListScroll::render`] instead of building a `ListState` itself.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ListScroll {
    offset: usize,
}

impl ListScroll {
    /// The first visible row of the last draw — what [`render_scrollbar`] takes
    /// as its `position`.
    pub fn offset(&self) -> usize {
        self.offset
    }

    /// Draws `list` into `area` with the selection on `selected` (`None` — no
    /// selection), carrying the scroll position over from the previous frame.
    ///
    /// `len` — the number of items, `view_h` — the rows the list actually draws
    /// into (`area.height` minus the block's borders, when it has one). The two
    /// clamp the stored offset to the list's tail before the draw, so a list
    /// that has shrunk under it (a filter, a deletion) cannot leave the window
    /// hanging past its end. For items taller than one row the clamp is merely
    /// conservative — ratatui still scrolls down to the selection.
    pub fn render(
        &mut self,
        frame: &mut Frame,
        list: List<'_>,
        area: Rect,
        len: usize,
        view_h: usize,
        selected: Option<usize>,
    ) {
        self.offset = self.offset.min(len.saturating_sub(view_h));
        let mut state = ListState::default().with_offset(self.offset);
        if len > 0
            && let Some(sel) = selected
        {
            state.select(Some(sel.min(len - 1)));
        }
        frame.render_stateful_widget(list, area, &mut state);
        self.offset = state.offset();
    }
}

/// Keeps `selected` inside a `view`-row window starting at `scroll`: the
/// offset moves only as far as it must, in either direction, so the selection
/// can walk to the top row as well as the bottom one. For screens that draw
/// their rows through a `Paragraph` rather than a `List` — the changes and
/// tasks screens — where [`ListScroll`] does not apply.
pub fn keep_visible(scroll: usize, selected: usize, view: usize) -> usize {
    if view == 0 {
        return 0;
    }
    if selected < scroll {
        selected
    } else if selected >= scroll + view {
        selected + 1 - view
    } else {
        scroll
    }
}

/// Gap between hotkey-grid columns, and between the chat bar's status pill and
/// the grid beside it.
pub const HINT_GAP: usize = 3;

/// One hint's cell width in columns: the keycap (the label plus the two spaces
/// [`Palette::keycap`] wraps it in), a space, and the description.
pub fn hint_cell_width(key: &str, desc: &str) -> usize {
    str_width(key) + 2 + 1 + str_width(desc)
}

/// The cell widths of a whole hint list, in its display order.
pub fn hint_cell_widths(items: &[(&str, &str, bool)]) -> Vec<usize> {
    items
        .iter()
        .map(|(key, desc, _)| hint_cell_width(key, desc))
        .collect()
}

/// Places `cell_w.len()` cells on a grid of `cols` columns: they fill
/// row-by-row, left-to-right/top-to-bottom, but **an incomplete bottom row is
/// right-aligned** — its cells take the rightmost columns, under the full rows
/// above. Returns `grid[row][col] = Some(cell index)`, the column widths (the
/// max over the cells actually placed in each column) and the block's total
/// width (columns + gaps).
///
/// The right-aligned bottom row is what makes a wrapped hint land exactly under
/// the column above it rather than as a floating group — see spec §11.1 and the
/// journal entry *status bar — pill top-left, hotkey grid right*.
pub fn hint_grid_layout(
    cell_w: &[usize],
    cols: usize,
) -> (Vec<Vec<Option<usize>>>, Vec<usize>, usize) {
    let n = cell_w.len();
    let rows = n.div_ceil(cols);
    let full = (rows - 1) * cols; // cells in full rows
    let empty_lead = cols - (n - full); // empty columns at the start of the bottom row

    let mut grid = vec![vec![None; cols]; rows];
    for i in 0..n {
        let (r, c) = if i < full {
            (i / cols, i % cols)
        } else {
            (rows - 1, empty_lead + (i - full))
        };
        grid[r][c] = Some(i);
    }

    let mut colw = vec![0usize; cols];
    for row in &grid {
        for (c, cell) in row.iter().enumerate() {
            if let Some(i) = cell {
                colw[c] = colw[c].max(cell_w[*i]);
            }
        }
    }
    let block_w = colw.iter().sum::<usize>() + HINT_GAP * cols.saturating_sub(1);
    (grid, colw, block_w)
}

/// The most columns whose grid fits into `avail` (→ the fewest rows); `None`
/// when not even a single column does.
pub fn widest_hint_grid(cell_w: &[usize], avail: usize) -> Option<usize> {
    (1..=cell_w.len())
        .rev()
        .find(|&c| hint_grid_layout(cell_w, c).2 <= avail)
}

/// Everything a hint block needs beyond its items: how wide the strip is, how
/// many columns to use, what shares its top row, and which cell is the one
/// highlighted mode light.
pub struct HintGrid<'a> {
    /// Hints in display order: key, description, and whether the key is
    /// "dangerous" (a red keycap — delete and friends).
    pub items: &'a [(&'a str, &'a str, bool)],
    /// Each item's cell width ([`hint_cell_widths`]) — passed in because the
    /// caller has usually computed it already to choose `cols`.
    pub cell_w: &'a [usize],
    /// Columns to lay the block out in ([`widest_hint_grid`], or the chat bar's
    /// own capped choice).
    pub cols: usize,
    /// The strip's full width; the block hugs its right edge.
    pub width: usize,
    /// Spans to put at the **left of the top row** — the chat bar's status
    /// pill. `None` on the screens, whose footers are hints and nothing else.
    pub lead: Option<Vec<Span<'static>>>,
    /// The one cell whose description is drawn in `accent` instead of muted —
    /// the chat bar's mouse-mode light. `None` elsewhere.
    pub accent: Option<usize>,
}

/// Draws a hint block right-aligned to `grid.width`: columns line up
/// vertically, an incomplete bottom row lands under the columns above, and
/// `grid.lead` (when given) opens the top row on the left.
///
/// The one hint-grid renderer in the application — every footer and the chat
/// bar's corner block come out of here, so they cannot drift apart in
/// alignment, spacing or keycap styling (docs/history/status-hints-unified.md §2.1).
pub fn render_hint_grid(grid: &HintGrid, palette: &Palette) -> Vec<Line<'static>> {
    if grid.items.is_empty() || grid.cols == 0 {
        return Vec::new();
    }
    let (cells, colw, block_w) = hint_grid_layout(grid.cell_w, grid.cols);
    let lead_w = grid.width.saturating_sub(block_w);
    let mut lead = grid.lead.clone();

    let mut out: Vec<Line<'static>> = Vec::new();
    for (r, row) in cells.iter().enumerate() {
        let mut spans: Vec<Span<'static>> = Vec::new();
        push_row_lead(&mut spans, r, &mut lead, lead_w);
        // A cell is padded out to its column's width (+ a gap, except in the
        // last column); an empty column is all spaces, so columns line up.
        for (c, cell) in row.iter().enumerate() {
            let gap = if c + 1 < grid.cols { HINT_GAP } else { 0 };
            match cell {
                Some(i) => push_hint_cell(&mut spans, grid, palette, *i, colw[c], gap),
                None => spans.push(Span::raw(" ".repeat(colw[c] + gap))),
            }
        }
        out.push(Line::from(spans));
    }
    out
}

/// One occupied grid cell: the hint — its description accent-highlighted when
/// this is the block's mode light, its keycap red when the key is "dangerous" —
/// followed by padding out to `col_w` plus the trailing `gap`. A column is
/// never narrower than the cells in it, so the padding cannot underflow.
fn push_hint_cell(
    spans: &mut Vec<Span<'static>>,
    grid: &HintGrid,
    palette: &Palette,
    i: usize,
    col_w: usize,
    gap: usize,
) {
    let (key, desc, danger) = grid.items[i];
    if grid.accent == Some(i) {
        spans.extend(palette.hint_highlight_value(key, desc, palette.accent));
    } else {
        spans.extend(palette.hint_marked(key, desc, danger));
    }
    let pad = col_w.saturating_sub(grid.cell_w[i]) + gap;
    if pad > 0 {
        spans.push(Span::raw(" ".repeat(pad)));
    }
}

/// The left margin of grid row `r`: on the top row — the lead cluster (taken
/// out of `lead`), everywhere else — spaces, since the block is right-aligned.
fn push_row_lead(
    spans: &mut Vec<Span<'static>>,
    r: usize,
    lead: &mut Option<Vec<Span<'static>>>,
    lead_w: usize,
) {
    if r == 0
        && let Some(pill) = lead.take()
    {
        let pill_w: usize = pill.iter().map(|s| str_width(&s.content)).sum();
        spans.extend(pill);
        if lead_w > pill_w {
            spans.push(Span::raw(" ".repeat(lead_w - pill_w)));
        }
    } else if lead_w > 0 {
        spans.push(Span::raw(" ".repeat(lead_w)));
    }
}

/// A screen's footer: hints laid out **right-aligned** into the widest grid
/// that fits `width`, wrapping to as many rows as they need. Empty for an empty
/// list.
///
/// Unlike the chat bar's corner block, a footer never sheds a hint: it has the
/// whole width and no status pill competing for it, so it grows a row instead
/// (user's decision, 2026-08-31 — docs/history/status-hints-unified.md §2.1).
pub fn hotkey_grid(
    palette: &Palette,
    items: &[(&str, &str, bool)],
    width: usize,
) -> Vec<Line<'static>> {
    if items.is_empty() {
        return Vec::new();
    }
    let cell_w = hint_cell_widths(items);
    let cols = widest_hint_grid(&cell_w, width).unwrap_or(1);
    render_hint_grid(
        &HintGrid {
            items,
            cell_w: &cell_w,
            cols,
            width,
            lead: None,
            accent: None,
        },
        palette,
    )
}

/// The visible width of a string in terminal columns.
fn str_width(s: &str) -> usize {
    crate::shared::wrap::display_width(&s.chars().collect::<Vec<_>>())
}

/// What [`screen_chrome`] hands back: where the content goes, where the hotkey
/// grid goes, and the grid itself.
pub struct ScreenChrome {
    /// Inside the panel's border — where the screen draws its own content.
    pub inner: Rect,
    /// The panel itself, border included. A screen that draws a scrollbar
    /// **on** the right border (`render_scrollbar`) measures it from here.
    pub panel: Rect,
    /// The strip below the panel, for [`Self::hotkeys`] or a warning line.
    pub status: Rect,
    pub hotkeys: Vec<Line<'static>>,
}

/// Draws the chrome a full-screen screen opens with: a hotkey grid pinned to the
/// bottom, and a titled panel filling everything above it.
///
/// Six lines that every screen here repeats verbatim — build the grid, size the
/// status row from it, split vertically, build the panel, take its `inner`,
/// render it. The duplication gate found the pair when the changes screen became
/// the fourth; this is the seam the rule says to build when a new thing is a
/// sibling of an existing one (docs/lessons.md §2). The search, self-model and
/// settings screens joined it when their footers moved onto the one hint grid
/// (docs/history/status-hints-unified.md).
///
/// `right` is the muted, right-aligned title some screens carry (a match count,
/// a summary); the caller still renders `hotkeys` into `status`, because a screen
/// with a confirmation to show puts that there instead.
pub fn screen_chrome(
    frame: &mut Frame,
    palette: &Palette,
    title: String,
    right: Option<String>,
    hk: &[(&str, &str, bool)],
) -> ScreenChrome {
    let area = frame.area();
    frame.render_widget(Clear, area);
    let hotkeys = hotkey_grid(palette, hk, area.width as usize);
    let status_h = (hotkeys.len() as u16).max(1);
    let [panel_area, status] =
        Layout::vertical([Constraint::Min(3), Constraint::Length(status_h)]).areas(area);
    let mut block = palette.panel(title, true);
    if let Some(right) = right {
        block = block.title(
            Line::from(Span::styled(format!(" {right} "), palette.muted_style())).right_aligned(),
        );
    }
    let inner = block.inner(panel_area);
    frame.render_widget(block, panel_area);
    ScreenChrome {
        inner,
        panel: panel_area,
        status,
        hotkeys,
    }
}

/// A modal confirmation: a centred, bordered box with a question and a footer
/// naming the keys that answer it.
///
/// One renderer rather than one per screen. The chat screen has asked
/// destructive questions since the dangerous-tool track (spec §9.8) and the
/// changes screen asks the same shape of question about a revert; `screens` are
/// siblings, so the second one could not have reached the first's without a
/// copy. The **keys** stay with each caller — what confirms differs (`Enter`
/// there, `Enter` here, `Enter`/`A`/`Esc` for a tool call) and only the drawing
/// is common.
pub fn confirm_popup(
    frame: &mut Frame,
    palette: &Palette,
    title: &str,
    question: &str,
    footer: &str,
) {
    // Wide enough to read, never wider than the terminal; three rows of border
    // and text, plus one for a wrapped second line.
    let width = 56u16.min(frame.area().width);
    let area = centered_rect(width, 5, frame.area());
    frame.render_widget(Clear, area);
    let block = palette.panel(title.to_string(), true).title_bottom(
        Line::from(Span::styled(footer.to_string(), palette.muted_style())).centered(),
    );
    let body = Paragraph::new(Line::from(Span::styled(
        question.to_string(),
        Style::new().fg(palette.text),
    )))
    .block(block)
    .wrap(Wrap { trim: true });
    frame.render_widget(body, area);
}

/// A fixed-width/height rectangle centred in `area` (clamped).
pub fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let [h] = Layout::horizontal([Constraint::Length(width.min(area.width))])
        .flex(Flex::Center)
        .areas(area);
    let [v] = Layout::vertical([Constraint::Length(height.min(area.height))])
        .flex(Flex::Center)
        .areas(h);
    v
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    /// A hint block's rows as plain strings.
    fn grid_text(items: &[(&str, &str, bool)], width: usize) -> Vec<String> {
        hotkey_grid(&Palette::default(), items, width)
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    /// Every footer in the application is right-aligned and wraps rather than
    /// sheds — the one property the screens share with the chat bar's corner
    /// block (docs/history/status-hints-unified.md §2.1).
    #[test]
    fn a_footer_is_right_aligned_and_wraps() {
        let items: &[(&str, &str, bool)] = &[
            ("Tab", "section", false),
            ("↑↓", "fields", false),
            ("Enter", "edit", false),
            ("Esc", "back", false),
            ("Ctrl+Q", "quit", false),
        ];
        // Wide — one row, flush against the right edge.
        let wide = grid_text(items, 200);
        assert_eq!(wide.len(), 1);
        assert_eq!(
            wide[0].chars().count(),
            200,
            "the row is padded out to the width"
        );
        assert!(wide[0].trim_end().ends_with("quit"), "{:?}", wide[0]);
        assert!(wide[0].starts_with("    "), "left margin: {:?}", wide[0]);
        // Narrow — more rows, and every hint is still there: a footer never sheds.
        let narrow = grid_text(items, 24);
        assert!(narrow.len() > 1);
        let all = narrow.join("");
        for (key, _, _) in items {
            assert!(all.contains(key), "{key} was shed: {narrow:?}");
        }
        // An empty set — no rows at all (the caller reserves a minimum height).
        assert!(hotkey_grid(&Palette::default(), &[], 80).is_empty());
        // A width no single cell fits into still lays out (one column, clipped
        // by the terminal) rather than panicking — `render` is called on every
        // frame, including the first one on a 1-column pane.
        for w in [0usize, 1, 2] {
            assert_eq!(grid_text(items, w).len(), items.len());
        }
    }

    /// An incomplete bottom row takes the **rightmost** columns, so a wrapped
    /// hint lands exactly under the column above it instead of reading as a
    /// floating group. Asserted in character positions, on the rendered rows.
    #[test]
    fn a_wrapped_row_lands_under_the_columns_above() {
        // Four equal-width cells at a width that fits three per row.
        let items: &[(&str, &str, bool)] = &[
            ("K1", "aaaa", false),
            ("K2", "bbbb", false),
            ("K3", "cccc", false),
            ("K4", "dddd", false),
        ];
        let cell = hint_cell_width("K1", "aaaa");
        let width = cell * 3 + HINT_GAP * 2;
        let rows = grid_text(items, width);
        assert_eq!(rows.len(), 2, "{rows:?}");
        assert_eq!(
            rows[1].find("K4"),
            rows[0].find("K3"),
            "the wrapped cell sits under the last column: {rows:?}"
        );
        assert!(
            rows[1][..rows[1].find("K4").unwrap()].trim().is_empty(),
            "everything left of the wrapped cell is padding: {rows:?}"
        );
        assert_eq!(rows[1].chars().count(), width);
    }

    /// The layout is the same one the chat bar's corner block uses, so the two
    /// cannot drift: the block hugs the right edge at every column count.
    #[test]
    fn the_block_width_accounts_for_every_column_and_gap() {
        let cell_w = vec![10, 12, 8, 14, 9];
        for cols in 1..=cell_w.len() {
            let (grid, colw, block_w) = hint_grid_layout(&cell_w, cols);
            assert_eq!(grid[0].len(), cols);
            assert_eq!(
                block_w,
                colw.iter().sum::<usize>() + HINT_GAP * (cols - 1),
                "cols={cols}"
            );
            // Every cell is placed exactly once.
            let mut seen: Vec<usize> = grid.iter().flatten().flatten().copied().collect();
            seen.sort_unstable();
            assert_eq!(seen, (0..cell_w.len()).collect::<Vec<_>>(), "cols={cols}");
        }
        // The widest grid that fits is the one with the fewest rows.
        assert_eq!(widest_hint_grid(&cell_w, 1000), Some(5));
        assert_eq!(widest_hint_grid(&cell_w, 5), None);
    }

    /// A "dangerous" key is drawn in the danger color; its neighbour is not.
    #[test]
    fn a_dangerous_key_gets_a_red_keycap() {
        let p = Palette::default();
        let items: &[(&str, &str, bool)] = &[("Del", "delete", true), ("Esc", "back", false)];
        let line = &hotkey_grid(&p, items, 80)[0];
        let keycap = |key: &str| {
            line.spans
                .iter()
                .find(|s| s.content.trim() == key)
                .unwrap_or_else(|| panic!("no {key} keycap"))
                .style
                .fg
        };
        assert_eq!(keycap("Del"), Some(p.keycap_danger));
        assert_eq!(keycap("Esc"), Some(p.keycap_fg));
    }

    /// Symbols of the buffer's right column (the scrollbar lives there).
    fn right_column(term: &Terminal<TestBackend>) -> Vec<String> {
        let buf = term.backend().buffer();
        let area = buf.area;
        (area.top()..area.bottom())
            .map(|y| buf[(area.right() - 1, y)].symbol().to_string())
            .collect()
    }

    /// One draw of `len` single-row items into an `h`-row area, with the
    /// selection on `selected`.
    fn draw(scroll: &mut ListScroll, len: usize, selected: usize, h: u16) {
        let mut term = Terminal::new(TestBackend::new(12, h)).unwrap();
        term.draw(|f| {
            let items: Vec<ratatui::widgets::ListItem> =
                (0..len).map(|i| format!("row {i}").into()).collect();
            let area = f.area();
            scroll.render(f, List::new(items), area, len, h as usize, Some(selected));
        })
        .unwrap();
    }

    /// The window follows the selection instead of being dragged by it: the
    /// selection crosses the visible rows first, and only a selection that has
    /// left the window moves it — the same in both directions. Guarding the
    /// helper guards every list built on it (docs/lessons.md §5).
    #[test]
    fn the_window_moves_only_when_the_selection_leaves_it() {
        let mut scroll = ListScroll::default();
        // Landing on the last item scrolls it to the bottom row.
        draw(&mut scroll, 30, 29, 10);
        assert_eq!(scroll.offset(), 20);
        // Moving up inside the window leaves the rows exactly where they were.
        draw(&mut scroll, 30, 28, 10);
        assert_eq!(scroll.offset(), 20);
        draw(&mut scroll, 30, 20, 10);
        assert_eq!(scroll.offset(), 20, "the selection is on the top row");
        // Past the top row — now, and only now, the list scrolls, by one row.
        draw(&mut scroll, 30, 19, 10);
        assert_eq!(scroll.offset(), 19);
        // Symmetrically at the other edge: down through the window, then a row.
        draw(&mut scroll, 30, 28, 10);
        assert_eq!(scroll.offset(), 19);
        draw(&mut scroll, 30, 29, 10);
        assert_eq!(scroll.offset(), 20);
    }

    /// A list that has shrunk under the stored offset (a filter, a deletion)
    /// must not leave the window hanging past its new tail — a couple of rows
    /// at the top and empty space below.
    #[test]
    fn a_shrunken_list_pulls_the_window_back_to_its_tail() {
        let mut scroll = ListScroll::default();
        draw(&mut scroll, 30, 29, 10);
        assert_eq!(scroll.offset(), 20);
        draw(&mut scroll, 12, 11, 10);
        assert_eq!(scroll.offset(), 2, "the last ten of twelve rows");
        // Shorter than the window — everything is visible from the first row.
        draw(&mut scroll, 4, 3, 10);
        assert_eq!(scroll.offset(), 0);
    }

    #[test]
    fn scrollbar_renders_thumb_only_on_overflow() {
        let palette = Palette::default();
        let mut term = Terminal::new(TestBackend::new(10, 6)).unwrap();
        // Content fits (total <= viewport) → the bar isn't drawn.
        term.draw(|f| render_scrollbar(f, f.area(), 6, 6, 0, false, &palette))
            .unwrap();
        assert!(right_column(&term).iter().all(|s| s != "█" && s != "│"));
        // Overflow → the thumb and track appear in the right column.
        term.draw(|f| render_scrollbar(f, f.area(), 24, 6, 0, false, &palette))
            .unwrap();
        let col = right_column(&term);
        assert!(col.iter().any(|s| s == "█"), "no thumb: {col:?}");
        assert!(col.iter().any(|s| s == "│"), "no track: {col:?}");
    }

    #[test]
    fn scrollbar_thumb_tracks_position() {
        // At the start the thumb is at the top, at full scroll — at the bottom.
        let palette = Palette::default();
        let mut term = Terminal::new(TestBackend::new(4, 8)).unwrap();
        let thumb_rows = |term: &Terminal<TestBackend>| -> Vec<usize> {
            right_column(term)
                .iter()
                .enumerate()
                .filter(|(_, s)| *s == "█")
                .map(|(i, _)| i)
                .collect()
        };
        term.draw(|f| render_scrollbar(f, f.area(), 32, 8, 0, false, &palette))
            .unwrap();
        let top = thumb_rows(&term);
        assert_eq!(
            top.first(),
            Some(&0),
            "thumb should be at the top initially: {top:?}"
        );
        // Full scroll: position = total - viewport.
        term.draw(|f| render_scrollbar(f, f.area(), 32, 8, 24, false, &palette))
            .unwrap();
        let bottom = thumb_rows(&term);
        assert_eq!(
            bottom.last(),
            Some(&7),
            "thumb should be at the bottom at full scroll: {bottom:?}"
        );
    }

    #[test]
    fn scrollbar_thumb_uses_border_color() {
        // The thumb is drawn in the border color (like the track), not the
        // text color. In the Auto palette `border` (DarkGray) and `text`
        // (Reset) differ, so the check is meaningful.
        let palette = Palette::default();
        let mut term = Terminal::new(TestBackend::new(4, 8)).unwrap();
        term.draw(|f| render_scrollbar(f, f.area(), 32, 8, 0, false, &palette))
            .unwrap();
        let buf = term.backend().buffer();
        let area = buf.area;
        let thumb_fg = (area.top()..area.bottom())
            .map(|y| &buf[(area.right() - 1, y)])
            .find(|c| c.symbol() == "█")
            .map(|c| c.fg);
        assert_eq!(
            thumb_fg,
            Some(palette.border),
            "thumb should be border-colored"
        );
    }

    #[test]
    fn scrollbar_zero_area_is_noop() {
        let palette = Palette::default();
        let mut term = Terminal::new(TestBackend::new(4, 4)).unwrap();
        term.draw(|f| {
            let zero = Rect::new(0, 0, 0, 0);
            render_scrollbar(f, zero, 10, 2, 0, false, &palette);
        })
        .unwrap();
    }

    #[test]
    fn prime_full_redraw_repaints_all_but_wide_glyph_tails() {
        // A gate on the sentinel's design (regression: "row drifts right on VS16").
        // Frame: a VS16 emoji with text after it — as in the feed.
        use ratatui::style::Style;
        use ratatui::text::{Line, Span};
        use ratatui::widgets::{Paragraph, Widget};
        use unicode_width::UnicodeWidthStr;

        let area = Rect::new(0, 0, 20, 2);
        let mut frame = Buffer::empty(area);
        Paragraph::new(Line::from(vec![Span::styled(
            "a 🗂\u{FE0F} хвост",
            Style::new().fg(ratatui::style::Color::Blue),
        )]))
        .render(area, &mut frame);

        let mut sentinel = frame.clone();
        prime_full_redraw(&mut sentinel);
        let updates = sentinel.diff(&frame);

        // (1) No update targets the second half of a wide glyph — otherwise
        // the backend would print it with no `MoveTo` and shift the rest of
        // the row.
        for &(x, y, _) in &updates {
            if x == 0 {
                continue;
            }
            let left = frame[(x - 1, y)].symbol();
            assert!(
                left.width() < 2,
                "update at ({x},{y}) targets the second half of glyph {left:?}"
            );
        }

        // (2) Everything else is repainted: the only uncovered cells are
        // trailing halves of wide glyphs (the glyph itself covers them) — no
        // gaps in the repaint.
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                if updates.iter().any(|&(ux, uy, _)| (ux, uy) == (x, y)) {
                    continue;
                }
                let is_tail = x > 0 && frame[(x - 1, y)].symbol().width() == 2;
                assert!(is_tail, "cell ({x},{y}) is neither repainted nor a tail");
            }
        }
    }

    #[test]
    fn screen_switch_emits_vs16_tail_without_full_redraw() {
        // Why a screen switch must go through a full redraw (`app/runtime`).
        //
        // For a VS16 cluster (`❤️` = U+2764 U+FE0F) ratatui accompanies it with a
        // trailing cell, sent WHEN ITS SYMBOL CHANGED. Within a single screen,
        // feed edits don't touch the tail (there was a space — a space it
        // stays), but on returning from another screen a foreign symbol sat in
        // its place → the tail goes out to the terminal. The backend tracks
        // position by cell number, without accounting for glyph width (open
        // ratatui#2651): no `MoveTo` is emitted after a wide glyph, and the
        // tail prints one column to the right — the rest of the row drifts
        // right. Symptom: an extra space after `❤️` when returning from the
        // chat list / `F3`, which disappears on scroll (it requests the same
        // full redraw).
        //
        // The sentinel makes the tail's symbol a space, i.e. equal to what the
        // frame will draw — the tail doesn't land in the diff and the row
        // doesn't drift.
        use ratatui::style::Style;
        use ratatui::text::{Line, Span};
        use ratatui::widgets::{Paragraph, Widget};

        let area = Rect::new(0, 0, 20, 1);
        let mut feed = Buffer::empty(area);
        Paragraph::new(Line::from(vec![Span::styled(
            "a \u{2764}\u{FE0F} tail",
            Style::new(),
        )]))
        .render(area, &mut feed);
        let gx = (0..area.width)
            .find(|&x| feed[(x, 0)].symbol().contains('\u{FE0F}'))
            .expect("VS16 glyph not found in the frame");

        // Returning from another screen: a foreign symbol sat in the tail's place.
        let mut other = Buffer::empty(area);
        Paragraph::new(Line::from("chat list content!!")).render(area, &mut other);
        assert!(
            other
                .diff(&feed)
                .iter()
                .any(|&(x, y, _)| (x, y) == (gx + 1, 0)),
            "a screen switch sends the VS16 tail — without a full redraw the row will drift"
        );

        // An edit within the same screen doesn't send the tail (which is why the
        // bug was only visible on switching, not during normal feed work).
        let mut same = feed.clone();
        same[(area.width - 1, 0)].set_symbol("Z");
        assert!(
            !same
                .diff(&feed)
                .iter()
                .any(|&(x, y, _)| (x, y) == (gx + 1, 0)),
            "an edit within the screen doesn't touch the VS16 tail"
        );

        // Full redraw: the tail isn't emitted → no shift.
        let mut sentinel = feed.clone();
        prime_full_redraw(&mut sentinel);
        assert!(
            !sentinel
                .diff(&feed)
                .iter()
                .any(|&(x, y, _)| (x, y) == (gx + 1, 0)),
            "the sentinel must not send the VS16 tail (otherwise it would shift the row itself)"
        );
    }

    #[test]
    fn sentinel_modifier_is_unused_by_ui() {
        // The marker must not occur in real frames, otherwise a matching cell
        // wouldn't land in the diff and would stay unpainted. The palette gets
        // by with DIM/BOLD/ITALIC/UNDERLINED/REVERSED — check the marker isn't
        // one of them.
        for used in [
            Modifier::DIM,
            Modifier::BOLD,
            Modifier::ITALIC,
            Modifier::UNDERLINED,
            Modifier::REVERSED,
        ] {
            assert!(
                !SENTINEL_MODIFIER.intersects(used),
                "sentinel marker intersects a modifier used in the UI {used:?}"
            );
        }
    }

    #[test]
    fn dim_background_uses_color_in_compat_mode() {
        let mut term = Terminal::new(TestBackend::new(4, 2)).unwrap();
        // Normal mode — the DIM modifier on cells.
        term.draw(|f| {
            dim_background(f, &Palette::default());
            assert!(f.buffer_mut()[(0, 0)].modifier.contains(Modifier::DIM));
        })
        .unwrap();
        // Compatibility mode — a muted color instead of DIM (conhost can't do it).
        let compat = Palette::default().with_compat(true);
        term.draw(|f| {
            dim_background(f, &compat);
            let cell = f.buffer_mut()[(0, 0)].clone();
            assert_eq!(cell.fg, compat.muted);
            assert!(!cell.modifier.contains(Modifier::DIM));
        })
        .unwrap();
    }

    /// A buffer as the rows of text it shows — for the tests that read what a
    /// widget drew, here and in the widgets.
    pub(crate) fn buffer_rows(buf: &Buffer) -> Vec<String> {
        let area = buf.area;
        (area.top()..area.bottom())
            .map(|y| {
                (area.left()..area.right())
                    .map(|x| buf[(x, y)].symbol())
                    .collect()
            })
            .collect()
    }

    /// A small frame holding one of everything the pass has to tell apart: bare
    /// text, a role colour, a selection backdrop, reverse video, a wide glyph
    /// and empty cells.
    fn mixed_frame(palette: &Palette) -> Buffer {
        use ratatui::widgets::Widget;
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = Buffer::empty(area);
        Paragraph::new(vec![
            Line::from(vec![
                Span::raw("bare "),
                Span::styled("role", Style::new().fg(palette.user)),
            ]),
            Line::from(vec![
                Span::styled("sel", Style::new().bg(palette.keycap_bg)),
                Span::styled(" rev", Style::new().add_modifier(Modifier::REVERSED)),
            ]),
            Line::from("a 😀 b"),
        ])
        .render(area, &mut buf);
        buf
    }

    #[test]
    fn the_system_mode_leaves_the_frame_alone() {
        // The regression guard for the default: no canvas, no pass — the
        // buffer is what the widgets drew, cell for cell.
        for theme in [
            crate::shared::config::Theme::Auto,
            crate::shared::config::Theme::Dark,
            crate::shared::config::Theme::Light,
        ] {
            let palette = Palette::for_theme(theme);
            let drawn = mixed_frame(&palette);
            let mut painted = drawn.clone();
            paint_canvas(&mut painted, &palette);
            assert_eq!(painted, drawn, "{theme:?}");
        }
    }

    #[test]
    fn the_full_mode_fills_what_the_widgets_left_at_the_default() {
        for name in crate::shared::theme::FULL_THEMES {
            let palette = Palette::full(name);
            let drawn = mixed_frame(&palette);
            let mut painted = drawn.clone();
            paint_canvas(&mut painted, &palette);

            for (before, after) in drawn.content.iter().zip(&painted.content) {
                // Nothing is left for the terminal to colour — the empty cells
                // and a wide glyph's trailing cell included.
                assert_ne!(after.bg, Color::Reset, "{name}: {:?}", after.symbol());
                assert_ne!(after.fg, Color::Reset, "{name}: {:?}", after.symbol());
                // A colour a widget chose is kept; only the default is filled.
                let want_bg = if before.bg == Color::Reset {
                    palette.canvas
                } else {
                    before.bg
                };
                let want_fg = if before.fg == Color::Reset {
                    palette.text
                } else {
                    before.fg
                };
                assert_eq!((after.fg, after.bg), (want_fg, want_bg), "{name}");
                // The text and its attributes are none of the pass's business.
                assert_eq!(after.symbol(), before.symbol(), "{name}");
                assert_eq!(after.modifier, before.modifier, "{name}");
            }
            // The three cases by name, so a vacuous loop cannot pass for them.
            let cell = |x: u16, y: u16| &painted[(x, y)];
            assert_eq!(cell(0, 0).fg, palette.text, "{name}: bare text");
            assert_eq!(cell(5, 0).fg, palette.user, "{name}: a role colour");
            assert_eq!(cell(0, 1).bg, palette.keycap_bg, "{name}: the backdrop");
            assert!(cell(4, 1).modifier.contains(Modifier::REVERSED), "{name}");
            assert_eq!(cell(11, 2).bg, palette.canvas, "{name}: an empty cell");
        }
    }

    #[test]
    fn a_popup_cleared_over_the_frame_gets_the_canvas_back() {
        // The case a base style under the widgets would have missed: `Clear`
        // resets its area to the terminal's default, and the popup drawn into
        // it would sit on the terminal's background in the middle of the
        // canvas. The pass runs after it.
        use ratatui::widgets::{Block, Widget};
        let palette = Palette::full("light");
        let mut buf = mixed_frame(&palette);
        paint_canvas(&mut buf, &palette);
        let popup = Rect::new(2, 0, 6, 3);
        Clear.render(popup, &mut buf);
        Block::bordered().render(popup, &mut buf);
        assert_eq!(buf[(3, 1)].bg, Color::Reset, "the premise: Clear resets");
        paint_canvas(&mut buf, &palette);
        assert!(buf.content.iter().all(|c| c.bg != Color::Reset));
    }

    #[test]
    fn the_monochrome_pass_leaves_nothing_but_the_mark() {
        use crate::shared::theme::MONO_MARK;
        use ratatui::widgets::Widget;
        let palette = Palette::mono();
        let mut buf = mixed_frame(&palette);
        // What the two marks draw, on top of whatever styling was under them
        // — and an attribute the frame above does not have.
        Paragraph::new(Line::from(vec![
            Span::styled(
                "m",
                palette.search_match(Style::new().bold().fg(Color::Red)),
            ),
            Span::styled("s", palette.selection(Style::new().underlined())),
            Span::styled("u", Style::new().underlined().underline_color(Color::Red)),
        ]))
        .render(Rect::new(8, 2, 3, 1), &mut buf);
        let drawn = buf.clone();
        assert_eq!(drawn[(8, 2)].bg, MONO_MARK, "the premise: a mark is drawn");
        assert!(drawn[(4, 1)].modifier.contains(Modifier::REVERSED));

        strip_styles(&mut buf, &palette);

        for (before, after) in drawn.content.iter().zip(&buf.content) {
            let what = before.symbol();
            assert_eq!(after.symbol(), what, "the text is not the pass's");
            assert_eq!(after.fg, Color::Reset, "{what:?}");
            assert_eq!(after.bg, Color::Reset, "{what:?}");
            assert_eq!(after.underline_color, Color::Reset, "{what:?}");
            let want = if before.bg == MONO_MARK {
                Modifier::REVERSED
            } else {
                Modifier::empty()
            };
            assert_eq!(after.modifier, want, "{what:?}");
        }
        // By name, so a vacuous loop cannot pass for them: the two marks are
        // reverse video and nothing else…
        assert_eq!(buf[(8, 2)].modifier, Modifier::REVERSED, "a search match");
        assert_eq!(buf[(9, 2)].modifier, Modifier::REVERSED, "a selection");
        // …and reverse video a widget set by hand is gone with the rest.
        assert_eq!(buf[(4, 1)].modifier, Modifier::empty(), "a popup's row");
        assert_eq!(buf[(0, 1)].bg, Color::Reset, "the selection backdrop");
    }

    #[test]
    fn only_the_monochrome_mode_is_stripped() {
        let mut palettes = vec![Palette::default()];
        palettes.extend(crate::shared::theme::FULL_THEMES.map(Palette::full));
        for palette in palettes {
            let drawn = mixed_frame(&palette);
            let mut passed = drawn.clone();
            strip_styles(&mut passed, &palette);
            assert_eq!(passed, drawn);
            // The two passes in one call: what the canvas does, and no more.
            let mut finished = drawn.clone();
            finish_frame(&mut finished, &palette);
            let mut painted = drawn.clone();
            paint_canvas(&mut painted, &palette);
            assert_eq!(finished, painted);
        }
        let mono = Palette::mono();
        let mut finished = mixed_frame(&mono);
        finish_frame(&mut finished, &mono);
        assert!(
            finished
                .content
                .iter()
                .all(|c| c.fg == Color::Reset && c.bg == Color::Reset && c.modifier.is_empty()),
            "the monochrome palette paints no canvas and is stripped"
        );
    }

    #[test]
    fn a_popup_over_the_frame_is_stripped_with_it() {
        // The pass runs after the overlay, so a dimmed background and a
        // popup's own styling go the same way as the screen's.
        use ratatui::widgets::{Block, Widget};
        let palette = Palette::mono();
        let mut buf = mixed_frame(&palette);
        for cell in buf.content.iter_mut() {
            cell.modifier |= Modifier::DIM; // what `dim_background` does
        }
        let popup = Rect::new(2, 0, 6, 3);
        Clear.render(popup, &mut buf);
        Block::bordered()
            .border_style(palette.border_style(true))
            .render(popup, &mut buf);
        strip_styles(&mut buf, &palette);
        assert!(buf.content.iter().all(|c| c.modifier.is_empty()));
        assert!(buf.content.iter().all(|c| c.fg == Color::Reset));
        assert_eq!(buf[(2, 0)].symbol(), "┌", "the border is what is left");
    }

    #[test]
    fn a_list_gets_its_marker_only_in_the_monochrome_mode() {
        use ratatui::widgets::StatefulWidget;
        let rows = |palette: &Palette| -> Vec<String> {
            let area = Rect::new(0, 0, 8, 3);
            let mut buf = Buffer::empty(area);
            let list = mark_selected(
                List::new(["one", "two", "three"]).highlight_style(Style::new().reversed()),
                palette,
            );
            let mut state = ListState::default().with_selected(Some(1));
            StatefulWidget::render(list, area, &mut buf, &mut state);
            buffer_rows(&buf)
        };
        assert_eq!(
            rows(&Palette::default()),
            ["one     ", "two     ", "three   "]
        );
        // The rows do not shift as the selection moves: the unselected ones
        // are indented by the marker's width.
        assert_eq!(rows(&Palette::mono()), ["  one   ", "› two   ", "  three "]);
    }

    #[test]
    fn the_erase_sets_the_canvas_and_the_reset_gives_it_back() {
        // The exact bytes: 24-bit background, erase display, reset.
        let canvas = crate::shared::theme::CANVAS_DARK;
        assert_eq!(set_background(canvas), "\x1b[48;2;15;17;21m");
        assert_eq!(ERASE_SCREEN, "\x1b[2J");
        assert_eq!(RESET_STYLE, "\x1b[0m");
        // Going back to the system mode erases with the terminal's own
        // background, which is what is current when nothing was set.
        assert_eq!(set_background(Color::Reset), "");
        // A named colour is not a canvas: nothing is written rather than a
        // shade the terminal would pick.
        assert_eq!(set_background(Color::Blue), "");
    }

    const FRAMES: &[char] = &['a', 'b', 'c'];

    fn ms(n: u64) -> Duration {
        Duration::from_millis(n)
    }

    #[test]
    fn a_spinner_steps_with_time_not_with_frames() {
        let t0 = Instant::now();
        let mut s = Spinner::started_at(t0);
        // However many frames are drawn within one step, they show one glyph —
        // a repaint someone else asked for does not speed the spin up.
        for _ in 0..5 {
            assert_eq!(s.glyph_at(FRAMES, t0), 'a');
        }
        assert_eq!(s.glyph_at(FRAMES, t0 + SPINNER_STEP - ms(1)), 'a');
        assert_eq!(s.glyph_at(FRAMES, t0 + SPINNER_STEP), 'b');
        assert_eq!(s.glyph_at(FRAMES, t0 + SPINNER_STEP * 2), 'c');
        assert_eq!(s.glyph_at(FRAMES, t0 + SPINNER_STEP * 3), 'a', "wraps");
    }

    #[test]
    fn a_spinner_is_due_only_when_its_glyph_would_change() {
        let t0 = Instant::now();
        let mut s = Spinner::started_at(t0);
        assert!(s.due_at(t0), "never drawn — the first frame is due");
        s.glyph_at(FRAMES, t0);
        // The idle ticks inside a step write nothing to the terminal.
        assert!(!s.due_at(t0 + ms(50)));
        assert!(!s.due_at(t0 + SPINNER_STEP - ms(1)));
        assert!(s.due_at(t0 + SPINNER_STEP), "the next glyph is due");
        // Drawn late in its step (the loop draws on its next tick), the glyph
        // is due again at the step's boundary, not a whole step after the draw.
        s.glyph_at(FRAMES, t0 + SPINNER_STEP + ms(40));
        assert!(!s.due_at(t0 + SPINNER_STEP * 2 - ms(1)));
        assert!(s.due_at(t0 + SPINNER_STEP * 2));
    }
}