summaryrefslogtreecommitdiff
path: root/src/tui_components.zig
blob: b2ed842d376e5d9212037464499ef7a26141bc36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
//! Built-in P1 components for the TUI (plan §6).
//!
//! Each component satisfies the `Component` vtable (`tui_component.zig`) and
//! implements the cache-derived dirty model exactly as `RenderCache` defines
//! it: any state mutation calls `markDirty`/`markDirtyFrom` (drops the cache),
//! and a successful `render` calls `cache.store(lines)` (diffs the new lines
//! against the prior cache, records the lowest differing index, re-populates
//! the cache, and marks it clean). `firstLineChanged` is therefore derived
//! purely from cache state and never a hand-managed integer that can drift.
//!
//! Data-in / lines-out: each component takes STRUCTURED DATA IN via setters or
//! delta-appenders and produces LINES OUT from `render(width, alloc)`. Every
//! returned line's visible width is <= `width` (we TRUNCATE; the engine treats
//! overflow as a hard error per plan §3.1).
//!
//! Render storage convention: a component renders into a transient list, calls
//! `cache.store(lines)` (which dupes the bytes into cache-owned storage), then
//! returns `cache.lines` re-typed as `[]const []const u8`. The returned slices
//! are owned by the cache and stay valid until the next `render`/`invalidate`
//! — satisfying the vtable's lifetime contract.

const std = @import("std");
const component = @import("tui_component.zig");
const theme = @import("tui_theme.zig");
const input = @import("tui_input.zig");
const key = @import("tui_key.zig");

const Component = component.Component;
const Focusable = component.Focusable;
const RenderCache = component.RenderCache;
const CURSOR_MARKER = component.CURSOR_MARKER;
const Style = theme.Style;
const Key = key.Key;
const KeyCode = key.KeyCode;

// ===========================================================================
// Shared helpers
// ===========================================================================

/// Number of display columns occupied by `text`, counted as one column per
/// UTF-8 codepoint. `text` here is assumed to be PLAIN (no escape sequences);
/// components wrap on plain text and only add styling escapes afterward, so
/// this is a faithful visible width. Mirrors the engine's P1 approximation
/// (1 col per codepoint; wide CJK/emoji width is a deferred refinement).
pub fn displayWidth(text: []const u8) usize {
    var cols: usize = 0;
    var i: usize = 0;
    while (i < text.len) {
        const seq_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1;
        cols += 1;
        i += @min(seq_len, text.len - i);
    }
    return cols;
}

/// Truncate `text` to at most `max_cols` display columns, returning a byte
/// slice of `text` that ends on a codepoint boundary. Never splits a multibyte
/// codepoint.
pub fn truncateToCols(text: []const u8, max_cols: usize) []const u8 {
    var cols: usize = 0;
    var i: usize = 0;
    while (i < text.len and cols < max_cols) {
        const seq_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1;
        const adv = @min(seq_len, text.len - i);
        i += adv;
        cols += 1;
    }
    return text[0..i];
}

/// Wrap `text` (a single logical paragraph, no embedded newlines) into lines of
/// at most `width` display columns, appending each produced line to `out`.
/// Greedy word-wrap on ASCII spaces; a word longer than `width` is hard-split.
/// An empty paragraph yields one empty line. Lines pushed to `out` are slices
/// borrowed from `text` (no allocation of line bytes here; `out` only stores
/// the slice headers).
fn wrapParagraph(text: []const u8, width: usize, out: *std.ArrayList([]const u8), alloc: std.mem.Allocator) !void {
    if (width == 0) {
        try out.append(alloc, "");
        return;
    }
    if (text.len == 0) {
        try out.append(alloc, "");
        return;
    }

    // Greedy word-wrap. We accumulate a line by byte range [line_start, i); on
    // overflow we break at the last space that fits, or hard-split a word that
    // is wider than `width`.
    var line_start: usize = 0;
    var line_cols: usize = 0;
    var last_break: ?usize = null; // byte index of the last space on this line
    var i: usize = 0;

    while (i < text.len) {
        const seq_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1;
        const adv = @min(seq_len, text.len - i);
        const is_space = adv == 1 and text[i] == ' ';

        if (is_space and line_cols == width) {
            // The overflowing glyph is the inter-word space itself: break here
            // and consume the space (standard word-wrap discards it) so the
            // current word group fills the line exactly.
            try out.append(alloc, text[line_start..i]);
            line_start = i + adv;
            last_break = null;
            line_cols = 0;
            i += adv;
            continue;
        }
        if (line_cols + 1 > width) {
            // Adding this glyph would overflow; break the line first.
            if (last_break) |brk| {
                // Break at the last space: emit up to (not including) it, and
                // start the next line just after it.
                try out.append(alloc, text[line_start..brk]);
                line_start = brk + 1;
                last_break = null;
                line_cols = displayWidth(text[line_start..i]);
            } else {
                // No space on this line: hard-split before the current glyph.
                try out.append(alloc, text[line_start..i]);
                line_start = i;
                line_cols = 0;
            }
        }

        if (is_space) last_break = i;
        line_cols += 1;
        i += adv;
    }
    // Flush the final line (always emit, even if empty/trailing fragment).
    try out.append(alloc, text[line_start..]);
}

/// Split `buffer` on newlines into paragraphs and wrap each to `width`,
/// appending all produced lines to `out`. A trailing newline produces a final
/// empty line (so a freshly-typed "\n" shows a blank row). An empty buffer
/// produces no lines.
fn wrapBuffer(buffer: []const u8, width: usize, out: *std.ArrayList([]const u8), alloc: std.mem.Allocator) !void {
    if (buffer.len == 0) return;
    var it = std.mem.splitScalar(u8, buffer, '\n');
    while (it.next()) |para| {
        try wrapParagraph(para, width, out, alloc);
    }
}

/// Build the cache-owned line set for a styled text block: each wrapped plain
/// line is wrapped in `style.open()`/`style.close()` and stored via the cache.
/// Returns the cache's owned lines re-typed for the vtable.
///
/// `width` bounds the *visible* width: the plain text is truncated to `width`
/// columns BEFORE styling escapes are added (escapes are zero visible width).
fn renderStyledLines(
    cache: *RenderCache,
    buffer: []const u8,
    style: Style,
    width: usize,
    alloc: std.mem.Allocator,
) ![]const []const u8 {
    // 1. Wrap plain text into borrowed slices.
    var plain: std.ArrayList([]const u8) = .empty;
    defer plain.deinit(alloc);
    try wrapBuffer(buffer, width, &plain, alloc);

    // 2. Style each line into a transient owned buffer.
    var styled: std.ArrayList([]const u8) = .empty;
    defer {
        for (styled.items) |s| alloc.free(s);
        styled.deinit(alloc);
    }
    for (plain.items) |line| {
        // Defensive truncate (wrap already bounds it, but a hard contract).
        const vis = truncateToCols(line, width);
        const composed = try std.fmt.allocPrint(alloc, "{s}{s}{s}", .{ style.open(), vis, style.close() });
        try styled.append(alloc, composed);
    }

    // 3. Commit to the cache (dupes), then return the cache's owned copy.
    try cache.store(styled.items);
    return cacheLines(cache);
}

/// Re-type the cache's owned `[][]u8` lines as `[]const []const u8` for the
/// vtable return. The cache guarantees these outlive the call until the next
/// render/invalidate.
fn cacheLines(cache: *RenderCache) []const []const u8 {
    const owned = cache.lines orelse return &.{};
    return @ptrCast(owned);
}

// ===========================================================================
// AssistantText — streaming assistant message (plan §6, §8)
// ===========================================================================

