eclipse-cli 0.13.2

Command-line interface for eclipse
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
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
//! Drawing. Takes [`App`] and a frame; touches no state.
//!
//! The transcript is laid out here rather than with a scrolling widget, because the
//! window it shows depends on how many lines the blocks wrap to — which is only known
//! once the width is known, which is only known inside `draw`.

use super::app::{self, Activity, App, Block, Menu, NoteKind, Picker, ToolState, Welcome};
use crate::approve::Choice;
use crate::status;
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block as Box_, BorderType, Clear, Paragraph, Wrap};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;

const ACCENT: Color = rgb(eclipse_core::palette::ACCENT);
/// The two ends of the wordmark's gradient: warm cream at the top of the letters, amber at the
/// foot. The ring that used to sit beside them is gone; the letters keep the light, because a
/// wordmark in one flat colour reads as a heading and this is meant to read as a mark.
const WORDMARK_TOP: Color = rgb(eclipse_core::palette::WORDMARK_TOP);
const WORDMARK_FOOT: Color = rgb(eclipse_core::palette::WORDMARK_FOOT);
const USER: Color = rgb(eclipse_core::palette::USER);
const OK: Color = rgb(eclipse_core::palette::OK);
const BAD: Color = rgb(eclipse_core::palette::BAD);
const WARN: Color = rgb(eclipse_core::palette::WARN);
const DIM: Color = Color::DarkGray;
const FAINT: Color = rgb(eclipse_core::palette::FAINT);

/// One triple from [`eclipse_core::palette`], as the terminal's own colour. The table is the single
/// definition — the dashboard is handed the same numbers as CSS when its page is rendered — so this
/// is a conversion, not a second list that could drift away from it.
const fn rgb((r, g, b): (u8, u8, u8)) -> Color {
    Color::Rgb(r, g, b)
}

const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

/// Draw the live region: the tail of anything still being written, the composer, and what the
/// interface has to say about the turn. Everything above this region has already been printed
/// into the terminal's own scrollback, which is where the transcript lives and where the reader
/// scrolls and selects with the terminal's own mouse.
/// `room` is how many lines the pane may occupy above the live region: the terminal's height less
/// the window and the header. A block that asked for more would be printed anyway and its top would
/// scroll off, so the pane is told the truth and picks a shape that fits.
pub fn draw(f: &mut Frame, app: &App, committed: usize, room: usize) {
    let area = f.area();
    // The badge owns a row, and only while there is something to say: it is the top right of
    // the one region that is reliably on screen, and the readout below is already full at 80
    // columns with the context bar, the cache share and the keys.
    let badge_row = u16::from(app.update.is_some());
    let rows = Layout::vertical([
        Constraint::Length(badge_row),
        Constraint::Min(0),    // the running turn, as far as it fits
        Constraint::Length(1), // rule
        Constraint::Length(1), // composer
        Constraint::Length(1), // readout
    ])
    .split(area);

    if badge_row > 0 {
        badge(f, app, rows[0]);
    }
    transcript(f, app, rows[1], committed, room);
    rule(f, rows[2]);
    composer(f, app, rows[3]);
    readout(f, app, rows[4]);

    if let Some(p) = &app.picker {
        picker(f, area, p);
    } else if let Some(a) = &app.approval {
        approval(f, area, &a.tool, &a.summary, a.choice);
    } else if let Some(m) = &app.menu {
        menu(f, area, rows[3], m);
    }
}

/// The update badge: `↑ 0.6.1 available · eclipse upgrade`, right-aligned on its own row at the
/// top of the live region. Amber, because it is a thing to do rather than a thing that went
/// wrong, and the command is dimmed so the version is what the eye lands on.
fn badge(f: &mut Frame, app: &App, area: Rect) {
    let Some(behind) = &app.update else {
        return;
    };
    let text = behind.line();
    let pad = (area.width as usize).saturating_sub(text.chars().count());
    let spans = vec![
        Span::raw(" ".repeat(pad)),
        Span::styled(
            format!("↑ {} available", behind.shown_latest()),
            Style::default().fg(WARN),
        ),
        Span::styled(" · eclipse upgrade", Style::default().fg(FAINT)),
    ];
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// The header's line: the version, the profile, the session and the workspace. Printed once above
/// the first frame, because it is a fact about the session and facts belong in the transcript.
pub fn header_line(app: &App, width: usize) -> Line<'static> {
    let mut spans = vec![
        Span::styled(" ◐ ", Style::default().fg(ACCENT)),
        Span::styled(
            "eclipse",
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" {} ", env!("CARGO_PKG_VERSION")),
            Style::default().fg(FAINT),
        ),
    ];
    if let Some(p) = &app.profile {
        spans.push(Span::styled(format!(" · {p}"), Style::default().fg(DIM)));
    }
    spans.push(Span::styled(" · ", Style::default().fg(FAINT)));
    spans.push(Span::styled(
        app.session.clone().unwrap_or_else(|| "new session".into()),
        Style::default().fg(DIM),
    ));
    spans.push(Span::styled(" · ", Style::default().fg(FAINT)));
    // Keep the head of the line intact and let the workspace shrink into what is left.
    let used: usize = spans.iter().map(|s| s.content.chars().count()).sum();
    let room = width.saturating_sub(used + 1);
    if room > 8 {
        spans.push(Span::styled(
            super::app::short_path(&app.workspace, room),
            Style::default().fg(FAINT),
        ));
    }
    Line::from(spans)
}

fn rule(f: &mut Frame, area: Rect) {
    let line = "─".repeat(area.width as usize);
    f.render_widget(
        Paragraph::new(Line::from(Span::styled(line, Style::default().fg(FAINT)))),
        area,
    );
}

/// How many wrapped lines of reasoning a folded block shows before the count takes over.
const REASONING_PREVIEW: usize = 5;

/// How many whole wrapped lines fit in `chars` characters, and whether the last one has to be cut.
///
/// `/reasoning clamp <n>` is a character budget, because that is what the five-line preview really
/// is: a number of characters a folded block is allowed to show. Cutting on a line boundary keeps
/// the preview readable; the one ellipsis marks that there was more.
fn clamp_chars(wrapped: &[String], chars: usize) -> (usize, bool) {
    let mut used = 0usize;
    for (i, line) in wrapped.iter().enumerate() {
        let len = line.chars().count();
        if used + len > chars {
            return (i, true);
        }
        used += len;
    }
    (wrapped.len(), false)
}

/// The same lines the pane is windowed from, for tests that need to see what a block renders as.
#[cfg(test)]
pub fn lines_for_test(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
    build_lines_of(&app.blocks, app, width, height)
}

/// The transcript as the terminal will hold it: every block, wrapped to `width`.
pub fn transcript_lines(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
    build_lines_of(&app.blocks, app, width, height)
}

/// The last reasoning block that is already in the scrollback, folded, and longer than its
/// preview — the one `^T` can no longer open in place.
///
/// Reasoning is folded by default, so this is the normal case after a turn ends: the block was
/// printed as five lines and a count, and the rest of it is behind a boundary that only moves
/// forward. `^T` prints it again below rather than pretending it can reach back.
pub fn last_folded_printed_reasoning(app: &App) -> Option<usize> {
    let upto = app.fold.len().min(app.blocks.len()).min(app.printed);
    (0..upto).rev().find(|&i| {
        app.fold.get(i).copied().flatten() == Some(false)
            && matches!(&app.blocks[i], Block::Reasoning { text, .. }
                if text.lines().count() > REASONING_PREVIEW)
    })
}

/// That block's reasoning again, as new lines: a copy under a rule, never an edit of what is
/// above it. What `^T` does for history now that the scrollback cannot be rewritten.
pub fn reasoning_echo(app: &App, index: usize, width: usize) -> Vec<Line<'static>> {
    let indent = "  ";
    let text = match app.blocks.get(index) {
        Some(Block::Reasoning { text, .. }) => text,
        _ => return Vec::new(),
    };
    let wrapped = wrap(text, width.saturating_sub(4));
    let mut out = vec![
        Line::from(""),
        rule_line(width),
        Line::from(Span::styled(
            format!(
                "{indent}💭 reasoning, printed again · {} line(s)",
                wrapped.len()
            ),
            Style::default().fg(FAINT),
        )),
    ];
    for (i, l) in wrapped.iter().enumerate() {
        let head = if i == 0 { "💭 " } else { "   " };
        out.push(Line::from(vec![
            Span::styled(format!("{indent}{head}"), Style::default().fg(FAINT)),
            Span::styled(l.clone(), Style::default().fg(DIM)),
        ]));
    }
    out.push(rule_line(width));
    out.push(Line::from(""));
    out
}

/// How many blocks are finished, and so may be printed.
///
/// The last block stays back while it is still being written: a line that is still growing
/// would be printed once and then disagree with the next frame. Everything before it is final.
///
/// This is a block count, not a line count, and that is the point: a terminal's scrollback is
/// append-only, but the *height* of what is already in it is not stable across a `^T` or a
/// resize. A watermark in lines would then point into a transcript that has been rearranged
/// around it — printing again what was already printed, and later skipping lines nobody saw.
/// A block boundary survives both, because the blocks themselves are never reordered.
pub fn finished_blocks(app: &App) -> usize {
    match app.blocks.last() {
        Some(Block::Reply { done: false, .. })
        | Some(Block::Reasoning { done: false, .. })
        | Some(Block::Tool {
            state: ToolState::Running,
            ..
        }) => app.blocks.len().saturating_sub(1),
        _ => app.blocks.len(),
    }
}

/// How many lines the first `blocks` blocks take at this width — where a block boundary falls
/// in the current rendering. Used both as the print boundary and as the window's first line, so
/// the two cannot disagree about where history ends.
pub fn line_offset_of(app: &App, blocks: usize, width: usize, height: usize) -> usize {
    let upto = blocks.min(app.blocks.len());
    build_lines_of(&app.blocks[..upto], app, width, height).len()
}

/// How many of the transcript's lines are finished, and so may be printed.
///
/// The printer asks [`line_offset_of`] for its two boundaries and never for this; the tests ask
/// for this, because "how tall is the printed part" is the invariant they are about.
#[cfg(test)]
pub fn stable_line_count(app: &App, width: usize, height: usize) -> usize {
    line_offset_of(app, finished_blocks(app), width, height)
}