/// Accumulates assistant content deltas into an internal buffer and renders
/// the wrapped text with the theme's assistant style.
///
/// Streaming-tail dirty model (plan §3.3): a delta is appended to the buffer
/// and the cache is marked dirty; the engine then requests a render. Because
/// appended text only changes the LAST wrapped line(s) and leaves earlier
/// wrapped lines byte-identical, `RenderCache.store`'s diff naturally reports
/// `firstLineChanged` near the TAIL, not line 0 — the cut stays near the end
/// during streaming. (There is no per-delta render method on the interface;
/// the delta just mutates state + dirties, per plan §8.)
///
/// Markdown hosting (plan §8, DEFERRED): the buffer/render are structured so a
/// later pass can cache finished blocks and only re-render the last open block.
/// For P1 this is plain text + word wrap; the tail-near firstLineChanged
/// property already holds via the cache diff, so the markdown upgrade slots in
/// without changing the dirty model.
pub const AssistantText = struct {
    alloc: std.mem.Allocator,
    buffer: std.ArrayList(u8) = .empty,
    cache: RenderCache,

    pub fn init(alloc: std.mem.Allocator) AssistantText {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *AssistantText) void {
        self.buffer.deinit(self.alloc);
        self.cache.deinit();
    }

    /// Append a streaming content delta. Mutates the buffer and marks the cache
    /// dirty (the engine will requestRender). The cache diff keeps
    /// firstLineChanged near the tail.
    pub fn appendDelta(self: *AssistantText, delta: []const u8) !void {
        try self.buffer.appendSlice(self.alloc, delta);
        // markDirtyAppend RETAINS the baseline so the post-render diff recovers
        // the true tail change point; while dirty it reports a tail hint, so
        // the engine's cut stays near the end during streaming (plan §3.3/§8).
        self.cache.markDirtyAppend();
    }

    /// Replace the whole buffer (e.g. a non-streaming set). Marks dirty.
    pub fn setText(self: *AssistantText, text: []const u8) !void {
        self.buffer.clearRetainingCapacity();
        try self.buffer.appendSlice(self.alloc, text);
        self.cache.markDirty();
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *AssistantText = @ptrCast(@alignCast(ptr));
        return renderStyledLines(&self.cache, self.buffer.items, theme.default.fg(.assistant), width, self.alloc);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *AssistantText = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *AssistantText = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *AssistantText) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// UserText — submitted user message (plan §6)
// ===========================================================================

/// A submitted user message, rendered with the theme's user style. Static once
/// set; `setText` replaces it and marks dirty.
pub const UserText = struct {
    alloc: std.mem.Allocator,
    buffer: std.ArrayList(u8) = .empty,
    cache: RenderCache,

    pub fn init(alloc: std.mem.Allocator) UserText {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *UserText) void {
        self.buffer.deinit(self.alloc);
        self.cache.deinit();
    }

    /// Set the (static) message text. Marks dirty.
    pub fn setText(self: *UserText, text: []const u8) !void {
        self.buffer.clearRetainingCapacity();
        try self.buffer.appendSlice(self.alloc, text);
        self.cache.markDirty();
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *UserText = @ptrCast(@alignCast(ptr));
        return renderStyledLines(&self.cache, self.buffer.items, theme.default.fg(.user), width, self.alloc);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *UserText = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *UserText = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *UserText) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// InputBox — editable single-row+ input (plan §6, §3.5)
// ===========================================================================

/// A `Focusable` editor. Single row by default; ENTER submits, SHIFT+ENTER
/// inserts a newline (grows one row per line). Growth is UNBOUNDED in P1 (the
/// cap + scroll-window is deferred to P2).
///
/// Editing (raw keys via `handleInput`, decoded by `tui_input`):
///   - printable chars (UTF-8) insert at the cursor
///   - backspace deletes the codepoint before the cursor
///   - delete removes the codepoint at the cursor
///   - left/right move by one codepoint; home/end jump to start/end of the
///     current visual buffer (P1: whole buffer, not per-line)
///   - ENTER submits the whole buffer (see "Submit mechanism")
///   - SHIFT+ENTER inserts a '\n'
///
/// Cursor (plan §3.5): the box draws its OWN cursor as a reverse-video block
/// (theme `.cursor` style) over the glyph at the cursor position. When focused
/// it also emits `CURSOR_MARKER` (zero visible width) at the cursor location in
/// its render output, so the engine can later position the hardware cursor.
///
/// SHIFT+ENTER limitation: on terminals without the Kitty protocol, Enter and
/// Shift+Enter send identical bytes (`\r`); the decoder cannot distinguish them
/// and both arrive as `.enter` with no shift modifier, so only plain submit is
/// possible there. When Kitty IS active, Shift+Enter arrives as CSI-u
/// (`\x1b[13;2u`) with `mods.shift` set and this box inserts a newline. The
/// logic works wherever the distinction is available.
///
/// Submit mechanism: a POLLABLE buffer. On ENTER the current editor contents
/// are moved into `submitted` and the editor is cleared. The app calls
/// `takeSubmitted()` once per frame; it returns the submitted bytes (owned by
/// the box, valid until the next `takeSubmitted`/edit) and clears the pending
/// flag, or null if nothing was submitted. This avoids callback re-entrancy
/// into the render loop.
pub const InputBox = struct {
    alloc: std.mem.Allocator,
    focusable: Focusable = .{},
    /// Editor contents (may contain '\n' for multi-line input). UTF-8.
    text: std.ArrayList(u8) = .empty,
    /// Cursor position as a BYTE offset into `text` (always on a codepoint
    /// boundary).
    cursor: usize = 0,
    /// Pending submitted line, owned by the box. Valid until the next submit
    /// or `takeSubmitted`.
    submitted: std.ArrayList(u8) = .empty,
    has_submitted: bool = false,
    /// Maximum number of VISUAL rows the box renders at once (plan §6 / P2).
    /// When the wrapped/`\n`-split buffer exceeds this many rows, the box
    /// renders only a `line_cap`-tall SCROLL-WINDOW that follows the cursor
    /// (so the cursor row stays visible). The default is 8. A single-row
    /// buffer still renders one row — the cap is a ceiling, not a floor, so
    /// the existing "single-row default, grow one row per line" behavior is
    /// preserved up to the cap.
    line_cap: usize = default_line_cap,
    cache: RenderCache,

    /// Default visual-row cap (plan §6, P2): show at most the last 8 contiguous
    /// lines once the buffer grows past the window.
    pub const default_line_cap: usize = 8;

    pub fn init(alloc: std.mem.Allocator) InputBox {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *InputBox) void {
        self.text.deinit(self.alloc);
        self.submitted.deinit(self.alloc);
        self.cache.deinit();
    }

    // -- focus -------------------------------------------------------------

    /// Set focus. Re-dirties because the cursor block + marker only render when
    /// focused, so focus changes alter the output.
    pub fn setFocused(self: *InputBox, value: bool) void {
        if (self.focusable.focused != value) {
            self.focusable.setFocused(value);
            self.cache.markDirty();
        }
    }

    pub fn isFocused(self: *const InputBox) bool {
        return self.focusable.focused;
    }

    // -- submit polling ----------------------------------------------------

    /// Poll the submitted line. Returns the bytes (box-owned) and clears the
    /// pending flag, or null if nothing was submitted since the last poll.
    pub fn takeSubmitted(self: *InputBox) ?[]const u8 {
        if (!self.has_submitted) return null;
        self.has_submitted = false;
        return self.submitted.items;
    }

    // -- buffer access (for the Ctrl+G $EDITOR round-trip) -----------------

    /// The current editor contents (box-owned; valid until the next edit).
    /// Used by the app's Ctrl+G handler to seed the external-editor tempfile.
    pub fn buffer(self: *const InputBox) []const u8 {
        return self.text.items;
    }

    /// Replace the whole editor buffer (e.g. with text edited in `$EDITOR`).
    /// Places the cursor at the end and marks dirty.
    pub fn setBuffer(self: *InputBox, bytes: []const u8) !void {
        self.text.clearRetainingCapacity();
        try self.text.appendSlice(self.alloc, bytes);
        self.cursor = self.text.items.len;
        self.cache.markDirty();
    }

    // -- editing primitives (also directly unit-testable) ------------------

    fn insertText(self: *InputBox, bytes: []const u8) !void {
        try self.text.insertSlice(self.alloc, self.cursor, bytes);
        self.cursor += bytes.len;
        self.cache.markDirty();
    }

    fn backspace(self: *InputBox) void {
        if (self.cursor == 0) return;
        const start = self.prevBoundary(self.cursor);
        const removed = self.cursor - start;
        std.mem.copyForwards(u8, self.text.items[start..], self.text.items[self.cursor..]);
        self.text.items.len -= removed;
        self.cursor = start;
        self.cache.markDirty();
    }

    fn deleteForward(self: *InputBox) void {
        if (self.cursor >= self.text.items.len) return;
        const next = self.nextBoundary(self.cursor);
        const removed = next - self.cursor;
        std.mem.copyForwards(u8, self.text.items[self.cursor..], self.text.items[next..]);
        self.text.items.len -= removed;
        self.cache.markDirty();
    }

    fn moveLeft(self: *InputBox) void {
        if (self.cursor == 0) return;
        self.cursor = self.prevBoundary(self.cursor);
        self.cache.markDirty();
    }

    fn moveRight(self: *InputBox) void {
        if (self.cursor >= self.text.items.len) return;
        self.cursor = self.nextBoundary(self.cursor);
        self.cache.markDirty();
    }

    fn moveHome(self: *InputBox) void {
        if (self.cursor == 0) return;
        self.cursor = 0;
        self.cache.markDirty();
    }

    fn moveEnd(self: *InputBox) void {
        if (self.cursor == self.text.items.len) return;
        self.cursor = self.text.items.len;
        self.cache.markDirty();
    }

    /// Byte index of the start of the current LOGICAL line (the byte just after
    /// the previous '\n', or 0). "Logical line" = a run delimited by '\n' in
    /// the buffer, independent of visual wrapping.
    fn lineStart(self: *const InputBox, at: usize) usize {
        if (at == 0) return 0;
        if (std.mem.lastIndexOfScalar(u8, self.text.items[0..at], '\n')) |nl| return nl + 1;
        return 0;
    }

    /// Byte index of the end of the current LOGICAL line (the next '\n' at or
    /// after `at`, or the buffer end).
    fn lineEnd(self: *const InputBox, at: usize) usize {
        if (std.mem.indexOfScalarPos(u8, self.text.items, at, '\n')) |nl| return nl;
        return self.text.items.len;
    }

    /// Move the cursor to the start of the current logical line (Ctrl+A).
    fn moveLineStart(self: *InputBox) void {
        const dest = self.lineStart(self.cursor);
        if (dest == self.cursor) return;
        self.cursor = dest;
        self.cache.markDirty();
    }

    /// Move the cursor to the end of the current logical line (Ctrl+E).
    fn moveLineEnd(self: *InputBox) void {
        const dest = self.lineEnd(self.cursor);
        if (dest == self.cursor) return;
        self.cursor = dest;
        self.cache.markDirty();
    }

    /// Whether the codepoint starting at byte `i` is "word" whitespace for
    /// word-motion. We treat ASCII spaces, tabs, and newlines as separators.
    fn isWordSep(self: *const InputBox, i: usize) bool {
        const b = self.text.items[i];
        return b == ' ' or b == '\t' or b == '\n';
    }

    /// Byte index one word to the LEFT of `from` (standard word-motion: skip a
    /// run of separators, then a run of non-separators). Returns 0 at the
    /// start. Operates on codepoint boundaries.
    fn prevWord(self: *const InputBox, from: usize) usize {
        var i = from;
        // Skip separators immediately to the left.
        while (i > 0) {
            const p = self.prevBoundary(i);
            if (!self.isWordSep(p)) break;
            i = p;
        }
        // Skip the word (non-separators) to the left.
        while (i > 0) {
            const p = self.prevBoundary(i);
            if (self.isWordSep(p)) break;
            i = p;
        }
        return i;
    }

    /// Byte index one word to the RIGHT of `from` (skip a run of non-separators,
    /// then a run of separators). Returns the buffer end at the end. Operates on
    /// codepoint boundaries.
    fn nextWord(self: *const InputBox, from: usize) usize {
        var i = from;
        const len = self.text.items.len;
        // Skip the word (non-separators) to the right.
        while (i < len and !self.isWordSep(i)) i = self.nextBoundary(i);
        // Skip trailing separators.
        while (i < len and self.isWordSep(i)) i = self.nextBoundary(i);
        return i;
    }

    /// Move one word left (Alt+Left / Ctrl+Left).
    fn moveWordLeft(self: *InputBox) void {
        if (self.cursor == 0) return;
        self.cursor = self.prevWord(self.cursor);
        self.cache.markDirty();
    }

    /// Move one word right (Alt+Right / Ctrl+Right).
    fn moveWordRight(self: *InputBox) void {
        if (self.cursor >= self.text.items.len) return;
        self.cursor = self.nextWord(self.cursor);
        self.cache.markDirty();
    }

    /// Delete from the cursor back to the start of the current logical line
    /// (Ctrl+U). A PLAIN delete — no kill-ring / yank buffer is kept.
    fn deleteToLineStart(self: *InputBox) void {
        const start = self.lineStart(self.cursor);
        if (start == self.cursor) return;
        const removed = self.cursor - start;
        std.mem.copyForwards(u8, self.text.items[start..], self.text.items[self.cursor..]);
        self.text.items.len -= removed;
        self.cursor = start;
        self.cache.markDirty();
    }

    /// Delete the previous word (Ctrl+W). A PLAIN delete — no kill-ring.
    fn deletePrevWord(self: *InputBox) void {
        if (self.cursor == 0) return;
        const start = self.prevWord(self.cursor);
        if (start == self.cursor) return;
        const removed = self.cursor - start;
        std.mem.copyForwards(u8, self.text.items[start..], self.text.items[self.cursor..]);
        self.text.items.len -= removed;
        self.cursor = start;
        self.cache.markDirty();
    }

    fn submit(self: *InputBox) !void {
        self.submitted.clearRetainingCapacity();
        try self.submitted.appendSlice(self.alloc, self.text.items);
        self.has_submitted = true;
        self.text.clearRetainingCapacity();
        self.cursor = 0;
        self.cache.markDirty();
    }

    /// Byte index of the codepoint boundary before `i` (i > 0).
    fn prevBoundary(self: *const InputBox, i: usize) usize {
        var j = i - 1;
        while (j > 0 and isContinuation(self.text.items[j])) : (j -= 1) {}
        return j;
    }

    /// Byte index of the next codepoint boundary after `i` (i < len).
    fn nextBoundary(self: *const InputBox, i: usize) usize {
        const seq_len = std.unicode.utf8ByteSequenceLength(self.text.items[i]) catch 1;
        return @min(i + seq_len, self.text.items.len);
    }

    fn isContinuation(b: u8) bool {
        return (b & 0xc0) == 0x80;
    }

    // -- input handling ----------------------------------------------------

    /// Apply one decoded key. Split out so tests can drive editing without raw
    /// byte sequences.
    pub fn applyKey(self: *InputBox, k: Key) !void {
        if (k.event == .release) return;
        switch (k.code) {
            .char => {
                // Ctrl/Alt chord bindings (standard editing shortcuts). These
                // are handled BEFORE the printable-insert path, which rejects
                // modified chars. NONE of these keep a kill-ring / yank buffer
                // — they are plain moves/deletes (plan P2: no kill-ring/undo).
                if (k.mods.ctrl and !k.mods.alt and !k.mods.super) {
                    switch (std.ascii.toLower(@intCast(k.code.char & 0x7f))) {
                        'u' => {
                            self.deleteToLineStart(); // delete to line start
                            return;
                        },
                        'w' => {
                            self.deletePrevWord(); // delete previous word
                            return;
                        },
                        'a' => {
                            self.moveLineStart(); // start of line
                            return;
                        },
                        'e' => {
                            self.moveLineEnd(); // end of line
                            return;
                        },
                        else => return, // other ctrl chords: ignore (Ctrl+G
                        // handled at the app level, never reaches the box).
                    }
                }
                // Alt-chord word bindings. Many terminals (notably Ghostty
                // and macOS terminals) send Alt+Left/Right as the classic
                // readline `ESC b` / `ESC f` rather than a modified arrow CSI,
                // so they arrive here as alt+b / alt+f char keys. Map them to
                // the same word-motion as Alt/Ctrl+Arrow so word navigation
                // works regardless of which form the terminal emits.
                if (k.mods.alt and !k.mods.ctrl and !k.mods.super) {
                    switch (std.ascii.toLower(@intCast(k.code.char & 0x7f))) {
                        'b' => {
                            self.moveWordLeft();
                            return;
                        },
                        'f' => {
                            self.moveWordRight();
                            return;
                        },
                        else => return, // other alt chords: ignore (not text)
                    }
                }
                if (k.mods.alt or k.mods.super) return; // not a printable insert
                if (k.text) |t| {
                    try self.insertText(t);
                } else {
                    // Encode the codepoint ourselves when no text was carried.
                    var buf: [4]u8 = undefined;
                    const n = std.unicode.utf8Encode(k.code.char, &buf) catch return;
                    try self.insertText(buf[0..n]);
                }
            },
            .enter => {
                if (k.mods.shift) {
                    try self.insertText("\n"); // shift+enter newline
                } else {
                    try self.submit();
                }
            },
            // Alt/Ctrl+Backspace deletes the previous word (readline
            // convention); plain Backspace deletes one codepoint.
            .backspace => if (k.mods.alt or k.mods.ctrl) self.deletePrevWord() else self.backspace(),
            .delete => self.deleteForward(),
            // Word-motion: Alt+Left/Right (xterm/kitty) and Ctrl+Left/Right
            // (many terminals send `1;5D`/`1;5C`). Plain Left/Right move by one
            // codepoint.
            .left => if (k.mods.alt or k.mods.ctrl) self.moveWordLeft() else self.moveLeft(),
            .right => if (k.mods.alt or k.mods.ctrl) self.moveWordRight() else self.moveRight(),
            .home => self.moveHome(),
            .end => self.moveEnd(),
            else => {}, // tab, arrows up/down, fkeys: ignored
        }
    }

    fn handleInputImpl(ptr: *anyopaque, data: []const u8) void {
        const self: *InputBox = @ptrCast(@alignCast(ptr));
        var off: usize = 0;
        while (off < data.len) {
            const step = input.decodeOne(data[off..]) orelse break; // partial tail: drop in P1
            off += step.consumed;
            switch (step.decoded) {
                .key => |k| self.applyKey(k) catch return,
                .paste => |p| self.insertText(p) catch return,
                // Negotiation replies are consumed by the app before input is
                // routed here; ignore defensively if one slips through.
                .negotiation => {},
            }
        }
    }

    // -- render ------------------------------------------------------------

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *InputBox = @ptrCast(@alignCast(ptr));
        return self.renderLines(width);
    }

    /// Render the editor: split on '\n' into visual rows, place the styled
    /// cursor block + CURSOR_MARKER at the cursor row/column when focused.
    /// Truncates each row to `width` columns.
    ///
    /// Scroll-window (plan §6, P2): when the buffer produces more than
    /// `line_cap` rows, only a `line_cap`-tall window is rendered. The window
    /// FOLLOWS the cursor — it always contains the cursor's row — and defaults
    /// to the LAST `line_cap` rows (so a freshly grown buffer shows its tail,
    /// where the cursor usually is). A single-row buffer is unaffected: the cap
    /// is a ceiling, not a floor.
    fn renderLines(self: *InputBox, width: usize) ![]const []const u8 {
        const a = self.alloc;
        var rows: std.ArrayList([]const u8) = .empty;
        defer {
            for (rows.items) |r| a.free(r);
            rows.deinit(a);
        }

        const cursor_style = theme.default.fg(.cursor);
        // Locate the cursor's (row, byte-col-in-row).
        const focused = self.focusable.focused;

        // Walk lines, tracking byte offset so we know which row holds cursor.
        // `cursor_row` records which produced row carries the cursor block, so
        // the scroll-window below can keep it visible.
        var line_byte_start: usize = 0;
        var produced_any = false;
        var cursor_row: usize = 0;
        var it = std.mem.splitScalar(u8, self.text.items, '\n');
        while (it.next()) |line| {
            const line_start = line_byte_start;
            const line_end = line_start + line.len;
            const cursor_in_line = focused and self.cursor >= line_start and self.cursor <= line_end and
                // The cursor belongs to the FIRST line whose range contains it
                // (at a '\n' boundary it stays on the line before the break,
                // i.e. == line_end). Disambiguate the boundary: if cursor ==
                // line_end and there are more lines, it belongs to the NEXT
                // line's start unless this is the last line.
                (self.cursor < line_end or it.peek() == null);

            if (cursor_in_line) cursor_row = rows.items.len;
            const row = try self.renderRow(line, if (cursor_in_line) self.cursor - line_start else null, cursor_style, width, focused);
            try rows.append(a, row);
            produced_any = true;
            line_byte_start = line_end + 1; // skip the '\n'
        }
        if (!produced_any) {
            // Empty buffer: a single (possibly cursor-bearing) row.
            const row = try self.renderRow("", if (focused) @as(?usize, 0) else null, cursor_style, width, focused);
            try rows.append(a, row);
        }

        // Apply the scroll-window: store at most `line_cap` rows, the window
        // defaulting to the tail and sliding up to keep the focused cursor row
        // visible. When unfocused there is no live cursor, so we never slide
        // up — the tail window stands.
        const window = self.scrollWindow(rows.items.len, if (focused) cursor_row else null);
        try self.cache.store(rows.items[window.start..window.end]);
        return cacheLines(&self.cache);
    }

    /// Compute the visible `[start, end)` row range for the scroll-window given
    /// the total produced rows and (optionally) the focused cursor's row.
    /// Returns the whole range when `total <= line_cap` (or the cap is
    /// 0/disabled). Otherwise returns a `line_cap`-tall window biased toward the
    /// TAIL: the default window is the last `line_cap` rows, sliding UP only as
    /// far as needed to keep `cursor_row` visible. A null `cursor_row` (no live
    /// cursor / unfocused) leaves the tail window in place.
    const Window = struct { start: usize, end: usize };
    fn scrollWindow(self: *const InputBox, total: usize, cursor_row: ?usize) Window {
        const cap = self.line_cap;
        if (cap == 0 or total <= cap) return .{ .start = 0, .end = total };

        // Default to the last `cap` rows.
        var start = total - cap;
        // Slide the window up if the focused cursor is above it (keep the cursor
        // row in view). The cursor is never below the tail window, so no
        // downward slide is needed.
        if (cursor_row) |cr| {
            if (cr < start) start = cr;
        }
        return .{ .start = start, .end = start + cap };
    }

    /// Render one visual row. `cursor_col` is the byte offset within `line`
    /// where the cursor sits (null if the cursor isn't on this row). When
    /// present and focused, draws a reverse-video block over the glyph at the
    /// cursor (or a space at end-of-line) and emits CURSOR_MARKER there.
    fn renderRow(self: *InputBox, line: []const u8, cursor_col: ?usize, cursor_style: Style, width: usize, focused: bool) ![]u8 {
        const a = self.alloc;
        // The cursor block consumes one visible column, so usable text width
        // is width-1 when the cursor sits at/after the truncated end and we
        // must show the block. To keep it simple and always-safe: truncate the
        // plain line to `width` columns; if a cursor block would push us to
        // width+1, the block replaces the last column instead.
        const vis = truncateToCols(line, width);

        var buf: std.ArrayList(u8) = .empty;
        errdefer buf.deinit(a);

        if (cursor_col == null or !focused) {
            try buf.appendSlice(a, vis);
            return buf.toOwnedSlice(a);
        }

        // Cursor is on this row. Find the byte position within `vis`.
        const cc = cursor_col.?;
        const before_cols = displayWidth(line[0..@min(cc, line.len)]);

        if (cc >= line.len) {
            // Cursor at end-of-line: block over a trailing space. Ensure room:
            // if the visible text already fills `width`, drop its last column.
            var head = vis;
            if (before_cols >= width) {
                head = truncateToCols(line, width - 1);
            }
            try buf.appendSlice(a, head);
            try buf.appendSlice(a, CURSOR_MARKER);
            try buf.appendSlice(a, cursor_style.open());
            try buf.appendSlice(a, " ");
            try buf.appendSlice(a, cursor_style.close());
            return buf.toOwnedSlice(a);
        }

        // Cursor over an interior glyph. Split: head | glyph | tail.
        const glyph_len = blk: {
            const sl = std.unicode.utf8ByteSequenceLength(line[cc]) catch 1;
            break :blk @min(sl, line.len - cc);
        };
        const head = line[0..cc];
        const glyph = line[cc .. cc + glyph_len];
        const tail = line[cc + glyph_len ..];

        // Compose head + marker + [reverse]glyph[/] + tail, then truncate the
        // whole visible width to `width` columns (escapes + marker are
        // zero-width, so truncation acts on glyphs).
        try buf.appendSlice(a, head);
        try buf.appendSlice(a, CURSOR_MARKER);
        try buf.appendSlice(a, cursor_style.open());
        try buf.appendSlice(a, glyph);
        try buf.appendSlice(a, cursor_style.close());
        try buf.appendSlice(a, tail);

        // The composed row's visible width == displayWidth(line). If that
        // exceeds `width`, rebuild with a width-bounded tail. (Rare: cursor
        // near a long line's start.) Simpler safe path: if over, truncate the
        // tail.
        if (displayWidth(line) > width) {
            buf.clearRetainingCapacity();
            // Keep head+glyph; truncate tail to remaining columns.
            const used = before_cols + 1; // head cols + the glyph
            try buf.appendSlice(a, head);
            try buf.appendSlice(a, CURSOR_MARKER);
            try buf.appendSlice(a, cursor_style.open());
            try buf.appendSlice(a, glyph);
            try buf.appendSlice(a, cursor_style.close());
            if (used < width) {
                const remaining = width - used;
                try buf.appendSlice(a, truncateToCols(tail, remaining));
            }
        }
        return buf.toOwnedSlice(a);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *InputBox = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *InputBox = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
        .handleInput = handleInputImpl,
    };

    pub fn comp(self: *InputBox) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// Footer — persistent bottom line with frame-timing element (plan §6)
// ===========================================================================

/// The persistent bottom line. For P1 it renders a FRAME-TIMING element: the
/// last frame's render time as a theoretical-max fps (1000/ms), shown inverted
/// (reverse-video). It optionally shows model info passed in by the app. The
/// fps element is TEMPORARY (removed after perf validation) but REQUIRED for
/// P1.
///
/// Frame-time input: the app calls `setFrameTime(ms)` after each rendered frame
/// with the measured render duration in milliseconds; this updates the fps and
/// marks dirty so the footer repaints. `setModel(name)` sets the model info.
pub const Footer = struct {
    alloc: std.mem.Allocator,
    cache: RenderCache,
    /// Last frame's render time in milliseconds (null = not measured yet).
    frame_ms: ?f64 = null,
    /// Model info string (borrowed; copied into a small owned buffer on set).
    model: std.ArrayList(u8) = .empty,
    /// Latest context-window size in tokens (null = no usage reported yet).
    /// Overwritten on each `message_complete` with the most recent value, not
    /// accumulated. Defined (plan §6) as
    /// `usage.input + usage.cache_read + usage.cache_write`.
    context_tokens: ?u64 = null,

    pub fn init(alloc: std.mem.Allocator) Footer {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *Footer) void {
        self.model.deinit(self.alloc);
        self.cache.deinit();
    }

    /// Feed the last frame's render time (milliseconds). Marks dirty so the
    /// footer's fps element repaints next frame.
    pub fn setFrameTime(self: *Footer, ms: f64) void {
        self.frame_ms = ms;
        self.cache.markDirty();
    }

    /// Set the model info shown in the footer.
    pub fn setModel(self: *Footer, name: []const u8) !void {
        self.model.clearRetainingCapacity();
        try self.model.appendSlice(self.alloc, name);
        self.cache.markDirty();
    }

    /// Set the latest context-window token count (plan §6). The caller passes
    /// the already-summed `input + cache_read + cache_write`. Overwrites the
    /// previous value (latest-wins) and marks dirty so the footer repaints.
    pub fn setContextTokens(self: *Footer, tokens: u64) void {
        self.context_tokens = tokens;
        self.cache.markDirty();
    }

    /// Format the context-window element: e.g. "12.3k ctx" for large counts,
    /// "845 ctx" for small ones. "" (empty) when no usage reported yet, so the
    /// element is simply absent until the first `message_complete`.
    fn contextText(self: *const Footer, buf: []u8) []const u8 {
        const n = self.context_tokens orelse return "";
        if (n < 1000) return std.fmt.bufPrint(buf, "{d} ctx", .{n}) catch "";
        const k = @as(f64, @floatFromInt(n)) / 1000.0;
        return std.fmt.bufPrint(buf, "{d:.1}k ctx", .{k}) catch "";
    }

    /// Format the theoretical-max fps element from the last frame time.
    /// `fps = 1000 / ms`; a zero/sub-millisecond frame is reported as a capped
    /// ">9999" sentinel rather than infinity. "--" when unmeasured.
    fn fpsText(self: *const Footer, buf: []u8) []const u8 {
        const ms = self.frame_ms orelse return std.fmt.bufPrint(buf, "fps: --", .{}) catch "fps: --";
        if (ms <= 0.0) return std.fmt.bufPrint(buf, "fps: >9999", .{}) catch "fps: >9999";
        const fps = 1000.0 / ms;
        if (fps > 9999.0) return std.fmt.bufPrint(buf, "fps: >9999", .{}) catch "fps: >9999";
        return std.fmt.bufPrint(buf, "fps: {d:.0} ({d:.2}ms)", .{ fps, ms }) catch "fps: ?";
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *Footer = @ptrCast(@alignCast(ptr));
        const a = self.alloc;

        var fps_buf: [48]u8 = undefined;
        const fps = self.fpsText(&fps_buf);
        var ctx_buf: [32]u8 = undefined;
        const ctx = self.contextText(&ctx_buf);

        // Build the PLAIN content: "<model>   <ctx>   <fps>" (model and ctx
        // only when present).
        var plain: std.ArrayList(u8) = .empty;
        defer plain.deinit(a);
        if (self.model.items.len != 0) {
            try plain.appendSlice(a, self.model.items);
            try plain.appendSlice(a, "   ");
        }
        if (ctx.len != 0) {
            try plain.appendSlice(a, ctx);
            try plain.appendSlice(a, "   ");
        }
        try plain.appendSlice(a, fps);

        const vis = truncateToCols(plain.items, width);

        // The fps element is shown INVERTED (reverse video). The whole footer
        // line uses reverse video so the timing element stands out; the model
        // rides along in the same inverted run. (Temporary perf chrome.)
        const cursor_style = theme.default.fg(.cursor); // reverse video
        const composed = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ cursor_style.open(), vis, cursor_style.close() });
        defer a.free(composed);

        const lines = [_][]const u8{composed};
        try self.cache.store(&lines);
        return cacheLines(&self.cache);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *Footer = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *Footer = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *Footer) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// Welcome — session-start banner (plan §6: "version, cwd, model info")
// ===========================================================================

/// A static banner shown as the first transcript entry at session start.
/// Structured data in (version / cwd / model label via setters), lines out.
/// Re-rendered only when one of the fields changes (markDirty), which in
/// practice is once during bring-up.
pub const Welcome = struct {
    alloc: std.mem.Allocator,
    cache: RenderCache,
    version: std.ArrayList(u8) = .empty,
    cwd: std.ArrayList(u8) = .empty,
    model: std.ArrayList(u8) = .empty,

    pub fn init(alloc: std.mem.Allocator) Welcome {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *Welcome) void {
        self.version.deinit(self.alloc);
        self.cwd.deinit(self.alloc);
        self.model.deinit(self.alloc);
        self.cache.deinit();
    }

    fn setField(self: *Welcome, field: *std.ArrayList(u8), value: []const u8) !void {
        field.clearRetainingCapacity();
        try field.appendSlice(self.alloc, value);
        self.cache.markDirty();
    }

    /// Set the panto version string (e.g. "0.1.0").
    pub fn setVersion(self: *Welcome, value: []const u8) !void {
        try self.setField(&self.version, value);
    }

    /// Set the working directory shown in the banner.
    pub fn setCwd(self: *Welcome, value: []const u8) !void {
        try self.setField(&self.cwd, value);
    }

    /// Set the model label shown in the banner.
    pub fn setModel(self: *Welcome, value: []const u8) !void {
        try self.setField(&self.model, value);
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *Welcome = @ptrCast(@alignCast(ptr));
        const a = self.alloc;
        const accent = theme.default.fg(.welcome);
        const dim = theme.default.fg(.dim);

        // Transient owned lines; freed after the cache dupes them.
        var lines: std.ArrayList([]const u8) = .empty;
        defer {
            for (lines.items) |l| a.free(l);
            lines.deinit(a);
        }

        // Title line: "panto v<version>" in the accent color.
        {
            const title_plain = if (self.version.items.len != 0)
                try std.fmt.allocPrint(a, "panto v{s}", .{self.version.items})
            else
                try std.fmt.allocPrint(a, "panto", .{});
            defer a.free(title_plain);
            const vis = truncateToCols(title_plain, width);
            try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ accent.open(), vis, accent.close() }));
        }

        // Detail lines (dim): cwd and model, only when set.
        if (self.cwd.items.len != 0) {
            const plain = try std.fmt.allocPrint(a, "cwd: {s}", .{self.cwd.items});
            defer a.free(plain);
            const vis = truncateToCols(plain, width);
            try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
        }
        if (self.model.items.len != 0) {
            const plain = try std.fmt.allocPrint(a, "model: {s}", .{self.model.items});
            defer a.free(plain);
            const vis = truncateToCols(plain, width);
            try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
        }

        try self.cache.store(lines.items);
        return cacheLines(&self.cache);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *Welcome = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *Welcome = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *Welcome) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// Thinking — streaming thinking deltas (plan §6: dimmed; streams)
// ===========================================================================

/// Accumulates thinking content deltas into an internal buffer and renders the
/// wrapped text with the theme's `thinking` (dim) style. Shares AssistantText's
/// streaming-tail dirty model (`appendDelta` + `markDirtyAppend`), so the cut
/// stays near the tail while reasoning streams. It is its OWN component type
/// (not a styled AssistantText) so the component taxonomy is honest: the engine
/// and any future event/handler logic can distinguish a thinking block from an
/// assistant body.
pub const Thinking = struct {
    alloc: std.mem.Allocator,
    buffer: std.ArrayList(u8) = .empty,
    cache: RenderCache,

    pub fn init(alloc: std.mem.Allocator) Thinking {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *Thinking) void {
        self.buffer.deinit(self.alloc);
        self.cache.deinit();
    }

    /// Append a streaming thinking delta. Retains the baseline so the cache
    /// diff recovers the true tail change point (firstLineChanged near the end).
    pub fn appendDelta(self: *Thinking, delta: []const u8) !void {
        try self.buffer.appendSlice(self.alloc, delta);
        self.cache.markDirtyAppend();
    }

    /// Replace the whole buffer. Marks dirty.
    pub fn setText(self: *Thinking, text: []const u8) !void {
        self.buffer.clearRetainingCapacity();
        try self.buffer.appendSlice(self.alloc, text);
        self.cache.markDirty();
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *Thinking = @ptrCast(@alignCast(ptr));
        return renderStyledLines(&self.cache, self.buffer.items, theme.default.fg(.thinking), width, self.alloc);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *Thinking = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *Thinking = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *Thinking) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// CompactionSummary — shown when context is compacted (plan §6)
// ===========================================================================

/// Renders a compaction summary (the synthetic seed text that replaces a
/// compacted conversation prefix). Structured data in (the summary string via
/// `setSummary`), lines out. Styled as dim chrome with a short prefix so it
/// reads as a system event rather than assistant prose.
pub const CompactionSummary = struct {
    alloc: std.mem.Allocator,
    buffer: std.ArrayList(u8) = .empty,
    cache: RenderCache,

    pub fn init(alloc: std.mem.Allocator) CompactionSummary {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *CompactionSummary) void {
        self.buffer.deinit(self.alloc);
        self.cache.deinit();
    }

    /// Set the compaction summary text. Marks dirty.
    pub fn setSummary(self: *CompactionSummary, text: []const u8) !void {
        self.buffer.clearRetainingCapacity();
        try self.buffer.appendSlice(self.alloc, text);
        self.cache.markDirty();
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *CompactionSummary = @ptrCast(@alignCast(ptr));
        const a = self.alloc;
        const style = theme.default.fg(.compaction);

        // Wrap a header line plus the summary body, all styled as compaction
        // chrome. The header makes the event legible even when the summary is
        // empty.
        var plain: std.ArrayList([]const u8) = .empty;
        defer plain.deinit(a);
        try plain.append(a, "[context compacted]");
        try wrapBuffer(self.buffer.items, width, &plain, a);

        var styled: std.ArrayList([]const u8) = .empty;
        defer {
            for (styled.items) |s| a.free(s);
            styled.deinit(a);
        }
        for (plain.items) |line| {
            const vis = truncateToCols(line, width);
            try styled.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ style.open(), vis, style.close() }));
        }

        try self.cache.store(styled.items);
        return cacheLines(&self.cache);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *CompactionSummary = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *CompactionSummary = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *CompactionSummary) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// ToolUse — one component owns the whole call + result (plan §6, P2)