/// A rule across the transcript. A turn is easier to find with the eye when it is framed than when
/// it is only a line of differently coloured text: the frame says "this is one exchange" without a
/// word of explanation.
fn rule_line(width: usize) -> Line<'static> {
    Line::from(Span::styled(
        "─".repeat(width.max(1)),
        Style::default().fg(FAINT),
    ))
}

/// Every block, wrapped to `width`, as styled lines ready to be windowed.
fn build_lines_of(blocks: &[Block], app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
    let mut out: Vec<Line<'static>> = Vec::new();
    let indent = "  ";
    // True when the block just drawn already ended on a rule: two rules in a row is a seam that
    // reads as a mistake, and it is the one thing that gives a framed transcript away as assembled.
    let mut on_rule = false;
    for (out_block_index, block) in blocks.iter().enumerate() {
        match block {
            Block::Welcome(welcome) => {
                out.extend(welcome_fitted(
                    welcome,
                    app.session.as_deref(),
                    width,
                    height,
                ));
                on_rule = false;
            }
            Block::User(text) => {
                out.push(rule_line(width));
                let wrapped = wrap(text, width.saturating_sub(2));
                for (i, l) in wrapped.iter().enumerate() {
                    if i == 0 {
                        out.push(Line::from(vec![
                            Span::styled("❯ ", Style::default().fg(ACCENT)),
                            Span::styled(l.clone(), Style::default().fg(USER)),
                        ]));
                    } else {
                        out.push(Line::from(vec![
                            Span::styled(indent.to_string(), Style::default()),
                            Span::styled(l.clone(), Style::default().fg(USER)),
                        ]));
                    }
                }
                out.push(rule_line(width));
                out.push(Line::from(""));
                on_rule = true;
            }
            Block::Reply { text, done } => {
                // A message with no text is a turn that only called tools. Its calls are printed
                // above; an empty card with a name on it would say nothing and frame nothing.
                if text.trim().is_empty() && *done {
                    continue;
                }
                // The answer gets a rule and a name, the way the question got a frame: the two are
                // different voices in one column, and the eye should not have to work that out from
                // colour alone. After a question or a tool call the rule is already there.
                if !on_rule {
                    out.push(rule_line(width));
                }
                out.push(Line::from(vec![
                    Span::styled("◐ ", Style::default().fg(ACCENT)),
                    Span::styled("eclipse", Style::default().fg(ACCENT)),
                ]));
                let wrapped = wrap(text, width.saturating_sub(2));
                for l in &wrapped {
                    out.push(Line::from(vec![
                        Span::styled(indent.to_string(), Style::default()),
                        Span::styled(l.clone(), Style::default()),
                    ]));
                }
                if !done {
                    out.push(Line::from(Span::styled(
                        format!("{indent}▌"),
                        Style::default().fg(ACCENT),
                    )));
                }
                if *done {
                    out.push(rule_line(width));
                }
                out.push(Line::from(""));
                on_rule = *done;
            }
            Block::Reasoning { text, done } => {
                // `/reasoning hide`: no block at all. Nothing is lost — the text is in the session —
                // and a hidden block contributes no lines, so the printer's count stays honest.
                let display = app.display_for(out_block_index);
                if display.hidden() {
                    continue;
                }
                let wrapped = wrap(text, width.saturating_sub(4));
                // The fold state this block renders at: its own, once it has been printed, so a
                // line already in the scrollback cannot change height under it. `^T` still opens
                // the tail — everything not yet printed — which is the only part it can.
                let open = app.fold_for(out_block_index) || display.unfolded();
                // Folded, the block is a status line, not a wall of dim text: five lines and a
                // count that grows while the model is still going, which is what tells a person
                // the run is alive. `^T` opens it for good, and `/reasoning full` keeps it open.
                // `/reasoning clamp <n>` caps the preview by characters and marks the cut.
                let cut = display.clamp().map(|chars| clamp_chars(&wrapped, chars));
                let shown: &[String] = if open {
                    &wrapped
                } else {
                    match &cut {
                        Some(cut) => &wrapped[..wrapped.len().min(cut.0)],
                        None => &wrapped[..wrapped.len().min(REASONING_PREVIEW)],
                    }
                };
                for (i, l) in shown.iter().enumerate() {
                    let head = if i == 0 { "💭 " } else { "  " };
                    // One ellipsis where a character clamp cut the preview, so the truncation is
                    // visible in the text rather than only in the count below it.
                    let body = match &cut {
                        Some((_, true)) if !open && i + 1 == shown.len() => format!("{l}…"),
                        _ => l.clone(),
                    };
                    out.push(Line::from(vec![
                        Span::styled(format!("{indent}{head}"), Style::default().fg(FAINT)),
                        Span::styled(body, Style::default().fg(DIM)),
                    ]));
                }
                let hidden = wrapped.len().saturating_sub(shown.len());
                if hidden > 0 || !done || !shown.is_empty() {
                    let mut tail = String::new();
                    if hidden > 0 {
                        tail.push_str(&format!("+{hidden} line(s)"));
                    }
                    if !*done {
                        if !tail.is_empty() {
                            tail.push_str(" · ");
                        }
                        tail.push_str("thinking");
                    }
                    if !open && (hidden > 0 || !*done) {
                        if !tail.is_empty() {
                            tail.push_str(" · ");
                        }
                        // A block that is still on screen can be opened in place. One already
                        // handed to the scrollback cannot — a terminal only appends — so the
                        // promise has to change with it, or the tail is describing something
                        // that will not happen. `^T` prints that text again below instead.
                        if app.fold.get(out_block_index).copied().flatten() == Some(false) {
                            tail.push_str("^T prints it below");
                        } else {
                            tail.push_str("^T shows it all");
                        }
                    }
                    if !tail.is_empty() {
                        let colour = if *done { FAINT } else { ACCENT };
                        out.push(Line::from(vec![
                            Span::styled(format!("{indent}  "), Style::default()),
                            Span::styled(tail, Style::default().fg(colour)),
                        ]));
                    }
                }
                out.push(Line::from(""));
            }
            Block::Tool {
                name,
                args,
                state,
                output,
                ..
            } => {
                // One line per call. What a call printed belongs in the log, not in the
                // conversation: three lines of exit code and stdout per call buries the answer the
                // reader is actually waiting for. The glyph says how it went without a word.
                //
                // A refusal is not a failure — nothing broke, someone said no — so it gets its own
                // mark rather than the cross.
                let refused = *state == ToolState::Failed && output.contains("declined");
                let (glyph, colour) = match state {
                    ToolState::Running => ("⏺", WARN),
                    ToolState::Ok => ("✓", OK),
                    ToolState::Failed if refused => ("⊘", WARN),
                    ToolState::Failed => ("✗", BAD),
                };
                let call = one_line(args);
                let call = if call.is_empty() {
                    name.clone()
                } else {
                    format!("{name}({call})")
                };
                // The tick is the signal, so the call itself stays quiet unless it failed.
                let body = if *state == ToolState::Failed {
                    colour
                } else {
                    DIM
                };
                let room = width.saturating_sub(indent.len() + 2);
                out.push(Line::from(vec![
                    Span::styled(format!("{indent}{glyph} "), Style::default().fg(colour)),
                    Span::styled(truncate(&call, room), Style::default().fg(body)),
                ]));
                on_rule = false;
            }
            Block::Note { kind, text } => {
                let (glyph, colour) = match kind {
                    NoteKind::Info => ("·", DIM),
                    NoteKind::Warn => ("!", WARN),
                    NoteKind::Error => ("✗", BAD),
                };
                on_rule = false;
                for (i, l) in wrap(text, width.saturating_sub(4)).iter().enumerate() {
                    let head = if i == 0 { glyph } else { " " };
                    out.push(Line::from(vec![
                        Span::styled(format!("{indent}{head} "), Style::default().fg(colour)),
                        Span::styled(l.clone(), Style::default().fg(colour)),
                    ]));
                }
            }
        }
    }
    out
}

/// The wordmark: seven letters, five rows, four columns each, one column between. Every glyph is
/// exactly four wide — a narrower letter shifts everything after it and the word stops reading as
/// a word.
const WORDMARK: [[&str; 5]; 7] = [
    ["█████", "█    ", "████ ", "█    ", "█████"], // E
    ["▄███▄", "█    ", "█    ", "█    ", "▀███▀"], // C
    ["█    ", "█    ", "█    ", "█    ", "█████"], // L
    ["█████", "  █  ", "  █  ", "  █  ", "█████"], // I
    ["████ ", "█   █", "████ ", "█    ", "█    "], // P
    ["▄███▄", "█    ", "▀███▄", "    █", "▀███▀"], // S
    ["█████", "█    ", "████ ", "█    ", "█████"], // E
];

/// Width as drawn: five cells per letter, two between. One cell was not enough — at one the
/// letters touch and `ECLIPSE` reads as a row of blocks.
const WORDMARK_COLS: usize = 7 * 5 + 6 * 2;

/// Render the wordmark into five rows of equal width.
fn wordmark() -> Vec<String> {
    (0..5)
        .map(|row| {
            WORDMARK
                .iter()
                .map(|letter| letter[row])
                .collect::<Vec<_>>()
                .join("  ")
        })
        .collect()
}

/// Where a wordmark row sits in its gradient: the top row is the brightest.
fn wordmark_row_colour(row: usize, rows: usize) -> Color {
    let t = if rows <= 1 {
        0.0
    } else {
        row as f32 / (rows - 1) as f32
    };
    let (Color::Rgb(r0, g0, b0), Color::Rgb(r1, g1, b1)) = (WORDMARK_TOP, WORDMARK_FOOT) else {
        return WORDMARK_TOP;
    };
    let mix = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;
    Color::Rgb(mix(r0, r1), mix(g0, g1), mix(b0, b1))
}

/// `session` comes from the app rather than the pane: the pane is drawn once at startup, before
/// a session id exists, and a banner that keeps saying "new" after the first message is a lie.
/// Build a line that is never wider than `width`, whatever the caller passes in. The pane is the
/// only place that draws values the program does not control (an endpoint, a workspace path), so
/// trimming happens here rather than at each call site.
fn fitting(pairs: Vec<(String, Style)>, width: usize) -> Line<'static> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut used = 0usize;
    for (text, style) in pairs {
        let room = width.saturating_sub(used);
        if room == 0 {
            break;
        }
        let text = truncate(&text, room);
        let n = text.chars().count();
        if n == 0 {
            break;
        }
        used += n;
        spans.push(Span::styled(text, style));
        if used >= width {
            break;
        }
    }
    Line::from(spans)
}