// ===========================================================================

/// A single component that owns an entire tool call: its name, its streamed
/// input (verbatim JSON args), and its result output. Render progression
/// (plan §6 / P2 table):
///
///   1. At creation (block_start), name unknown:    `tool (?)…`
///   2. Once args finish streaming (name known):    `tool (<name>) <input json>`
///      followed by a blank line and `(…)` as a result placeholder.
///   3. Once the result lands:                      `tool (<name>) <input json>`
///      followed by a blank line and the result output text.
///
/// The input JSON is rendered VERBATIM (no pretty-print), terminal-wrapped to
/// width. It accumulates from the ToolUse block's `content_delta`s (the deltas
/// ARE the streaming JSON args), or is set wholesale from the completed block.
///
/// Collapsing (ctrl+o) is a GLOBAL toggle driven by the app: it calls
/// `setCollapsed(bool)` on every ToolUse component. Default is COLLAPSED. When
/// collapsed, only the LAST 5 lines of the wrapped output are shown (with a
/// leading `…` marker line when output was truncated); expanded shows all of
/// it. Collapsing is a length change — the RenderCache diff and the engine's
/// line-diff backstop handle the shrink; the component just re-renders fewer
/// lines and marks dirty.
///
/// No "active component" (plan §6): the app keys each ToolUse instance by the
/// libpanto block index AND by tool-call id (for result correlation). This
/// component holds no global state.
pub const ToolUse = struct {
    /// Number of trailing output lines shown when collapsed.
    pub const collapsed_tail_lines: usize = 5;

    alloc: std.mem.Allocator,
    cache: RenderCache,
    /// Resolved tool name, or null until `tool_details`/completion.
    name: ?std.ArrayList(u8) = null,
    /// Accumulated verbatim input JSON (streamed args).
    input: std.ArrayList(u8) = .empty,
    /// Result output text, or null until the result lands.
    output: ?std.ArrayList(u8) = null,
    /// Whether the output is collapsed to its tail. Default true.
    collapsed: bool = true,

    pub fn init(alloc: std.mem.Allocator) ToolUse {
        return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
    }

    pub fn deinit(self: *ToolUse) void {
        if (self.name) |*n| n.deinit(self.alloc);
        self.input.deinit(self.alloc);
        if (self.output) |*o| o.deinit(self.alloc);
        self.cache.deinit();
    }

    /// Resolve the tool name (from `tool_details` or the completed block).
    pub fn setName(self: *ToolUse, name: []const u8) !void {
        if (self.name == null) self.name = .empty;
        self.name.?.clearRetainingCapacity();
        try self.name.?.appendSlice(self.alloc, name);
        self.cache.markDirty();
    }

    /// Append a streaming args delta (verbatim JSON bytes).
    pub fn appendInput(self: *ToolUse, delta: []const u8) !void {
        try self.input.appendSlice(self.alloc, delta);
        self.cache.markDirty();
    }

    /// Replace the input verbatim (e.g. from the completed block's `input`).
    pub fn setInput(self: *ToolUse, value: []const u8) !void {
        self.input.clearRetainingCapacity();
        try self.input.appendSlice(self.alloc, value);
        self.cache.markDirty();
    }

    /// Set the result output text. Transitions render stage 2 -> 3.
    pub fn setOutput(self: *ToolUse, value: []const u8) !void {
        if (self.output == null) self.output = .empty;
        self.output.?.clearRetainingCapacity();
        try self.output.?.appendSlice(self.alloc, value);
        self.cache.markDirty();
    }

    /// Global collapse toggle target. The app calls this on every ToolUse
    /// component when ctrl+o is pressed. A no-op state change skips the dirty.
    pub fn setCollapsed(self: *ToolUse, value: bool) void {
        if (self.collapsed == value) return;
        self.collapsed = value;
        self.cache.markDirty();
    }

    fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
        _ = alloc;
        const self: *ToolUse = @ptrCast(@alignCast(ptr));
        const a = self.alloc;
        const tool_style = theme.default.fg(.tool);
        const dim = theme.default.fg(.dim);

        // Transient owned lines; the cache dupes them and we free here.
        var lines: std.ArrayList([]const u8) = .empty;
        defer {
            for (lines.items) |l| a.free(l);
            lines.deinit(a);
        }

        // -- Header: `tool (?)…` or `tool (<name>) <input json>` ------------
        if (self.name == null) {
            const plain = "tool (?)…";
            const vis = truncateToCols(plain, width);
            try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ tool_style.open(), vis, tool_style.close() }));
            try self.cache.store(lines.items);
            return cacheLines(&self.cache);
        }

        // Name known: header is `tool (<name>) <input json>`, wrapped to width.
        // The whole header (including verbatim JSON) is one logical paragraph
        // that we wrap; it is styled with the tool accent.
        {
            const header_plain = try std.fmt.allocPrint(a, "tool ({s}) {s}", .{ self.name.?.items, self.input.items });
            defer a.free(header_plain);
            var wrapped: std.ArrayList([]const u8) = .empty;
            defer wrapped.deinit(a);
            try wrapParagraph(header_plain, width, &wrapped, a);
            for (wrapped.items) |line| {
                const vis = truncateToCols(line, width);
                try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ tool_style.open(), vis, tool_style.close() }));
            }
        }

        // -- Blank separator line ------------------------------------------
        try lines.append(a, try a.dupe(u8, ""));

        // -- Result region: `(…)` placeholder or the output text -----------
        if (self.output == null) {
            const vis = truncateToCols("(…)", width);
            try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
        } else {
            // Wrap the full output, then optionally collapse to the tail.
            var out_lines: std.ArrayList([]const u8) = .empty;
            defer out_lines.deinit(a);
            try wrapBuffer(self.output.?.items, width, &out_lines, a);

            var start: usize = 0;
            var truncated = false;
            if (self.collapsed and out_lines.items.len > collapsed_tail_lines) {
                start = out_lines.items.len - collapsed_tail_lines;
                truncated = true;
            }
            if (truncated) {
                // A leading marker so the user knows output was elided.
                const vis = truncateToCols("…", width);
                try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
            }
            for (out_lines.items[start..]) |line| {
                const vis = truncateToCols(line, width);
                // Output uses plain assistant style (no escape) so it reads as
                // content; truncate enforces the width contract.
                try lines.append(a, try a.dupe(u8, vis));
            }
        }

        try self.cache.store(lines.items);
        return cacheLines(&self.cache);
    }

    fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
        const self: *ToolUse = @ptrCast(@alignCast(ptr));
        return self.cache.firstLineChanged();
    }

    fn invalidateImpl(ptr: *anyopaque) void {
        const self: *ToolUse = @ptrCast(@alignCast(ptr));
        self.cache.invalidate();
    }

    const vtable = Component.VTable{
        .render = renderImpl,
        .firstLineChanged = firstLineChangedImpl,
        .invalidate = invalidateImpl,
    };

    pub fn comp(self: *ToolUse) Component {
        return .{ .ptr = self, .vtable = &vtable };
    }
};

// ===========================================================================
// Tests
// ===========================================================================

const testing = std.testing;
const engine = @import("tui_engine.zig");

/// Visible width of a rendered (possibly styled, possibly marker-bearing) line,
/// reusing the engine's authoritative measure.
fn vw(line: []const u8) usize {
    return engine.visibleWidth(line);
}

// -- helpers ---------------------------------------------------------------

test "displayWidth counts codepoints; truncateToCols respects boundaries" {
    try testing.expectEqual(@as(usize, 3), displayWidth("abc"));
    try testing.expectEqual(@as(usize, 3), displayWidth("aé✓"));
    try testing.expectEqualStrings("aé", truncateToCols("aé✓", 2));
    try testing.expectEqualStrings("abc", truncateToCols("abcdef", 3));
    // Never splits a multibyte codepoint.
    const t = truncateToCols("é", 1);
    try testing.expectEqualStrings("é", t);
}

test "wrapParagraph word-wraps and hard-splits long words" {
    var out: std.ArrayList([]const u8) = .empty;
    defer out.deinit(testing.allocator);
    try wrapParagraph("hello world foo", 7, &out, testing.allocator);
    try testing.expectEqual(@as(usize, 3), out.items.len);
    try testing.expectEqualStrings("hello", out.items[0]);
    try testing.expectEqualStrings("world", out.items[1]);
    try testing.expectEqualStrings("foo", out.items[2]);

    out.clearRetainingCapacity();
    try wrapParagraph("abcdefghij", 4, &out, testing.allocator);
    try testing.expectEqual(@as(usize, 3), out.items.len);
    try testing.expectEqualStrings("abcd", out.items[0]);
    try testing.expectEqualStrings("efgh", out.items[1]);
    try testing.expectEqualStrings("ij", out.items[2]);
}

// -- AssistantText ---------------------------------------------------------