#[cfg(test)]
fn welcome_lines(welcome: &Welcome, session: Option<&str>, width: usize) -> Vec<Line<'static>> {
    welcome_fitted(welcome, session, width, usize::MAX)
}

/// The pane in the arrangement it can *afford*. Height is the constraint that bit: a pane asking
/// for more lines than the terminal has is scrolled, and the line that scrolls off the top of a
/// pane is its first.
fn welcome_fitted(
    welcome: &Welcome,
    session: Option<&str>,
    width: usize,
    height: usize,
) -> Vec<Line<'static>> {
    let facts = facts(welcome, session);

    // The picture beats the lists and the lists beat the picture's own height: on a short terminal
    // the art gives way last, but it does give way — a pane asking for more lines than the
    // terminal has is scrolled, and the first thing to scroll off is the top of the letters.
    for (art, tools, skills) in [
        (true, true, true),
        (true, true, false),
        (true, false, false),
        (false, false, false),
    ] {
        let lines = pane(welcome, &facts, width, art, tools, skills);
        if lines.len() <= height {
            return lines;
        }
    }
    pane(welcome, &facts, width, false, false, false)
}

fn facts(welcome: &Welcome, session: Option<&str>) -> Vec<(&'static str, String)> {
    let mut facts: Vec<(&'static str, String)> = vec![
        ("version", welcome.version.clone()),
        ("endpoint", welcome.endpoint.clone()),
        ("workspace", welcome.workspace.clone()),
        (
            "session",
            session
                .map(crate::status::short_session)
                .unwrap_or_else(|| "new".to_string()),
        ),
    ];
    if let Some(profile) = &welcome.profile {
        facts.insert(1, ("profile", profile.clone()));
    }
    // The state, not the history: this block is drawn once, and the readout under the prompt is
    // what keeps saying it. A `--yes` run has to be visible from the first frame, though — it is
    // the only warning before the first tool call.
    facts.push((
        "approvals",
        if welcome.approvals { "auto" } else { "ask" }.to_string(),
    ));
    facts
}

/// Widest label plus a two-space gutter, so `workspace` lines up with `model` rather than
/// sitting one space off.
fn label_width(facts: &[(&str, String)]) -> usize {
    facts
        .iter()
        .map(|(l, _)| l.chars().count())
        .max()
        .unwrap_or(0)
        + 2
}

/// The launch hint, in the widest form the terminal can hold.
///
/// This row is the whole summary of the interface that a new person gets, so it carries the one
/// thing nothing else tells them: `!command` runs a shell command here without spending a turn or
/// a token. It is in `/help` and in the user guide, but nobody reads `/help` before their first
/// question, and a feature that is only discoverable by someone already looking for it does not
/// exist. `/model` gave up its place in this row: the status line under the composer already
/// names the model, so the row was spending its width on something already on screen.
///
/// Three tiers, each one item shorter than the last, because the row is a single line and a
/// truncated hint is worse than a shorter one.
fn hints(width: usize) -> Vec<(String, Style)> {
    const SEP: &str = "   ·   ";
    let accent = Style::default().fg(ACCENT);
    let faint = Style::default().fg(FAINT);
    let tiers: [&[(&str, Style)]; 3] = [
        &[
            ("/", accent),
            (" commands", faint),
            (SEP, faint),
            ("!command", accent),
            (" runs a shell command", faint),
            (SEP, faint),
            ("^D", accent),
            (" quits", faint),
        ],
        &[
            ("/", accent),
            (" commands", faint),
            (SEP, faint),
            ("!command", accent),
            (" runs a shell", faint),
            (SEP, faint),
            ("^D", accent),
            (" quits", faint),
        ],
        &[
            ("/", accent),
            (" commands", faint),
            (SEP, faint),
            ("!", accent),
            (" shell", faint),
            (SEP, faint),
            ("^D", accent),
            (" quits", faint),
        ],
    ];
    let fits =
        |t: &[(&str, Style)]| -> usize { t.iter().map(|(text, _)| text.chars().count()).sum() };
    let chosen = tiers
        .iter()
        .find(|t| fits(t) <= width)
        .or(tiers.last())
        .copied()
        .unwrap_or_default();
    chosen
        .iter()
        .map(|(text, style)| (text.to_string(), *style))
        .collect()
}

/// The pane itself, with or without its wordmark and its two lists.
fn pane(
    welcome: &Welcome,
    facts: &[(&'static str, String)],
    width: usize,
    with_art: bool,
    with_tools: bool,
    with_skills: bool,
) -> Vec<Line<'static>> {
    let mut out: Vec<Line<'static>> = Vec::new();
    let label_width = label_width(facts);

    // The wordmark when the terminal can hold it, the name in words when it cannot: a block
    // wordmark that wraps reads as a row of debris, and forty-seven columns is what the letters
    // cost. The version is a fact below, not a suffix on the drawing.
    if with_art && width >= WORDMARK_COLS {
        // Two blank rows above the letters and two below: the mark was sitting flush under the
        // top edge and one row above `version`, which read as a table heading crowding its first
        // row. Space is what separates a mark from the text it introduces.
        out.push(Line::from(""));
        out.push(Line::from(""));
        for (row, line) in wordmark().iter().enumerate() {
            out.push(Line::from(Span::styled(
                line.clone(),
                Style::default().fg(wordmark_row_colour(row, 5)),
            )));
        }
        out.push(Line::from(""));
        out.push(Line::from(""));
    } else {
        out.push(Line::from(vec![
            Span::styled("ECLIPSE", Style::default().fg(ACCENT)),
            Span::styled(format!(" {}", welcome.version), Style::default().fg(DIM)),
        ]));
        out.push(Line::from(""));
    }
    for (label, value) in facts.iter() {
        out.push(fitting(
            vec![
                (format!("{label:<label_width$}"), Style::default().fg(FAINT)),
                (value.clone(), Style::default().fg(colour_for(label, value))),
            ],
            width,
        ));
    }

    if with_tools {
        out.push(Line::from(""));
        let count = welcome.tool_count();
        out.push(fitting(
            vec![
                ("tools".to_string(), Style::default().fg(FAINT)),
                (format!("  {count}"), Style::default().fg(OK)),
                (" offered".to_string(), Style::default().fg(FAINT)),
            ],
            width,
        ));
        for (source, names) in &welcome.groups {
            wrapped_group(&mut out, source, names, width);
        }
    }

    if with_skills && welcome.skill_count() > 0 {
        out.push(fitting(
            vec![
                ("skills".to_string(), Style::default().fg(FAINT)),
                (
                    format!("  {}", welcome.skill_count()),
                    Style::default().fg(OK),
                ),
                (" available".to_string(), Style::default().fg(FAINT)),
            ],
            width,
        ));
        for (source, names) in &welcome.skills {
            wrapped_group(&mut out, source, names, width);
        }
    }

    out.push(Line::from(""));
    out.push(fitting(hints(width), width));
    out.push(Line::from(""));
    out
}

/// One `source: a, b, c` line of the pane, wrapped by hand: a tool or skill list can be long,
/// and one line running off the right edge is the only way this pane can look broken.
fn wrapped_group(out: &mut Vec<Line<'static>>, source: &str, names: &[String], width: usize) {
    let mut line = truncate(&format!("  {source}: "), width.saturating_sub(1));
    for (i, name) in names.iter().enumerate() {
        let piece = if i == 0 {
            name.clone()
        } else {
            format!(", {name}")
        };
        if line.chars().count() + piece.chars().count() > width.saturating_sub(1) {
            // A wrapped line does not start with the separator: `, skill_view` at the left edge
            // reads as a typo, and the indent already says the line continues.
            out.push(Line::from(Span::styled(
                line.trim_end().to_string(),
                Style::default().fg(DIM),
            )));
            line = format!("    {name}");
            continue;
        }
        line.push_str(&piece);
    }
    out.push(Line::from(Span::styled(line, Style::default().fg(DIM))));
}

/// Which fact is worth the reader's eye: the model answers, everything else is provenance.
fn colour_for(label: &str, value: &str) -> Color {
    match (label, value) {
        ("model", _) => USER,
        ("profile", _) => OK,
        // Amber, and only when it is on: `ask` is the ordinary answer and must not be dressed up.
        ("approvals", "auto") => ACCENT,
        _ => DIM,
    }
}

fn transcript(f: &mut Frame, app: &App, area: Rect, printed: usize, room: usize) {
    // The same budget the printer used: a block built against a different one comes out a different
    // shape. `printed` is a block count, so it is turned into this frame's line offset — the window
    // and the printer agree on which block history ends at even when the height of what is behind
    // it changed under a `^T` or a resize.
    let lines = build_lines_of(&app.blocks, app, area.width as usize, room);
    let skip = line_offset_of(app, printed, area.width as usize, room);
    // Whatever is before `skip` is already in the terminal's scrollback. What is left is the turn
    // in flight, and only its tail can be on screen at once.
    let rest: Vec<Line> = lines.into_iter().skip(skip).collect();
    let (height, total) = (area.height as usize, rest.len());
    let visible = if total > height {
        rest.into_iter().skip(total - height).collect()
    } else {
        rest
    };
    f.render_widget(Paragraph::new(Text::from(visible)), area);
}

/// The `/resume` list: a modal over the transcript, built the same way as the approval modal —
/// one way of asking the reader to choose something, not two.
fn picker(f: &mut Frame, area: Rect, picker: &Picker) {
    let w = (area.width as f32 * 0.7) as u16;
    // Title, blank, the rows, blank, keys. Ask for a detail line per row and fall back to one
    // line per row when the frame cannot give it — better a short list than a list whose rows
    // are indistinguishable.
    let count = picker.items.len() as u16;
    // A row is one line, or more when it can afford its detail: a stored session adds its facts
    // line, a route adds `current` and its endpoint. Seven lines are the frame itself — two
    // borders, the title, the filter line, a blank, a blank and the keys — so the box asks for
    // exactly what it will draw. Under-counting it clipped the key line off a two-route list.
    let per_row = match picker.kind {
        crate::tui::app::PickerKind::Provider => 3,
        _ => 2,
    };
    let want = count.saturating_mul(per_row).saturating_add(7);
    let h = want.min(area.height);
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = Rect {
        x,
        y,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);

    // One title for both lists, with the word that changes: what is being chosen, and how many
    // there are. A model list has no "stored"; it has what the endpoint just said it serves.
    let count = format!("  {}", picker.count_label());
    let mut lines = vec![
        Line::from(vec![
            Span::styled(
                match picker.kind {
                    crate::tui::app::PickerKind::Model => "Switch ",
                    crate::tui::app::PickerKind::Provider => "Ask ",
                    crate::tui::app::PickerKind::Sessions => "Resume ",
                    // Opening a task opens the session it runs in: the same verb, and the one the
                    // reader is about to do.
                    crate::tui::app::PickerKind::Tasks => "Open ",
                },
                Style::default().fg(DIM),
            ),
            Span::styled(picker.title, Style::default().fg(ACCENT)),
            Span::styled(count, Style::default().fg(FAINT)),
        ]),
        // The filter line is always drawn, empty or not: a list you can type into must say so,
        // or nobody types into it.
        Line::from(vec![
            Span::styled(
                format!(
                    " {} ",
                    if picker.query.is_empty() {
                        "filter"
                    } else {
                        " "
                    }
                ),
                Style::default().fg(FAINT),
            ),
            Span::styled(picker.query.clone(), Style::default().fg(DIM)),
            if picker.query.is_empty() {
                Span::styled("type to narrow", Style::default().fg(FAINT))
            } else {
                Span::raw("")
            },
        ]),
        Line::from(""),
    ];
    // The room left after the frame's own six lines, and whether every row can afford its
    // detail in it.
    let room = rect.height.saturating_sub(6) as usize;
    let detail = room >= picker.items.len() * per_row as usize;
    let rows = if detail {
        room / per_row as usize
    } else {
        room
    };
    // A window that follows the cursor rather than moving the list.
    let first = picker.cursor.saturating_sub(rows.saturating_sub(1));
    for (i, item) in picker.items.iter().enumerate().skip(first).take(rows) {
        let current = i == picker.cursor;
        let mut spans = Vec::new();
        if current {
            spans.push(Span::styled("  › ", Style::default().fg(ACCENT)));
            spans.push(Span::styled(
                item.label(),
                Style::default().add_modifier(Modifier::BOLD),
            ));
        } else {
            spans.push(Span::styled(
                format!("    {}", item.label()),
                Style::default().fg(DIM),
            ));
        }
        // The one fact a model list needs beyond names — `current` beside the model in use,
        // on the same line, not a line below it.
        if !item.note.is_empty() && picker.kind == crate::tui::app::PickerKind::Model {
            spans.push(Span::styled(
                format!("  {}", item.note),
                Style::default().fg(FAINT),
            ));
        }
        lines.push(Line::from(spans));
        if !item.note.is_empty() && picker.kind != crate::tui::app::PickerKind::Model {
            // `current` beside the model in use: the one fact a model list needs beyond names.
            lines.push(Line::from(Span::styled(
                format!("     {}", item.note),
                Style::default().fg(FAINT),
            )));
            // A route also says where it goes. Two routes called `cheap` and `fast` on the same
            // box are told apart by nothing else, and `current` has no room for it.
            if picker.kind == crate::tui::app::PickerKind::Provider && detail {
                lines.push(Line::from(Span::styled(
                    format!("     {}", item.preview),
                    Style::default().fg(FAINT),
                )));
            }
            // A task's detail is where it lives and what it last did: the id is what
            // `eclipse --plain -s <id>` needs, and the last line is why a row is worth opening.
            if picker.kind == crate::tui::app::PickerKind::Tasks && detail {
                lines.push(Line::from(Span::styled(
                    format!("     {} · {}", item.id, item.preview),
                    Style::default().fg(FAINT),
                )));
            }
        } else if picker.kind == crate::tui::app::PickerKind::Provider && detail {
            lines.push(Line::from(Span::styled(
                format!("     {}", item.preview),
                Style::default().fg(FAINT),
            )));
        } else if detail && picker.kind == crate::tui::app::PickerKind::Sessions {
            // When and how much: how two similar previews are told apart. `pinned` explains why
            // an old session is above a newer one.
            let pinned = if item.note.is_empty() {
                String::new()
            } else {
                format!(" · {}", item.note)
            };
            lines.push(Line::from(Span::styled(
                format!(
                    "     {} · {} {}{} · {}",
                    item.ago,
                    item.messages,
                    if item.messages == 1 {
                        "message"
                    } else {
                        "messages"
                    },
                    pinned,
                    item.id
                ),
                Style::default().fg(FAINT),
            )));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "↑↓ choose · type to filter · enter open · esc clear/close",
        Style::default().fg(FAINT),
    )));

    let block = Box_::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(ACCENT))
        // The frame is named for the question it is asking. It said "resume" for every list —
        // the model list and the provider list included — which reads as the wrong menu.
        .title(Span::styled(
            match picker.kind {
                crate::tui::app::PickerKind::Sessions => " resume ",
                crate::tui::app::PickerKind::Provider => " provider ",
                crate::tui::app::PickerKind::Model => " model ",
                crate::tui::app::PickerKind::Tasks => " tasks ",
            },
            Style::default().fg(ACCENT),
        ));
    f.render_widget(
        Paragraph::new(Text::from(lines))
            .block(block)
            .wrap(Wrap { trim: false })
            .alignment(Alignment::Left),
        rect,
    );
}

/// The most command rows the menu shows; the rest are counted on a `… N more` line.
const MENU_ROWS: usize = 8;

/// The menu's lines, each at most `width` columns: `› /name args  help`, the cursor's row
/// marked and bold, and a `… N more` line when the list is longer than the window.
fn menu_lines(menu: &Menu, rows: usize, width: usize) -> Vec<Line<'static>> {
    // A line that is a command word with nothing matching it keeps the menu, and the menu says what
    // is wrong rather than disappearing: a list that vanishes reads as "the menu broke", and it left
    // no way back but clearing the line (#253).
    if menu.items.is_empty() {
        return vec![Line::from(Span::styled(
            truncate("  no command matches — esc closes this", width),
            Style::default().fg(FAINT),
        ))];
    }
    let rows = rows.min(MENU_ROWS).min(menu.items.len());
    let label_width = menu
        .items
        .iter()
        .map(|c| c.label().chars().count())
        .max()
        .unwrap_or(0);
    // A window that follows the cursor rather than moving the list.
    let first = menu.cursor.saturating_sub(rows.saturating_sub(1));
    let mut lines: Vec<Line<'static>> = menu
        .items
        .iter()
        .enumerate()
        .skip(first)
        .take(rows)
        .map(|(i, c)| {
            let current = i == menu.cursor;
            let mark = if current { "› " } else { "  " };
            let text = truncate(
                &format!("{mark}{:<label_width$}  {}", c.label(), c.help),
                width,
            );
            if current {
                Line::from(Span::styled(
                    text,
                    Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
                ))
            } else {
                Line::from(Span::styled(text, Style::default().fg(DIM)))
            }
        })
        .collect();
    let hidden = menu.items.len() - lines.len();
    if hidden > 0 {
        lines.push(Line::from(Span::styled(
            truncate(&format!("  … {hidden} more"), width),
            Style::default().fg(FAINT),
        )));
    }
    lines
}

/// The command list, just above the line it completes. Takes the room it needs from the
/// transcript, and fewer rows when the frame is short rather than spilling past it.
fn menu(f: &mut Frame, area: Rect, composer: Rect, menu: &Menu) {
    // Borders cost two rows; the header keeps its own.
    let room = composer.y.saturating_sub(area.y + 1) as usize;
    if room < 3 || area.width < 6 {
        return;
    }
    let wanted = menu.items.len().max(1);
    let mut rows = MENU_ROWS.min(wanted).min(room - 2);
    // A "more" line takes a row of its own, so give a row up for it when the list is cut.
    if wanted > rows && rows + 3 > room {
        rows = rows.saturating_sub(1).max(1);
    }
    let mut lines = menu_lines(menu, rows, area.width as usize - 2);
    lines.truncate(room - 2);
    let h = (lines.len() + 2) as u16;
    let rect = Rect {
        x: area.x,
        y: composer.y - h,
        width: area.width,
        height: h,
    };
    f.render_widget(Clear, rect);
    let block = Box_::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(ACCENT))
        .title(Span::styled(" commands ", Style::default().fg(ACCENT)));
    f.render_widget(Paragraph::new(Text::from(lines)).block(block), rect);
}

fn composer(f: &mut Frame, app: &App, area: Rect) {
    let prompt = Span::styled("❯ ", Style::default().fg(ACCENT));
    if app.approval.is_some() {
        f.render_widget(
            Paragraph::new(Line::from(vec![
                prompt,
                Span::styled("waiting for a decision (y / n)", Style::default().fg(WARN)),
            ])),
            area,
        );
        return;
    }
    let hint = if app.busy() {
        Some(Span::styled(
            "  esc stops the run",
            Style::default().fg(FAINT),
        ))
    } else if app.input.is_empty() {
        Some(Span::styled(
            "  ask anything, or / for commands",
            Style::default().fg(FAINT),
        ))
    } else {
        None
    };

    // Keep the cursor on screen: show the tail of a long line, not its head. Everything here is
    // counted in terminal *cells*, not `char`s — a CJK character or an emoji is one `char` and two
    // cells, so counting chars put the hardware cursor left of the real insertion point and made
    // `truncate` clip a wide line short of the edge (`#409`).
    let room = area.width.saturating_sub(2) as usize;
    let chars: Vec<char> = app.input.chars().collect();
    let cursor = app.cursor.min(chars.len());
    let (first, before_cursor) = prompt_window(&chars, cursor, room);
    let shown: String = chars[first..].iter().collect();
    let shown = truncate(&shown, room);

    let mut spans = vec![prompt, Span::styled(shown, Style::default())];
    if let Some(h) = hint {
        spans.push(h);
    }
    f.render_widget(Paragraph::new(Line::from(spans)), area);
    if !app.busy() && app.approval.is_none() {
        let x = area.x + 2 + before_cursor as u16;
        let x = x.min(area.x + area.width.saturating_sub(1));
        f.set_cursor_position((x, area.y));
    }
}