test "AssistantText: renders wrapped text within width" {
    var at = AssistantText.init(testing.allocator);
    defer at.deinit();
    try at.setText("hello world foo");
    const lines = try at.comp().render(7, testing.allocator);
    try testing.expectEqual(@as(usize, 3), lines.len);
    for (lines) |l| try testing.expect(vw(l) <= 7);
    // First render after empty cache => changed from 0.
    try testing.expectEqual(@as(?usize, 0), at.comp().firstLineChanged());
}

test "AssistantText: streaming keeps firstLineChanged near the tail, not 0" {
    var at = AssistantText.init(testing.allocator);
    defer at.deinit();
    // Seed several wrapped lines.
    try at.setText("alpha beta gamma delta epsilon");
    _ = try at.comp().render(11, testing.allocator);
    const lines1 = at.cache.lines.?.len;
    try testing.expect(lines1 >= 3);

    // Append a delta to the tail; earlier wrapped lines stay byte-identical.
    try at.appendDelta(" zeta");
    // While dirty, firstLineChanged reports 0 (full markDirty). The KEY
    // property is what the cache reports AFTER the render: the lowest line that
    // actually changed must be near the tail, not 0.
    _ = try at.comp().render(11, testing.allocator);
    const fc = at.comp().firstLineChanged();
    // The change landed on the last line(s); the cut must be > 0.
    try testing.expect(fc == null or fc.? > 0);
    // Stronger: the first changed line should be at the tail region.
    if (fc) |v| try testing.expect(v >= lines1 - 1);
}

test "AssistantText: width truncation on a long unbroken word" {
    var at = AssistantText.init(testing.allocator);
    defer at.deinit();
    try at.setText("supercalifragilistic");
    const lines = try at.comp().render(5, testing.allocator);
    for (lines) |l| try testing.expect(vw(l) <= 5);
}

// -- UserText ---------------------------------------------------------------

test "UserText: renders user-styled lines within width" {
    var ut = UserText.init(testing.allocator);
    defer ut.deinit();
    try ut.setText("a user message that wraps");
    const lines = try ut.comp().render(10, testing.allocator);
    for (lines) |l| try testing.expect(vw(l) <= 10);
    // Static: re-render with no change => clean.
    _ = try ut.comp().render(10, testing.allocator);
    try testing.expectEqual(@as(?usize, null), ut.comp().firstLineChanged());
}

// -- InputBox ---------------------------------------------------------------

fn charKey(c: u21, text: []const u8) Key {
    return .{ .code = .{ .char = c }, .text = text };
}

test "InputBox: insert printable chars and render with cursor block when focused" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.setFocused(true);
    try ib.applyKey(charKey('h', "h"));
    try ib.applyKey(charKey('i', "i"));
    const lines = try ib.comp().render(20, testing.allocator);
    try testing.expectEqual(@as(usize, 1), lines.len);
    try testing.expect(vw(lines[0]) <= 20);
    // Focused => emits CURSOR_MARKER and reverse-video style.
    try testing.expect(std.mem.indexOf(u8, lines[0], CURSOR_MARKER) != null);
    try testing.expect(std.mem.indexOf(u8, lines[0], "\x1b[7m") != null);
    try testing.expect(std.mem.indexOf(u8, lines[0], "hi") != null);
}

test "InputBox: not focused emits no cursor marker" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try ib.applyKey(charKey('x', "x"));
    const lines = try ib.comp().render(20, testing.allocator);
    try testing.expect(std.mem.indexOf(u8, lines[0], CURSOR_MARKER) == null);
}

test "InputBox: backspace, delete, and cursor movement" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    for ("abc") |c| try ib.applyKey(charKey(c, &[_]u8{c}));
    try testing.expectEqual(@as(usize, 3), ib.cursor);
    ib.backspace(); // "ab"
    try testing.expectEqualStrings("ab", ib.text.items);
    try testing.expectEqual(@as(usize, 2), ib.cursor);
    ib.moveLeft(); // cursor at 1
    try testing.expectEqual(@as(usize, 1), ib.cursor);
    ib.deleteForward(); // delete 'b' -> "a"
    try testing.expectEqualStrings("a", ib.text.items);
    ib.moveHome();
    try testing.expectEqual(@as(usize, 0), ib.cursor);
    ib.moveEnd();
    try testing.expectEqual(@as(usize, 1), ib.cursor);
}

test "InputBox: multibyte backspace removes a whole codepoint" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try ib.applyKey(charKey('é', "é")); // 2 bytes
    try testing.expectEqual(@as(usize, 2), ib.cursor);
    ib.backspace();
    try testing.expectEqual(@as(usize, 0), ib.text.items.len);
}

test "InputBox: shift+enter inserts newline, enter submits" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    for ("ab") |c| try ib.applyKey(charKey(c, &[_]u8{c}));
    // Shift+Enter => newline (grows a row).
    try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
    for ("cd") |c| try ib.applyKey(charKey(c, &[_]u8{c}));
    try testing.expectEqualStrings("ab\ncd", ib.text.items);
    const lines = try ib.comp().render(20, testing.allocator);
    try testing.expectEqual(@as(usize, 2), lines.len);

    // Plain Enter => submit, editor cleared, pollable buffer set.
    try ib.applyKey(.{ .code = .enter });
    const got = ib.takeSubmitted();
    try testing.expect(got != null);
    try testing.expectEqualStrings("ab\ncd", got.?);
    try testing.expectEqual(@as(usize, 0), ib.text.items.len);
    // Second poll returns null.
    try testing.expect(ib.takeSubmitted() == null);
}

test "InputBox: handleInput decodes raw bytes (typing + enter)" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.comp().handleInput("hi\r"); // 'h' 'i' Enter
    const got = ib.takeSubmitted();
    try testing.expect(got != null);
    try testing.expectEqualStrings("hi", got.?);
}

test "InputBox: handleInput kitty shift+enter inserts newline" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.comp().handleInput("a\x1b[13;2ub"); // 'a', shift+enter, 'b'
    try testing.expectEqualStrings("a\nb", ib.text.items);
    try testing.expect(ib.takeSubmitted() == null); // no plain enter yet
}

test "InputBox: firstLineChanged is cache-derived (clean after stable render)" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.setFocused(true);
    try ib.applyKey(charKey('x', "x"));
    _ = try ib.comp().render(20, testing.allocator);
    // Re-render with no state change => clean.
    _ = try ib.comp().render(20, testing.allocator);
    try testing.expectEqual(@as(?usize, null), ib.comp().firstLineChanged());
    // Edit => dirty again.
    try ib.applyKey(charKey('y', "y"));
    try testing.expectEqual(@as(?usize, 0), ib.comp().firstLineChanged());
}

test "InputBox: cursor block fits within width at end of a full line" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.setFocused(true);
    for ("abcde") |c| try ib.applyKey(charKey(c, &[_]u8{c}));
    // width 5, cursor at end: the block must not overflow.
    const lines = try ib.comp().render(5, testing.allocator);
    try testing.expect(vw(lines[0]) <= 5);
}

fn ctrlKey(letter: u8) Key {
    return .{ .code = .{ .char = letter }, .mods = .{ .ctrl = true } };
}

fn typeStr(ib: *InputBox, s: []const u8) !void {
    for (s) |c| try ib.applyKey(charKey(c, &[_]u8{c}));
}

test "InputBox: alt+left / alt+right move by word" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "foo bar baz"); // cursor at 11 (end)
    try testing.expectEqual(@as(usize, 11), ib.cursor);
    // Alt+Left: jump to start of "baz" (byte 8).
    try ib.applyKey(.{ .code = .left, .mods = .{ .alt = true } });
    try testing.expectEqual(@as(usize, 8), ib.cursor);
    // Again: start of "bar" (byte 4).
    try ib.applyKey(.{ .code = .left, .mods = .{ .alt = true } });
    try testing.expectEqual(@as(usize, 4), ib.cursor);
    // Alt+Right: skip "bar" + the trailing space -> start of "baz" (byte 8).
    try ib.applyKey(.{ .code = .right, .mods = .{ .alt = true } });
    try testing.expectEqual(@as(usize, 8), ib.cursor);
    // Ctrl+Left also performs word-motion (many terminals send 1;5D).
    try ib.applyKey(.{ .code = .left, .mods = .{ .ctrl = true } });
    try testing.expectEqual(@as(usize, 4), ib.cursor);
}

test "InputBox: alt+arrow via RAW BYTES moves by word (handleInput pipeline)" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "foo bar baz"); // cursor at 11
    try testing.expectEqual(@as(usize, 11), ib.cursor);

    // Kitty functional alt+left: CSI 57350 ; 3 u -> word-left to byte 8.
    ib.comp().handleInput("\x1b[57350;3u");
    try testing.expectEqual(@as(usize, 8), ib.cursor);

    // Legacy CSI alt+left: 1;3D -> word-left to byte 4.
    ib.comp().handleInput("\x1b[1;3D");
    try testing.expectEqual(@as(usize, 4), ib.cursor);

    // Alt+right via raw bytes -> back to byte 8.
    ib.comp().handleInput("\x1b[1;3C");
    try testing.expectEqual(@as(usize, 8), ib.cursor);
}

test "InputBox: ESC b / ESC f (readline alt-word form) moves by word" {
    // Ghostty and most macOS terminals send Alt+Left/Right as the classic
    // readline `ESC b` / `ESC f`, which decode to alt+b / alt+f CHAR keys
    // rather than modified-arrow CSIs. These must move by word (and must NOT
    // be inserted as literal text).
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "foo bar baz"); // cursor at 11
    try testing.expectEqual(@as(usize, 11), ib.cursor);

    ib.comp().handleInput("\x1bb"); // alt+b -> word-left to byte 8
    try testing.expectEqual(@as(usize, 8), ib.cursor);
    ib.comp().handleInput("\x1bb"); // -> byte 4
    try testing.expectEqual(@as(usize, 4), ib.cursor);
    ib.comp().handleInput("\x1bf"); // alt+f -> word-right to byte 8
    try testing.expectEqual(@as(usize, 8), ib.cursor);

    // The alt-char must not have inserted any literal 'b'/'f' bytes.
    try testing.expectEqualStrings("foo bar baz", ib.text.items);
}

test "InputBox: alt/ctrl+backspace deletes the previous word" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "foo bar baz"); // cursor at 11
    try ib.applyKey(.{ .code = .backspace, .mods = .{ .alt = true } });
    try testing.expectEqualStrings("foo bar ", ib.text.items);
    try ib.applyKey(.{ .code = .backspace, .mods = .{ .ctrl = true } });
    try testing.expectEqualStrings("foo ", ib.text.items);
    // Plain backspace still deletes a single codepoint.
    try ib.applyKey(.{ .code = .backspace });
    try testing.expectEqualStrings("foo", ib.text.items);
}