fn readout(f: &mut Frame, app: &App, area: Rect) {
    let s = &app.status;
    let glyph = match &app.activity {
        Activity::Idle => "·".to_string(),
        Activity::Requesting => SPINNER[(app.ticks % 10) as usize].to_string(),
        Activity::Streaming => SPINNER[(app.ticks % 10) as usize].to_string(),
        Activity::Tool(_) => "⚙".to_string(),
    };
    let state = match &app.activity {
        Activity::Idle => String::new(),
        Activity::Requesting => " thinking".to_string(),
        Activity::Streaming => " streaming".to_string(),
        Activity::Tool(t) => format!(" {t}"),
    };

    let mut left = vec![
        Span::styled(format!(" {glyph} "), Style::default().fg(ACCENT)),
        Span::styled(s.model.clone(), Style::default().fg(DIM)),
        Span::styled(state, Style::default().fg(WARN)),
    ];
    if app.running {
        left.push(Span::styled(
            format!(" · {:.1}s", s.started.elapsed().as_secs_f64()),
            Style::default().fg(FAINT),
        ));
    }
    if app.listing_models {
        left.push(Span::styled(
            " · listing models",
            Style::default().fg(FAINT),
        ));
    }
    // `#264`: the effort the next request carries, every frame. Amber only while the session is
    // the reason — the file's own level is the ordinary case and does not need shouting.
    if let Some(effort) = &s.effort {
        left.push(Span::styled(
            format!(" · effort {}", effort.label),
            Style::default().fg(if effort.session { ACCENT } else { FAINT }),
        ));
    }
    // One field, in the accent colour, for as long as it is on. This is the whole point of
    // `/yolo`: an interface that can skip every dangerous call says so while it is skipping them.
    if app.yolo.on() {
        left.push(Span::styled(
            " · approvals: auto",
            Style::default().fg(ACCENT),
        ));
    } else if s.judged {
        // `#340`: `smart` is on, so some calls run without a card. Silent for `ask`, which is the
        // default and the ordinary case — the word here means "something is deciding for you".
        left.push(Span::styled(
            " · approvals: judged",
            Style::default().fg(ACCENT),
        ));
    }

    let mut right: Vec<Span> = Vec::new();
    // The compaction tripwire is the one cell of the bar that is not "how full" but "when does
    // it start paying": it is coloured apart from the fill, and the whole readout turns warm
    // once the prompt has gone past it.
    let passed = app::context_passed(s);
    let text = app::context_text(s, 10);
    let mut rest = text.split(status::MARKER);
    if let Some(head) = rest.next() {
        right.push(Span::styled(
            head.to_string(),
            Style::default().fg(if passed { WARN } else { DIM }),
        ));
    }
    for part in rest {
        right.push(Span::styled(
            status::MARKER.to_string(),
            Style::default().fg(BAD),
        ));
        if !part.is_empty() {
            right.push(Span::styled(
                part.to_string(),
                Style::default().fg(if passed { WARN } else { DIM }),
            ));
        }
    }
    if let Some(last) = &s.last {
        right.push(Span::styled(" · ", Style::default().fg(FAINT)));
        right.push(Span::styled(
            app::tokens_per_sec_text(last),
            Style::default().fg(DIM),
        ));
        if let Some(share) = app::cache_share(last) {
            right.push(Span::styled(" · ", Style::default().fg(FAINT)));
            right.push(Span::styled(
                format!("⚡{:.0}%", share * 100.0),
                Style::default().fg(OK),
            ));
        }
    }
    if s.totals.turns > 1 {
        right.push(Span::styled(" · ", Style::default().fg(FAINT)));
        right.push(Span::styled(
            format!(
                "Σ {}/{}",
                status::short_tokens(s.totals.prompt_tokens),
                status::short_tokens(s.totals.completion_tokens)
            ),
            Style::default().fg(FAINT),
        ));
    }
    right.push(Span::styled(" · ", Style::default().fg(FAINT)));
    right.push(Span::styled(
        if app.busy() {
            "esc stop "
        } else {
            "/help · ⌃D quit "
        },
        Style::default().fg(FAINT),
    ));

    // Right-align by measuring: a Paragraph has no "two ends" mode.
    let left_text: String = left.iter().map(|s| s.content.as_ref()).collect();
    let right_text: String = right.iter().map(|s| s.content.as_ref()).collect();
    let width = area.width as usize;
    let pad = width
        .saturating_sub(left_text.chars().count() + right_text.chars().count())
        .max(1);
    let mut spans = left;
    spans.push(Span::raw(" ".repeat(pad)));
    spans.extend(right);
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

fn approval(f: &mut Frame, area: Rect, tool: &str, summary: &str, choice: Choice) {
    let w = (area.width as f32 * 0.7) as u16;
    // Header, blank, summary, blank, one row per answer, blank, keys.
    let h = (7 + Choice::ALL.len() as u16).min(area.height);
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = Rect {
        x,
        y,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);
    let mut lines = vec![
        Line::from(vec![
            Span::styled("Allow ", Style::default().fg(DIM)),
            Span::styled(
                tool.to_string(),
                Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
            ),
            Span::styled("?", Style::default().fg(DIM)),
        ]),
        Line::from(""),
        Line::from(Span::styled(summary.to_string(), Style::default())),
        Line::from(""),
    ];
    for option in Choice::ALL {
        let label = option.label(tool);
        lines.push(if option == choice {
            Line::from(vec![
                Span::styled("  › ", Style::default().fg(ACCENT)),
                Span::styled(label, Style::default().add_modifier(Modifier::BOLD)),
            ])
        } else {
            Line::from(Span::styled(
                format!("    {label}"),
                Style::default().fg(DIM),
            ))
        });
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "↑↓ move · enter confirm · esc deny",
        Style::default().fg(FAINT),
    )));
    let text = Text::from(lines);
    let block = Box_::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(WARN))
        .title(Span::styled(" approval ", Style::default().fg(WARN)));
    f.render_widget(
        Paragraph::new(text)
            .block(block)
            .wrap(Wrap { trim: false })
            .alignment(Alignment::Left),
        rect,
    );
}

// ---- text helpers ---------------------------------------------------------------