test "InputBox: arrow press+release moves ONCE, not twice (no key-up double-move)" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "abcdef"); // cursor at 6
    try testing.expectEqual(@as(usize, 6), ib.cursor);

    // A physical left-arrow press under the Kitty protocol would, with event
    // reporting on, arrive as a PRESS then a RELEASE. Feeding both must move
    // the cursor only once (the release is dropped). This guards the
    // double-move regression at the raw-bytes pipeline level even if a
    // terminal still emits releases.
    ib.comp().handleInput("\x1b[57350u"); // functional left press
    try testing.expectEqual(@as(usize, 5), ib.cursor);
    ib.comp().handleInput("\x1b[57350;1:3u"); // functional left RELEASE
    try testing.expectEqual(@as(usize, 5), ib.cursor); // unchanged

    // Same property for the legacy CSI release form via applyKey directly.
    try ib.applyKey(.{ .code = .left, .event = .release });
    try testing.expectEqual(@as(usize, 5), ib.cursor);
}

test "InputBox: word-nav boundary cases (multiple spaces, newlines, buffer ends)" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    // Multiple spaces between words and a newline-separated logical line.
    try typeStr(&ib, "foo   bar");
    try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } }); // '\n' at byte 9
    try typeStr(&ib, "baz"); // cursor at end (byte 13)
    try testing.expectEqual(@as(usize, 13), ib.cursor);

    // Word-left from end: start of "baz" (byte 10, just after the '\n').
    ib.moveWordLeft();
    try testing.expectEqual(@as(usize, 10), ib.cursor);
    // Again: crosses the newline and the multi-space run to the start of "bar"
    // (byte 6).
    ib.moveWordLeft();
    try testing.expectEqual(@as(usize, 6), ib.cursor);
    // Again: start of "foo" (byte 0).
    ib.moveWordLeft();
    try testing.expectEqual(@as(usize, 0), ib.cursor);
    // At the start, word-left is a clamped no-op.
    ib.moveWordLeft();
    try testing.expectEqual(@as(usize, 0), ib.cursor);

    // Word-right skips "foo" + the multi-space run -> start of "bar" (byte 6).
    ib.moveWordRight();
    try testing.expectEqual(@as(usize, 6), ib.cursor);
    // Jump to end, then word-right is a clamped no-op.
    ib.moveEnd();
    const end = ib.cursor;
    ib.moveWordRight();
    try testing.expectEqual(end, ib.cursor);
}

test "InputBox: ctrl+u on the FIRST logical line clears to byte 0" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    // Single logical line; ctrl+u from the end clears the whole line to 0
    // (the first-line case, complementing the later-line case below).
    try typeStr(&ib, "hello world");
    try ib.applyKey(ctrlKey('u'));
    try testing.expectEqualStrings("", ib.text.items);
    try testing.expectEqual(@as(usize, 0), ib.cursor);
}

test "InputBox: focused render emits CURSOR_MARKER exactly once" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.setFocused(true);
    // Multi-row buffer so we exercise the per-row cursor placement: the marker
    // must appear on exactly ONE row, once.
    try typeStr(&ib, "alpha");
    try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
    try typeStr(&ib, "beta");
    const lines = try ib.comp().render(20, testing.allocator);
    var count: usize = 0;
    for (lines) |l| {
        var idx: usize = 0;
        while (std.mem.indexOfPos(u8, l, idx, CURSOR_MARKER)) |at| {
            count += 1;
            idx = at + CURSOR_MARKER.len;
        }
    }
    try testing.expectEqual(@as(usize, 1), count);
}

test "InputBox: ctrl+u deletes to start of the current logical line" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    // Two logical lines; cursor mid-second-line.
    try typeStr(&ib, "first");
    try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } }); // newline
    try typeStr(&ib, "second");
    // Cursor at end of "second"; ctrl+u clears just "second", keeping "first\n".
    try ib.applyKey(ctrlKey('u'));
    try testing.expectEqualStrings("first\n", ib.text.items);
    try testing.expectEqual(@as(usize, 6), ib.cursor); // just after the '\n'
}

test "InputBox: ctrl+w deletes the previous word (plain, no kill-ring)" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "hello world");
    try ib.applyKey(ctrlKey('w')); // delete "world"
    try testing.expectEqualStrings("hello ", ib.text.items);
    try ib.applyKey(ctrlKey('w')); // delete "hello "
    try testing.expectEqualStrings("", ib.text.items);
}

test "InputBox: ctrl+a / ctrl+e move to line start / end" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "abc");
    try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
    try typeStr(&ib, "defg"); // second line, cursor at end (byte 8)
    try ib.applyKey(ctrlKey('a'));
    try testing.expectEqual(@as(usize, 4), ib.cursor); // start of "defg"
    try ib.applyKey(ctrlKey('e'));
    try testing.expectEqual(@as(usize, 8), ib.cursor); // end of "defg"
}

test "InputBox: line cap renders only the last cap rows by default" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.line_cap = 3;
    // 5 logical lines: L0..L4. Cursor ends on L4.
    try typeStr(&ib, "L0");
    for (0..4) |i| {
        try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
        var b: [2]u8 = .{ 'L', @intCast('1' + i) };
        try typeStr(&ib, &b);
    }
    const lines = try ib.comp().render(20, testing.allocator);
    // Only `cap` rows rendered (the tail window: L2, L3, L4).
    try testing.expectEqual(@as(usize, 3), lines.len);
    try testing.expect(std.mem.indexOf(u8, lines[0], "L2") != null);
    try testing.expect(std.mem.indexOf(u8, lines[2], "L4") != null);
    for (lines) |ln| try testing.expect(vw(ln) <= 20);
}

test "InputBox: scroll-window slides up to keep the cursor visible" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    ib.setFocused(true);
    ib.line_cap = 3;
    try typeStr(&ib, "L0");
    for (0..4) |i| {
        try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
        var b: [2]u8 = .{ 'L', @intCast('1' + i) };
        try typeStr(&ib, &b);
    }
    // Move the cursor up to the top (L0) via Home then re-anchor: move cursor
    // to byte 0 so cursor_row == 0, above the default tail window.
    ib.moveHome();
    const lines = try ib.comp().render(20, testing.allocator);
    try testing.expectEqual(@as(usize, 3), lines.len);
    // Window slid up so the cursor row (L0) is visible at the TOP: the cursor
    // block + marker render on row 0 (the cursor splits "L0", so the marker is
    // the reliable signal), and the rows below are L1, L2 — proving the window
    // is [0, 3) not the default tail [2, 5).
    try testing.expect(std.mem.indexOf(u8, lines[0], CURSOR_MARKER) != null);
    try testing.expect(std.mem.indexOf(u8, lines[1], "L1") != null);
    try testing.expect(std.mem.indexOf(u8, lines[2], "L2") != null);
}

test "InputBox: single-row default is unaffected by the cap" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try testing.expectEqual(InputBox.default_line_cap, ib.line_cap);
    try typeStr(&ib, "just one line");
    const lines = try ib.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(usize, 1), lines.len);
}

test "InputBox: setBuffer/buffer round-trip for the $EDITOR hook" {
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    try typeStr(&ib, "old");
    try ib.setBuffer("new multi\nline text");
    try testing.expectEqualStrings("new multi\nline text", ib.buffer());
    // Cursor lands at the end.
    try testing.expectEqual(ib.text.items.len, ib.cursor);
}

// -- Footer -----------------------------------------------------------------

test "Footer: renders fps from frame time, inverted, within width" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    ft.setFrameTime(8.0); // 1000/8 = 125 fps
    const lines = try ft.comp().render(80, testing.allocator);
    try testing.expectEqual(@as(usize, 1), lines.len);
    try testing.expect(vw(lines[0]) <= 80);
    // Inverted (reverse video) styling present.
    try testing.expect(std.mem.indexOf(u8, lines[0], "\x1b[7m") != null);
    // fps value 125 present.
    try testing.expect(std.mem.indexOf(u8, lines[0], "125") != null);
}

test "Footer: unmeasured frame shows placeholder; submillisecond capped" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    var buf: [48]u8 = undefined;
    try testing.expectEqualStrings("fps: --", ft.fpsText(&buf));
    ft.setFrameTime(0.0);
    try testing.expectEqualStrings("fps: >9999", ft.fpsText(&buf));
    ft.setFrameTime(0.05); // 20000 fps -> capped
    try testing.expectEqualStrings("fps: >9999", ft.fpsText(&buf));
}

test "Footer: shows model info and truncates to width" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    ft.setFrameTime(10.0);
    try ft.setModel("gpt-test-model");
    const lines = try ft.comp().render(12, testing.allocator);
    try testing.expect(vw(lines[0]) <= 12);
}

test "Footer: setFrameTime dirties; stable re-render is clean" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    ft.setFrameTime(8.0);
    _ = try ft.comp().render(80, testing.allocator);
    _ = try ft.comp().render(80, testing.allocator);
    try testing.expectEqual(@as(?usize, null), ft.comp().firstLineChanged());
    ft.setFrameTime(16.0);
    try testing.expectEqual(@as(?usize, 0), ft.comp().firstLineChanged());
}

test "Footer: context tokens absent until set, then shown alongside fps" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    var buf: [32]u8 = undefined;
    // Absent until usage is reported.
    try testing.expectEqualStrings("", ft.contextText(&buf));
    ft.setFrameTime(8.0);
    {
        const lines = try ft.comp().render(80, testing.allocator);
        try testing.expect(std.mem.indexOf(u8, lines[0], "ctx") == null);
    }
    // Small count rendered verbatim.
    ft.setContextTokens(845);
    try testing.expectEqualStrings("845 ctx", ft.contextText(&buf));
    {
        const lines = try ft.comp().render(80, testing.allocator);
        try testing.expect(vw(lines[0]) <= 80);
        try testing.expect(std.mem.indexOf(u8, lines[0], "845 ctx") != null);
        // fps element still present alongside.
        try testing.expect(std.mem.indexOf(u8, lines[0], "fps:") != null);
    }
}

test "Footer: contextText formatting boundaries (0, 999, 1000 -> k)" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    var buf: [32]u8 = undefined;
    // Zero is a real measured value (not "absent") -> "0 ctx".
    ft.setContextTokens(0);
    try testing.expectEqualStrings("0 ctx", ft.contextText(&buf));
    // Just below the k threshold stays verbatim.
    ft.setContextTokens(999);
    try testing.expectEqualStrings("999 ctx", ft.contextText(&buf));
    // Exactly 1000 crosses into the k suffix.
    ft.setContextTokens(1000);
    try testing.expectEqualStrings("1.0k ctx", ft.contextText(&buf));
}

test "Footer: large context token counts format as k; latest wins" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    var buf: [32]u8 = undefined;
    ft.setContextTokens(12345);
    try testing.expectEqualStrings("12.3k ctx", ft.contextText(&buf));
    // Overwritten (latest-wins), not accumulated.
    ft.setContextTokens(2000);
    try testing.expectEqualStrings("2.0k ctx", ft.contextText(&buf));
}

test "Footer: setContextTokens dirties; stable re-render is clean" {
    var ft = Footer.init(testing.allocator);
    defer ft.deinit();
    ft.setFrameTime(8.0);
    ft.setContextTokens(1000);
    _ = try ft.comp().render(80, testing.allocator);
    _ = try ft.comp().render(80, testing.allocator);
    try testing.expectEqual(@as(?usize, null), ft.comp().firstLineChanged());
    ft.setContextTokens(2000);
    try testing.expectEqual(@as(?usize, 0), ft.comp().firstLineChanged());
}

// -- Integration with the real Engine (no TTY) ------------------------------

test "components drive the real engine without a TTY" {
    var buf = std.Io.Writer.Allocating.init(testing.allocator);
    defer buf.deinit();
    var eng = engine.Engine.init(testing.allocator, &buf.writer, 40, 24, false);
    defer eng.deinit();

    var user = UserText.init(testing.allocator);
    defer user.deinit();
    var assistant = AssistantText.init(testing.allocator);
    defer assistant.deinit();
    var ib = InputBox.init(testing.allocator);
    defer ib.deinit();
    var footer = Footer.init(testing.allocator);
    defer footer.deinit();

    try user.setText("hi there");
    try assistant.appendDelta("hello");
    ib.setFocused(true);
    try ib.applyKey(charKey('q', "q"));
    footer.setFrameTime(8.0);

    try eng.addComponent(user.comp());
    try eng.addComponent(assistant.comp());
    try eng.addComponent(ib.comp());
    try eng.addComponent(footer.comp());

    try eng.render(); // first paint: must not error (width contract holds)
    const out = buf.written();
    try testing.expect(std.mem.indexOf(u8, out, "hi there") != null);
    try testing.expect(std.mem.indexOf(u8, out, "hello") != null);
    // Cursor marker is consumed by the engine and recorded as a hint.
    try testing.expect(eng.cursor_hint != null);

    // Stream another delta -> only the assistant should re-render; the engine
    // stays on the differential path (no full clear after first paint).
    try assistant.appendDelta(" world");
    footer.setFrameTime(9.0);
    buf.clearRetainingCapacity();
    try eng.render();
    const out2 = buf.written();
    try testing.expect(std.mem.indexOf(u8, out2, "world") != null);
}

// -- Welcome / Thinking / CompactionSummary / ToolUse (P2) ------------------

test "Welcome: renders title + cwd + model, all within width" {
    var w = Welcome.init(testing.allocator);
    defer w.deinit();
    try w.setVersion("0.1.0");
    try w.setCwd("/tmp/project");
    try w.setModel("anthropic:claude");
    const lines = try w.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(usize, 3), lines.len);
    for (lines) |l| try testing.expect(vw(l) <= 40);
    try testing.expect(std.mem.indexOf(u8, lines[0], "panto v0.1.0") != null);
    try testing.expect(std.mem.indexOf(u8, lines[1], "/tmp/project") != null);
    try testing.expect(std.mem.indexOf(u8, lines[2], "anthropic:claude") != null);
}

test "Welcome: title only when cwd/model unset" {
    var w = Welcome.init(testing.allocator);
    defer w.deinit();
    const lines = try w.comp().render(20, testing.allocator);
    try testing.expectEqual(@as(usize, 1), lines.len);
    try testing.expect(std.mem.indexOf(u8, lines[0], "panto") != null);
}

test "Welcome: honors the width contract at a tiny width" {
    var w = Welcome.init(testing.allocator);
    defer w.deinit();
    try w.setVersion("0.1.0");
    try w.setCwd("/a/very/long/working/directory/path/that/overflows");
    try w.setModel("anthropic:claude-some-very-long-model-id");
    // Width 6: every banner row (title + cwd + model) must truncate to fit.
    const lines = try w.comp().render(6, testing.allocator);
    try testing.expectEqual(@as(usize, 3), lines.len);
    for (lines) |l| try testing.expect(vw(l) <= 6);
}

test "Thinking: streams dim, firstLineChanged stays near the tail" {
    var t = Thinking.init(testing.allocator);
    defer t.deinit();
    try t.appendDelta("line one is fairly long so it wraps across");
    _ = try t.comp().render(20, testing.allocator);
    // A clean re-render reports no change.
    _ = try t.comp().render(20, testing.allocator);
    try testing.expectEqual(@as(?usize, null), t.comp().firstLineChanged());
    // Appending a delta should dirty near the tail (not line 0).
    try t.appendDelta(" more");
    const flc = t.comp().firstLineChanged();
    try testing.expect(flc != null and flc.? > 0);
    const lines = try t.comp().render(20, testing.allocator);
    for (lines) |l| try testing.expect(vw(l) <= 20);
}

test "CompactionSummary: header + wrapped summary within width" {
    var c = CompactionSummary.init(testing.allocator);
    defer c.deinit();
    try c.setSummary("summarized prior turns here");
    const lines = try c.comp().render(20, testing.allocator);
    try testing.expect(lines.len >= 2);
    try testing.expect(std.mem.indexOf(u8, lines[0], "compacted") != null);
    for (lines) |l| try testing.expect(vw(l) <= 20);
}

test "ToolUse: stage 1 renders tool (?) before the name resolves" {
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    const lines = try t.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(usize, 1), lines.len);
    try testing.expect(std.mem.indexOf(u8, lines[0], "tool (?)") != null);
}

test "ToolUse: stage 2 shows name + verbatim json + placeholder" {
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    try t.setName("read");
    try t.appendInput("{\"path\":\"a\"}");
    const lines = try t.comp().render(60, testing.allocator);
    // header line, blank, placeholder
    try testing.expect(lines.len >= 3);
    try testing.expect(std.mem.indexOf(u8, lines[0], "tool (read) {\"path\":\"a\"}") != null);
    try testing.expectEqualStrings("", lines[lines.len - 2]);
    try testing.expect(std.mem.indexOf(u8, lines[lines.len - 1], "(…)") != null);
    for (lines) |l| try testing.expect(vw(l) <= 60);
}

test "ToolUse: collapsed shows only the last 5 output lines (default)" {
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    try t.setName("read");
    try t.setInput("{}");
    // 8 short output lines -> collapsed shows the marker + last 5.
    try t.setOutput("l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8");
    const collapsed = try t.comp().render(40, testing.allocator);
    // header, blank, marker, l4..l8 = 3 + 5
    try testing.expect(std.mem.indexOf(u8, collapsed[collapsed.len - 1], "l8") != null);
    try testing.expect(std.mem.indexOf(u8, collapsed[collapsed.len - 5], "l4") != null);
    // The earliest output lines are elided when collapsed.
    var has_l1 = false;
    for (collapsed) |l| {
        if (std.mem.indexOf(u8, l, "l1") != null) has_l1 = true;
    }
    try testing.expect(!has_l1);

    // Expanding shows everything.
    t.setCollapsed(false);
    const expanded = try t.comp().render(40, testing.allocator);
    try testing.expect(expanded.len > collapsed.len);
    var has_l1_exp = false;
    for (expanded) |l| {
        if (std.mem.indexOf(u8, l, "l1") != null) has_l1_exp = true;
    }
    try testing.expect(has_l1_exp);
}

test "ToolUse: short output is shown whole even when collapsed" {
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    try t.setName("ls");
    try t.setInput("{}");
    try t.setOutput("only\ntwo");
    const lines = try t.comp().render(40, testing.allocator);
    var seen_only = false;
    var seen_two = false;
    for (lines) |l| {
        if (std.mem.indexOf(u8, l, "only") != null) seen_only = true;
        if (std.mem.indexOf(u8, l, "two") != null) seen_two = true;
    }
    try testing.expect(seen_only and seen_two);
}

test "ToolUse: collapse/expand is a length change with a cache-derived firstLineChanged" {
    // Expanding/collapsing changes the rendered LINE COUNT (plan §3.3). A
    // collapse toggle is a structural change (the whole output region shifts),
    // so `setCollapsed` re-dirties via `markDirty` — dropping the baseline — and
    // the post-render `firstLineChanged` is therefore 0 (cache-derived: a full
    // drop reports from the top). That is correct and cheap for a small tool
    // component; the engine's line-diff backstop (plan §3.3) still handles the
    // length delta. The KEY guarantees this test pins: the line COUNT changes
    // across the toggle, the signal is cache-derived (0 after a full drop, null
    // after a stable render), and there is no hand-managed drift.
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    try t.setName("read");
    try t.setInput("{}");
    try t.setOutput("l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8");

    // Default collapsed: header + blank + marker + last 5 = 8 rows.
    const collapsed = try t.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(usize, 8), collapsed.len);
    // A stable re-render is clean (cache-derived, no drift).
    _ = try t.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(?usize, null), t.comp().firstLineChanged());

    // Expand: header + blank + all 8 output rows = 10 rows (a length GROWTH).
    t.setCollapsed(false);
    // While dirty (full drop), the signal is the cache-derived 0.
    try testing.expectEqual(@as(?usize, 0), t.comp().firstLineChanged());
    const expanded = try t.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(usize, 10), expanded.len);
    // After the render the baseline was dropped on the toggle, so the diff
    // reports from 0 — cache-derived, not a hand-managed value.
    try testing.expectEqual(@as(?usize, 0), t.comp().firstLineChanged());
    // Stable re-render is clean again.
    _ = try t.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(?usize, null), t.comp().firstLineChanged());

    // Collapse again: shrink back to 8 rows (the length-change shrink path).
    t.setCollapsed(true);
    const recollapsed = try t.comp().render(40, testing.allocator);
    try testing.expectEqual(@as(usize, 8), recollapsed.len);
}

test "ToolUse: args are rendered VERBATIM (no pretty-print) and within width" {
    // The input JSON must pass through byte-for-byte (no reflow of the JSON
    // structure), only terminal-wrapped. We use a compact object with no spaces
    // and assert the exact substring survives in the joined header.
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    try t.setName("search");
    try t.appendInput("{\"q\":\"a b\",");
    try t.appendInput("\"n\":10}");
    const verbatim = "{\"q\":\"a b\",\"n\":10}";
    try testing.expectEqualStrings(verbatim, t.input.items);

    // Wide render: the verbatim args appear unmodified on the header line.
    const wide = try t.comp().render(80, testing.allocator);
    try testing.expect(std.mem.indexOf(u8, wide[0], verbatim) != null);

    // Narrow render: header wraps across rows but every row honors the width
    // contract (no pretty-print expansion, just wrapping).
    const narrow = try t.comp().render(12, testing.allocator);
    for (narrow) |l| try testing.expect(vw(l) <= 12);
}

test "ToolUse: long output lines honor the width contract" {
    var t = ToolUse.init(testing.allocator);
    defer t.deinit();
    try t.setName("read");
    try t.setInput("{}");
    t.setCollapsed(false);
    try t.setOutput("a very long single output line that must be wrapped to fit the narrow width");
    const lines = try t.comp().render(10, testing.allocator);
    for (lines) |l| try testing.expect(vw(l) <= 10);
}