/// Collapse whitespace so a value can sit on one line.
fn one_line(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Where to start showing a `room`-cell-wide input line, and how many cells lie between that start
/// and the cursor: `(first char, cells before the cursor)`.
///
/// In cells, because a wide character is one `char` and two columns (`#409`). The tail is kept
/// rather than the head, so the cursor is always visible; one cell is reserved for the character
/// under it.
fn prompt_window(chars: &[char], cursor: usize, room: usize) -> (usize, usize) {
    let cursor = cursor.min(chars.len());
    let tail = room.saturating_sub(1);
    let mut cells = 0;
    let mut first = cursor;
    while first > 0 {
        let w = unicode_width::UnicodeWidthChar::width(chars[first - 1]).unwrap_or(0);
        if cells + w > tail {
            break;
        }
        cells += w;
        first -= 1;
    }
    (first, cells)
}

/// The longest prefix of `s` that fits in `width` cells, and the rest.
fn split_at_cells(s: &str, width: usize) -> (String, String) {
    let mut head = String::new();
    let mut used = 0;
    let mut at = s.len();
    for (i, ch) in s.char_indices() {
        let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + w > width {
            at = i;
            break;
        }
        head.push(ch);
        used += w;
    }
    (head, s[at..].to_string())
}

/// Cut to `width` terminal cells with an ellipsis, on a character boundary.
fn truncate(s: &str, width: usize) -> String {
    if unicode_width::UnicodeWidthStr::width(s) <= width {
        return s.to_string();
    }
    let keep = width.saturating_sub(1);
    let (head, _) = split_at_cells(s, keep);
    head + "…"
}

/// Word-wrap to `width`, honouring existing newlines and cutting words that are longer
/// than a line rather than letting them overflow.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let mut out = Vec::new();
    for para in text.split('\n') {
        if para.is_empty() {
            out.push(String::new());
            continue;
        }
        let mut line = String::new();
        for word in para.split(' ') {
            // Cells, not chars: a paragraph of CJK wrapped by `chars().count()` came out twice as
            // wide as the pane and was clipped at the right edge (`#409`).
            let w = UnicodeWidthStr::width(word);
            if line.is_empty() {
                let mut word = word.to_string();
                while UnicodeWidthStr::width(word.as_str()) > width {
                    let (head, rest) = split_at_cells(&word, width);
                    if head.is_empty() {
                        // A character wider than the whole line (a lone wide char in a 1-cell
                        // pane): put it on its own line rather than looping forever.
                        out.push(word.clone());
                        word = String::new();
                        break;
                    }
                    out.push(head);
                    word = rest;
                }
                line = word;
            } else if UnicodeWidthStr::width(line.as_str()) + 1 + w <= width {
                line.push(' ');
                line.push_str(word);
            } else {
                out.push(std::mem::take(&mut line));
                let mut word = word.to_string();
                while UnicodeWidthStr::width(word.as_str()) > width {
                    let (head, rest) = split_at_cells(&word, width);
                    if head.is_empty() {
                        out.push(word.clone());
                        word = String::new();
                        break;
                    }
                    out.push(head);
                    word = rest;
                }
                line = word;
            }
        }
        if !line.is_empty() {
            out.push(line);
        }
    }
    out
}

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

    /// `#409`: a CJK character or an emoji is one `char` and two terminal cells. Counting chars
    /// made the wrapper produce lines twice as wide as the pane, which were then clipped at the
    /// right edge — so the reader lost the end of every wide paragraph.
    #[test]
    fn a_wrapped_paragraph_fits_the_pane_in_cells_not_chars() {
        let para = "中文中文中文中文中文中文中文中文中文中文";
        for width in [4usize, 9, 20, 41] {
            let lines = wrap(para, width);
            for line in &lines {
                assert!(
                    UnicodeWidthStr::width(line.as_str()) <= width,
                    "a {}-cell pane got a {}-cell line: {line:?}",
                    width,
                    UnicodeWidthStr::width(line.as_str())
                );
            }
            // And nothing was dropped on the way: cells in, cells out.
            let out: usize = lines
                .iter()
                .map(|l| UnicodeWidthStr::width(l.as_str()))
                .sum();
            assert_eq!(out, UnicodeWidthStr::width(para), "width {width}");
        }
    }

    #[test]
    fn truncate_counts_cells_so_a_wide_line_stops_at_the_edge() {
        // Six wide characters are twelve cells; a five-cell field holds two of them and the ellipsis.
        assert_eq!(truncate("中文中文中文", 5), "中文…");
        assert_eq!(
            UnicodeWidthStr::width(truncate("中文中文中文", 5).as_str()),
            5
        );
        // A string that fits is returned untouched, wide or not.
        assert_eq!(truncate("中文", 4), "中文");
        assert_eq!(truncate("abc", 3), "abc");
        // Narrow text keeps the old behaviour.
        assert_eq!(truncate("abcdef", 4), "abc…");
        // An emoji is two cells as well.
        assert_eq!(UnicodeWidthStr::width(truncate("🙂🙂🙂", 3).as_str()), 3);
    }

    /// The cursor is placed from this, so it is the bug in `#409` in its purest form: with the
    /// cursor after two wide characters the cell offset is 4, not 2.
    #[test]
    fn the_prompt_window_measures_the_cursor_in_cells() {
        let wide: Vec<char> = "中文中文".chars().collect();
        // Everything visible: the window starts at 0 and the cursor is 4 cells in.
        assert_eq!(prompt_window(&wide, 2, 20), (0, 4));
        // A five-cell field keeps the tail: two wide characters (4 cells) fit in the 4 cells left
        // after reserving one, so the window starts at char 2 and the cursor is 4 cells from it.
        assert_eq!(prompt_window(&wide, 4, 5), (2, 4));
        // Narrow text is unaffected.
        let narrow: Vec<char> = "abcdef".chars().collect();
        assert_eq!(prompt_window(&narrow, 6, 20), (0, 6));
        assert_eq!(prompt_window(&narrow, 6, 4), (3, 3));
        // A cursor past the end is clamped, not trusted.
        assert_eq!(prompt_window(&narrow, 99, 20), (0, 6));
    }

    /// The launch hints are the only place `!command` is ever advertised, so they have to name it
    /// — and keep naming it when the terminal is too narrow for the full sentence (#217).
    #[test]
    fn the_launch_hints_name_the_bang_command() {
        let row = |width: usize| -> String {
            hints(width)
                .into_iter()
                .map(|(text, _)| text)
                .collect::<String>()
        };

        let widest = row(100);
        assert!(
            widest.contains("!command runs a shell command"),
            "the widest row must name it in full: {widest:?}"
        );
        assert!(widest.contains("/ commands") && widest.contains("^D quits"));

        // Each tier is one item shorter, and each fits the width that selected it.
        assert!(row(61).contains("!command runs a shell command"));
        assert!(
            row(53).contains("!command runs a shell"),
            "a tighter row says less about it, not nothing: {:?}",
            row(53)
        );
        assert!(
            row(52).contains("! shell"),
            "the floor still says `!` exists: {:?}",
            row(52)
        );
        assert!(
            row(20).contains("! shell"),
            "and it is the floor, never a gap"
        );
        for width in [61usize, 53, 39] {
            assert!(
                row(width).chars().count() <= width,
                "at {width} columns the hint row overflows: {:?}",
                row(width)
            );
        }

        // And it reaches the pane, which is the only place anyone reads it.
        let w = sample_welcome();
        let pane = text_of(&welcome_fitted(&w, None, 100, 60));
        assert!(
            pane.lines()
                .any(|l| l.contains("!command runs a shell command")),
            "the launch pane must carry the row: {pane}"
        );
    }

    /// `^T` on a block that is already in the scrollback cannot open it in place (#219), so it
    /// prints the reasoning again below. The tail must not promise the version that cannot happen.
    #[test]
    fn a_printed_folded_block_promises_the_echo_not_an_opening() {
        let mut a = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        a.blocks.clear();
        a.blocks.push(Block::Reasoning {
            text: (1..=30).map(|i| format!("thought {i}\n")).collect(),
            done: true,
        });
        a.freeze_printed(finished_blocks(&a));

        let on_screen = text_of(&transcript_lines(&a, 80, 24));
        assert!(
            on_screen.contains("line(s) · ^T prints it below"),
            "the hidden count and the promise survive: {on_screen}"
        );
        assert!(
            on_screen.contains("^T prints it below"),
            "and the promise changes with the block: {on_screen}"
        );
        assert!(!on_screen.contains("^T shows it all"));

        // The echo is the whole block, ruled off, and it names itself as a copy.
        let echo = text_of(&reasoning_echo(&a, 0, 80));
        assert!(echo.contains("reasoning, printed again"));
        for i in [1usize, 17, 30] {
            assert!(
                echo.contains(&format!("thought {i}")),
                "line {i} missing from the echo"
            );
        }
        assert_eq!(last_folded_printed_reasoning(&a), Some(0));
    }

    #[test]
    fn wrapping_respects_words_and_newlines() {
        assert_eq!(wrap("a b c", 10), ["a b c"]);
        assert_eq!(wrap("aaa bbb", 3), ["aaa", "bbb"]);
        assert_eq!(wrap("one\ntwo", 10), ["one", "two"]);
        assert_eq!(wrap("", 5), [""]);
    }

    #[test]
    fn a_word_longer_than_the_line_is_cut_not_overflowed() {
        assert_eq!(wrap("abcdefgh", 3), ["abc", "def", "gh"]);
        for line in wrap("abcdefgh", 3) {
            assert!(line.chars().count() <= 3);
        }
    }

    #[test]
    fn truncation_keeps_character_boundaries() {
        assert_eq!(truncate("héllo", 10), "héllo");
        assert_eq!(truncate("héllo", 4), "hél…");
        assert_eq!(truncate("héllo", 1), "…");
    }

    #[test]
    fn tool_output_is_summarised_to_one_line_for_the_head() {
        assert_eq!(one_line("a\n  b\tc"), "a b c");
    }

    fn sample_welcome() -> Welcome {
        Welcome {
            approvals: false,
            version: "0.1.0".into(),
            model: "basalt-inkling2".into(),
            endpoint: "127.0.0.1:18045".into(),
            profile: None,
            workspace: "/home/max/projects".into(),
            groups: vec![
                (
                    "builtin".to_string(),
                    vec!["fetch".to_string(), "shell".to_string()],
                ),
                ("plugin:notes".to_string(), vec!["note_write".to_string()]),
            ],
            skills: vec![
                ("shared".to_string(), vec!["backup".to_string()]),
                (
                    "workspace".to_string(),
                    vec!["deploy".to_string(), "release-notes".to_string()],
                ),
            ],
        }
    }

    fn text_of(lines: &[Line]) -> String {
        lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn the_pane_draws_the_wordmark_when_there_is_room_and_spells_it_out_when_there_is_not() {
        // The letters are the mark now that the ring is gone, so they are what a wide terminal
        // gets; a narrow one gets the name in words rather than a wrapped block drawing.
        let wide = text_of(&welcome_lines(&sample_welcome(), None, 100));
        let art_rows = wide.lines().filter(|l| l.contains('█')).count();
        assert_eq!(art_rows, 5, "five rows of letters:\n{wide}");
        assert!(
            !wide.contains('\u{2800}'),
            "and no braille ring beside them:\n{wide}"
        );
        assert!(
            !wide.lines().next().unwrap().contains("ECLIPSE"),
            "the name is not spelled out as well:\n{wide}"
        );

        let narrow = text_of(&welcome_lines(&sample_welcome(), None, 40));
        assert!(narrow.contains("ECLIPSE"), "{narrow}");
        assert!(!narrow.contains('█'), "no half-drawn wordmark:\n{narrow}");
        assert!(narrow.contains("workspace"), "the facts stay:\n{narrow}");
    }

    #[test]
    fn the_facts_sit_under_the_name() {
        // The name is the header, then one blank line, then the facts: the version is a fact, not
        // a suffix on the drawing, and nothing shares a line with a block glyph.
        let lines = welcome_lines(&sample_welcome(), None, 100);
        let shown: Vec<String> = lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        let last_art = shown
            .iter()
            .rposition(|l| l.contains('█'))
            .expect("the wordmark is drawn");
        assert!(
            shown[last_art + 1].trim().is_empty() && shown[last_art + 2].trim().is_empty(),
            "two blank rows under the letters, so they do not crowd `version`: {shown:?}"
        );
        assert!(
            shown[last_art + 3].contains("version"),
            "the facts start under that: {shown:?}"
        );
        for (i, line) in shown.iter().enumerate() {
            assert!(
                !(line.contains('█') && line.contains("workspace")),
                "line {i} draws a fact over the art: {line:?}"
            );
        }
    }

    #[test]
    fn the_pane_never_draws_past_the_width() {
        // The one way this pane can look broken is a line running off the right edge, so sweep
        // the widths rather than trusting the one terminal it was built against.
        for width in (20..140).step_by(3) {
            for line in welcome_lines(&sample_welcome(), Some("1795875858162-956151-0"), width) {
                let drawn: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();
                assert!(drawn <= width, "{drawn} chars at width {width}: {line:?}");
            }
        }
    }

    #[test]
    fn a_wrapped_tool_list_does_not_start_its_continuation_with_a_comma() {
        let mut welcome = sample_welcome();
        welcome.groups = vec![(
            "builtin".to_string(),
            (0..40).map(|i| format!("tool{i}")).collect(),
        )];
        let shown = text_of(&welcome_lines(&welcome, None, 60));
        for line in shown.lines().skip(1) {
            assert!(
                !line.trim_start().starts_with(','),
                "a line opens with a comma:\n{shown}"
            );
        }
        assert!(shown.contains("tool0"), "{shown}");
        assert!(shown.contains("tool39"), "the last one is still listed");
    }

    #[test]
    fn the_pane_never_asks_for_more_lines_than_the_terminal_has() {
        // A pane taller than its area is scrolled, and what scrolls off the top of a splash is
        // its first line — which is how the wordmark lost a row and read as nonsense.
        for width in [40usize, 64, 80, 96, 140] {
            for height in 12usize..=44 {
                let lines = welcome_fitted(&sample_welcome(), None, width, height);
                assert!(
                    lines.len() <= height,
                    "{width}x{height}: the pane asks for {} lines",
                    lines.len()
                );
            }
        }
    }

    /// `#226`: the launch panel says it for a `--yes` run, and `ask` is drawn plainly — this is the
    /// only warning a person gets before the first tool call answers itself.
    #[test]
    fn the_pane_says_approvals_and_ambers_the_automatic_one() {
        let mut welcome = sample_welcome();
        welcome.approvals = false;
        let said = text_of(&welcome_lines(&welcome, None, 96));
        assert!(said.contains("approvals"), "{said}");
        assert!(
            said.lines()
                .any(|l| l.contains("approvals") && l.contains("ask")),
            "{said}"
        );
        assert_eq!(colour_for("approvals", "ask"), DIM);
        assert_eq!(colour_for("approvals", "auto"), ACCENT, "amber while on");

        welcome.approvals = true;
        let said = text_of(&welcome_lines(&welcome, None, 96));
        assert!(
            said.lines()
                .any(|l| l.contains("approvals") && l.contains("auto")),
            "{said}"
        );
    }

    #[test]
    fn a_short_terminal_gives_up_the_lists_then_the_letters() {
        // The wordmark and the facts are what the pane is for; the lists are an aside. Then, when
        // even the letters do not fit, the name goes back to one line rather than a scrolled pane.
        let roomy = welcome_fitted(&sample_welcome(), None, 96, 30);
        assert!(text_of(&roomy).contains("skills"));
        // 17 rows, not 16: the pane gained a fact (`approvals`) and the rung where the lists go
        // and the letters stay is one row lower for it.
        let tight = welcome_fitted(&sample_welcome(), None, 96, 17);
        let shown = text_of(&tight);
        assert!(shown.contains('█'), "the letters stay:\n{shown}");
        assert!(shown.contains("workspace"), "the facts stay:\n{shown}");
        assert!(!shown.contains("skills"), "the lists go first:\n{shown}");
        assert!(shown.contains("!command"), "the keys stay");
        let cramped = text_of(&welcome_fitted(&sample_welcome(), None, 96, 10));
        assert!(
            cramped.contains("ECLIPSE"),
            "one line when nothing else fits:\n{cramped}"
        );
    }

    #[test]
    fn the_pane_fits_the_eighty_columns_a_default_terminal_gives() {
        // The narrowest terminal that still gets the designed pane, and the widest — the same
        // arrangement at both, because there is nothing left that needs room to be drawn in.
        for width in [80usize, 120] {
            let shown = text_of(&welcome_lines(&sample_welcome(), None, width));
            assert!(
                shown.contains('█') || shown.contains("ECLIPSE"),
                "the name is drawn one way or the other: {shown}"
            );
            assert!(shown.contains("workspace"), "{shown}");
            let widest = welcome_lines(&sample_welcome(), None, width)
                .iter()
                .map(|l| {
                    l.spans
                        .iter()
                        .map(|s| s.content.chars().count())
                        .sum::<usize>()
                })
                .max()
                .unwrap();
            assert!(widest <= width, "nothing overflows at {width}: {widest}");
        }
    }

    #[test]
    fn the_pane_counts_the_tools_that_are_offered() {
        assert_eq!(sample_welcome().tool_count(), 3);
        let shown = text_of(&welcome_lines(&sample_welcome(), None, 100));
        assert!(shown.contains("3 offered"), "{shown}");
    }

    #[test]
    fn the_pane_lists_skills_by_source_without_counting_them_as_tools() {
        let shown = text_of(&welcome_lines(&sample_welcome(), None, 100));
        assert!(shown.contains("skills  3 available"), "{shown}");
        assert!(shown.contains("shared: backup"), "{shown}");
        assert!(
            shown.contains("workspace: deploy, release-notes"),
            "{shown}"
        );
        assert!(
            shown.contains("3 offered"),
            "tools are counted apart: {shown}"
        );
        assert_eq!(sample_welcome().skill_count(), 3);
    }

    #[test]
    fn the_pane_has_no_skills_section_when_there_are_no_skills() {
        let bare = Welcome {
            skills: Vec::new(),
            ..sample_welcome()
        };
        let shown = text_of(&welcome_lines(&bare, None, 100));
        assert!(!shown.contains("skills"), "{shown}");
    }

    #[test]
    fn the_session_column_follows_the_app_not_the_snapshot() {
        // The pane is built before a session exists; it must not keep saying "new" afterwards.
        let before = text_of(&welcome_lines(&sample_welcome(), None, 100));
        assert!(before.contains("new"), "{before}");
        let after = text_of(&welcome_lines(
            &sample_welcome(),
            Some("1795875858162-956151-0"),
            100,
        ));
        assert!(!after.contains(" session   new"), "{after}");
        assert!(
            after.contains("956151-0"),
            "the tail of the id shows: {after}"
        );
    }

    fn menu_of(n: usize, cursor: usize) -> Menu {
        let all = eclipse_core::commands::COMMANDS;
        Menu {
            items: all.iter().take(n).collect(),
            cursor,
        }
    }

    #[test]
    fn the_menu_shows_the_command_its_arguments_and_its_help_with_the_cursor_marked() {
        let lines = menu_lines(&menu_of(8, 2), 8, 100);
        let text = text_of(&lines);
        assert_eq!(lines.len(), 8);
        assert!(
            text.contains("/resume") && text.contains("open a stored session"),
            "{text}"
        );
        // `/model` takes an argument but the menu does not spell it: the way in is the picker, and
        // `[number|name]` was the first thing a reader learned instead of the thing to press.
        assert!(
            text.contains("/model") && !text.contains("[number|name]"),
            "{text}"
        );
        assert!(
            text.contains("pick a model (↑↓, enter)"),
            "the row says what happens, in the shape /resume already had: {text}"
        );
        let marked: Vec<&Line> = lines
            .iter()
            .filter(|l| l.spans.iter().any(|s| s.content.starts_with("› ")))
            .collect();
        assert_eq!(marked.len(), 1);
        assert!(
            marked[0].spans[0].content.contains("/retry"),
            "row 2 is /retry now: {:?}",
            marked[0].spans[0].content
        );
    }

    #[test]
    fn a_long_list_shows_eight_rows_and_counts_the_rest() {
        let mut long = menu_of(8, 0);
        let extra = eclipse_core::commands::COMMANDS.iter().cycle().take(11);
        long.items.extend(extra);
        let lines = menu_lines(&long, 99, 100);
        assert_eq!(lines.len(), 9, "eight rows and the count");
        assert!(text_of(&lines).contains("… 11 more"), "{}", text_of(&lines));
        // The window follows the cursor instead of hiding it.
        long.cursor = 15;
        let text = text_of(&menu_lines(&long, 99, 100));
        assert_eq!(text.matches("› ").count(), 1, "{text}");
    }

    /// A line that is still growing must not be printed: the terminal cannot take it back. So the
    /// last block is held out of the count until it stops changing, and everything before it is
    /// final the moment it is drawn.
    fn rendered(app: &App) -> Vec<String> {
        transcript_lines(app, 60, usize::MAX)
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    /// A turn is framed: a rule above the question and below it, and the answer carries its own
    /// name between rules. One rule, not two — a doubled seam is what makes a transcript look
    /// assembled rather than written.
    #[test]
    fn a_turn_is_framed_by_rules_and_the_answer_has_a_name() {
        let mut app = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        app.blocks.clear();
        app.blocks.push(Block::User("why is the sky blue".into()));
        app.blocks.push(Block::Reply {
            text: "Rayleigh scattering.".into(),
            done: true,
        });
        let lines = rendered(&app);
        let rules: Vec<usize> = lines
            .iter()
            .enumerate()
            .filter(|(_, l)| l.starts_with('─') && l.chars().all(|c| c == '─'))
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            rules.len(),
            3,
            "above the question, below it, and after the answer: {lines:#?}"
        );
        assert!(
            lines[rules[0] + 1].starts_with("❯ "),
            "the question is inside its frame"
        );
        assert_eq!(
            lines[rules[1] + 2],
            "◐ eclipse",
            "the answer is named: {lines:#?}"
        );
        for pair in rules.windows(2) {
            assert!(
                pair[1] - pair[0] > 1,
                "never two rules in a row: {lines:#?}"
            );
        }
        // And the closing rule of a turn is followed by nothing but a blank line.
        assert_eq!(lines[rules[2] + 1], "");
    }

    /// A tool call is one line: what it printed is in the log, not in the conversation.
    #[test]
    fn a_tool_call_is_one_line_and_says_how_it_went() {
        let mut app = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        app.blocks.clear();
        for (state, output, want) in [
            (ToolState::Ok, "2026-11-30", "✓"),
            (ToolState::Failed, "exit code: 1", "✗"),
            (ToolState::Failed, "declined: not mine to write", "⊘"),
        ] {
            app.blocks.clear();
            app.blocks.push(Block::Tool {
                call_id: "c1".into(),
                name: "shell".into(),
                args: r#"{"command":"date"}"#.into(),
                state,
                output: output.into(),
            });
            let lines = rendered(&app);
            assert_eq!(
                lines.len(),
                1,
                "one line per call, whatever it printed: {lines:#?}"
            );
            assert!(
                lines[0].contains(want),
                "{state:?} wants {want}: {}",
                lines[0]
            );
            assert!(
                lines[0].contains(r#"shell({"command":"date"})"#),
                "the call is named, not its output: {}",
                lines[0]
            );
            assert!(
                !lines[0].contains("exit code") && !lines[0].contains("stdout"),
                "the output stays in the log: {}",
                lines[0]
            );
        }
    }

    /// A turn that only called tools has no answer of its own: it must not leave an empty card with
    /// a name on it, which is what the tool-calling message would otherwise render as.
    #[test]
    fn a_turn_with_no_text_draws_no_card() {
        let mut app = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        app.blocks.clear();
        app.blocks.push(Block::User("date".into()));
        app.blocks.push(Block::Tool {
            call_id: "c1".into(),
            name: "shell".into(),
            args: "{}".into(),
            state: ToolState::Ok,
            output: String::new(),
        });
        app.blocks.push(Block::Reply {
            text: String::new(),
            done: true,
        });
        let lines = rendered(&app);
        assert!(
            !lines.iter().any(|l| l == "◐ eclipse"),
            "no name without an answer: {lines:#?}"
        );
    }

    #[test]
    fn a_block_is_only_finished_once_it_stops_changing() {
        let mut app = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        app.blocks.clear();
        app.blocks.push(Block::User("hi".into()));
        app.blocks.push(Block::Reply {
            text: "one\ntwo".into(),
            done: false,
        });

        let everything = lines_for_test(&app, 40, 12).len();
        let stable = stable_line_count(&app, 40, 12);
        assert!(
            stable < everything,
            "an unfinished reply is held back: {stable} of {everything}"
        );
        // The finished user line is part of the stable prefix: it is printed while the reply runs.
        assert!(
            stable >= 2,
            "the prompt above it is already final: {stable}"
        );

        if let Some(Block::Reply { done, .. }) = app.blocks.last_mut() {
            *done = true;
        }
        assert_eq!(
            stable_line_count(&app, 40, 12),
            lines_for_test(&app, 40, 12).len(),
            "once it stops changing, all of it may be printed"
        );
    }

    #[test]
    fn no_menu_line_is_wider_than_the_width_it_was_given() {
        for width in [4, 12, 30, 80] {
            for line in menu_lines(&menu_of(8, 1), 8, width) {
                let w: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();
                assert!(w <= width, "{w} > {width}");
            }
        }
    }

    /// `#227`: `/reasoning hide|full|clamp <n>` is the screen's dial, and it is tested where the
    /// screen draws — a preview of five lines, the whole block, nothing at all, and a character cap
    /// with one ellipsis.
    #[test]
    fn the_reasoning_dial_changes_what_the_transcript_draws() {
        use crate::reasoning_cli::{Live, Mode};
        let long: String = (0..12)
            .map(|i| format!("thought line {i}\n"))
            .collect::<String>();
        let mut app = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        app.blocks.push(app::Block::Reasoning {
            text: long,
            done: true,
        });
        let dial: eclipse_core::reasoning::Shared =
            std::sync::Arc::new(eclipse_core::reasoning::Dial::new(None));

        // Folded by default: a preview and a count.
        let folded = text_of(&transcript_lines(&app, 80, 24));
        assert!(folded.contains("thought line 0"), "{folded}");
        assert!(folded.contains("line(s)"), "the count takes over: {folded}");

        // Whole: every line, no count to open.
        app.reasoning = Some(Live::bare(std::sync::Arc::clone(&dial)));
        if let Some(live) = app.reasoning.as_mut() {
            live.display = Mode::Full;
        }
        let full = text_of(&transcript_lines(&app, 80, 24));
        assert!(
            full.contains("thought line 11"),
            "the tail is drawn: {full}"
        );

        // Hidden: nothing at all, and the block contributes no lines.
        if let Some(live) = app.reasoning.as_mut() {
            live.display = Mode::Hidden;
        }
        let hidden = text_of(&transcript_lines(&app, 80, 24));
        assert!(!hidden.contains("thought line"), "{hidden}");

        // Clamped: a character budget, and one ellipsis where it was cut.
        if let Some(live) = app.reasoning.as_mut() {
            live.display = Mode::Clamp(40);
        }
        let clamped = text_of(&transcript_lines(&app, 80, 24));
        assert!(clamped.contains("thought line 0"), "{clamped}");
        assert!(clamped.contains("…"), "the cut is marked once: {clamped}");
        assert_eq!(
            clamped.matches('…').count(),
            1,
            "one ellipsis, not one per line: {clamped}"
        );
    }

    /// `#253`: a command word with nothing matching keeps the box, and the box says why. An empty
    /// menu would have drawn a bare border with no explanation, which is why the row exists.
    #[test]
    fn a_menu_with_nothing_matching_says_so_in_one_row() {
        let menu = Menu {
            items: Vec::new(),
            cursor: 0,
        };
        let lines = menu_lines(&menu, 8, 60);
        assert_eq!(lines.len(), 1, "one row, not none");
        let text = text_of(&lines);
        assert!(text.contains("no command matches"), "{text}");
        assert!(text.contains("esc"), "and the way out: {text}");
        assert!(!text.contains("›"), "nothing is highlighted: {text}");
        // A narrow frame truncates it rather than spilling.
        let narrow = text_of(&menu_lines(&menu, 8, 12));
        assert!(narrow.chars().count() <= 12, "{narrow:?}");
    }

    #[test]
    fn the_menu_draws_inside_any_frame_without_overflowing_it() {
        use ratatui::backend::TestBackend;
        let mut app = App::new(
            status::Status::new("m", "h:1", 1000, "/w".into()),
            "m",
            "/w",
            None,
        );
        app.input = "/".into();
        app.cursor = 1;
        app.refilter_menu();
        assert!(app.menu.is_some());
        for (w, h) in [(80, 24), (30, 12), (20, 6), (8, 5), (80, 4), (3, 3)] {
            let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).expect("test terminal");
            term.draw(|f| draw(f, &app, 0, usize::MAX))
                .expect("the draw must not panic");
        }
        let mut term = ratatui::Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
        let screen: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // The rows are capped and overrun is counted, so the last commands are not on this
        // frame: what this asserts is a frame that draws the title, a row near the top, and the
        // count of what did not fit.
        assert!(
            screen.contains("commands") && screen.contains("/bg") && screen.contains("more"),
            "{screen}"
        );
    }

    /// The provider step: the routes, each with the endpoint it points at, drawn as a real frame
    /// so that "it looks like a list of places" is checked and not assumed.
    #[test]
    fn the_provider_picker_draws_each_route_with_the_endpoint_it_points_at() {
        use ratatui::backend::TestBackend;
        let mut app = App::new(
            status::Status::new("inkling-2-mini", "h:1", 1000, "/w".into()),
            "inkling-2-mini",
            "/w",
            None,
        );
        let routes = vec![
            eclipse_core::router::RouteInfo {
                name: "local".into(),
                model: "inkling-2-mini".into(),
                endpoint: "http://127.0.0.1:18045/v1".into(),
            },
            eclipse_core::router::RouteInfo {
                name: "cloud".into(),
                model: "big".into(),
                endpoint: "https://ollama.example/v1".into(),
            },
        ];
        app.open_providers(&routes, Some("local"));
        let mut term = ratatui::Terminal::new(TestBackend::new(80, 22)).expect("test terminal");
        term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
        let screen: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(screen.contains("Ask"), "{screen}");
        assert!(screen.contains("provider"), "{screen}");
        assert!(screen.contains("2 configured"), "{screen}");
        assert!(screen.contains("local"), "{screen}");
        assert!(screen.contains("cloud"), "{screen}");
        // The endpoint is the row's detail line: two routes can be the same box, and the name
        // alone does not tell you which one you are moving to.
        assert!(screen.contains("127.0.0.1:18045"), "{screen}");
        assert!(screen.contains("ollama.example"), "{screen}");
        assert!(screen.contains("current"), "{screen}");
        // It is not a model list or a session list.
        assert!(!screen.contains("served"), "{screen}");
        assert!(!screen.contains("stored"), "{screen}");
    }

    /// The `/model` menu: the endpoint's list, arrow keys, the model in use marked, and the
    /// cursor already on it so Enter does not switch anything by accident.
    #[test]
    fn the_model_picker_lists_what_the_endpoint_serves_and_marks_the_one_in_use() {
        use ratatui::backend::TestBackend;
        let mut app = App::new(
            status::Status::new("inkling-2-mini", "h:1", 1000, "/w".into()),
            "inkling-2-mini",
            "/w",
            None,
        );
        app.set_models_from(
            None,
            vec![
                "gemma-4-12b".into(),
                "inkling-2-mini".into(),
                "qwen-3.8-27b".into(),
            ],
        );
        let picker = app.picker.as_ref().expect("the list is up");
        assert_eq!(picker.kind, crate::tui::app::PickerKind::Model);
        assert_eq!(picker.items.len(), 3);
        assert_eq!(
            picker.cursor, 1,
            "the cursor starts on the model in use, not on the first row"
        );
        assert_eq!(picker.items[1].note, "current");
        assert_eq!(picker.items[0].note, "");

        let mut term = ratatui::Terminal::new(TestBackend::new(72, 20)).expect("test terminal");
        term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
        let screen: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(screen.contains("Switch"), "{screen}");
        assert!(screen.contains("model"), "{screen}");
        assert!(screen.contains("3 served"), "{screen}");
        assert!(screen.contains("gemma-4-12b"), "{screen}");
        assert!(screen.contains("qwen-3.8-27b"), "{screen}");
        assert!(screen.contains("current"), "{screen}");
        // No session furniture in a model list.
        assert!(!screen.contains("stored"), "{screen}");
        assert!(!screen.contains("messages"), "{screen}");
        assert!(screen.contains("↑↓ choose"), "{screen}");

        // The `current` mark sits on the row of the model it marks, not a line below it.
        let buffer = term.backend().buffer();
        let area = buffer.area;
        let mut lines: Vec<String> = Vec::new();
        for y in area.y..area.y + area.height {
            let mut line = String::new();
            for x in area.x..area.x + area.width {
                line.push_str(buffer[(x, y)].symbol());
            }
            lines.push(line.trim_end().to_string());
        }
        let model_line = lines
            .iter()
            .find(|l| l.contains("inkling-2-mini"))
            .expect("the model row is on screen");
        assert!(
            model_line.contains("current"),
            "the current mark is on the model's own row: {model_line:?}"
        );
    }

    /// The screen, row by row, as a reader would see it.
    fn rows_of(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
        let buffer = term.backend().buffer();
        let area = buffer.area;
        (area.y..area.y + area.height)
            .map(|y| {
                (area.x..area.x + area.width)
                    .map(|x| buffer[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect()
    }

    /// The badge is a standing row, not a note in the scrollback: it takes the top row of the
    /// live region, right-aligned, and the composer and the readout keep the rows they had.
    /// The row is only there while the install is behind — a current install pays nothing.
    #[test]
    fn the_update_badge_takes_one_row_and_never_displaces_the_readout() {
        use ratatui::backend::TestBackend;

        let mut app = App::new(
            status::Status::new("inkling-2-mini", "h:1", 327_680, "/w".into()),
            "inkling-2-mini",
            "/w",
            None,
        );
        app.update = Some(eclipse_core::update::Behind {
            installed: "0.7.0".into(),
            latest: "v0.8.0".into(),
        });
        let mut term = ratatui::Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");

        let rows = rows_of(&term);
        assert!(
            rows[0].contains("↑ 0.8.0 available"),
            "the badge is on the first row, without the tag's v: {:?}",
            rows[0]
        );
        assert!(
            rows[0].trim_end().ends_with("eclipse upgrade"),
            "and it is right-aligned to the edge: {:?}",
            rows[0]
        );
        assert!(
            rows[0].chars().count() <= 80,
            "one row at eighty columns: {:?}",
            rows[0]
        );
        assert!(
            rows[23].contains("inkling-2-mini"),
            "the readout still names the model on the last row: {:?}",
            rows[23]
        );

        // A current install pays nothing: the row is gone, and nothing else moved with it.
        app.update = None;
        term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
        let rows = rows_of(&term);
        assert!(
            !rows.iter().any(|r| r.contains("available")),
            "no badge, no row: {rows:?}"
        );
        assert!(
            rows[23].contains("inkling-2-mini"),
            "the readout is where it was: {:?}",
            rows[23]
        );
    }
}