procyon 0.1.2

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Padding, Paragraph},
    Frame,
};

use crate::app::{AppState, AppStatus, AutocompleteItem, ChatMessage};
use crate::config::Theme;

// Stellar Development Foundation, Brand Guidelines 2026, p.02 / p.04.
//
// Primary: yellow, black, white. Secondary: warm grey, lavender, teal, deep navy. The guidelines'
// typography (Lora / Inter) has no equivalent here — a terminal renders in whatever font the user
// chose, so the brand has to carry entirely on colour and mark.
const STELLAR_YELLOW: Color = Color::Rgb(253, 218, 36); // #FDDA24
const STELLAR_BLACK: Color = Color::Rgb(15, 15, 15); // #0F0F0F
const STELLAR_WHITE: Color = Color::Rgb(246, 247, 248); // #F6F7F8
const STELLAR_LAVENDER: Color = Color::Rgb(183, 172, 232); // #B7ACE8
const STELLAR_TEAL: Color = Color::Rgb(0, 167, 181); // #00A7B5
const STELLAR_NAVY: Color = Color::Rgb(0, 46, 93); // #002E5D
/// The warm grey, darkened until it works as chrome against #0F0F0F rather than as body text.
const STELLAR_GREY_DARK_BG: Color = Color::Rgb(138, 134, 124);
/// ...and the same hue darkened the other way, for chrome on a light background.
const STELLAR_GREY_LIGHT_BG: Color = Color::Rgb(107, 103, 94);

/// Six roles, no more. Every colour in the TUI comes from here — a literal `Color::*` at a call
/// site is a bug, because it is a colour nobody can re-theme and nobody can name.
pub struct ColorPalette {
    /// Body text.
    pub fg: Color,
    /// Chrome: labels, sub-steps, hints, the status line.
    pub dim: Color,
    /// The Stellar accent — prompt glyph, monogram, selection, the running step.
    pub accent: Color,
    /// Network name in the status line, for any network that is not mainnet.
    pub network: Color,
    pub ok: Color,
    pub err: Color,
}

impl ColorPalette {
    pub fn from_theme(theme: &Theme) -> Self {
        match theme {
            Theme::Dark => Self {
                fg: STELLAR_WHITE,
                dim: STELLAR_GREY_DARK_BG,
                accent: STELLAR_YELLOW,
                network: STELLAR_LAVENDER,
                ok: STELLAR_TEAL,
                err: Color::Red,
            },
            // The brand yellow is a fill colour, not a text colour: on white it is illegible, and
            // the guidelines themselves only ever put it behind black strokes. Deep navy is the
            // secondary that survives the swap, so the light theme leads with it.
            Theme::Light => Self {
                fg: STELLAR_BLACK,
                dim: STELLAR_GREY_LIGHT_BG,
                accent: STELLAR_NAVY,
                network: STELLAR_TEAL,
                ok: STELLAR_TEAL,
                err: Color::Red,
            },
        }
    }
}

/// Marker for a user turn, and for the input prompt — the two places the human speaks.
const USER_GLYPH: &str = "";
/// Marker for an execution step or a system notice.
const STEP_GLYPH: &str = "";
/// Marker for a sub-step hanging off the step above it.
const SUBSTEP_GLYPH: &str = "";

const SPINNER_FRAMES: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];

/// One text row plus the two border rows around it.
const INPUT_FRAME_HEIGHT: u16 = 3;
/// The same frame carrying the question and the keys that answer it.
const APPROVAL_FRAME_HEIGHT: u16 = 4;

/// The house frame. Rounded corners throughout — the Stellar mark and wordmark are built on
/// curves, and a square box next to them reads as a different system. One column of padding on
/// each side, so text has an edge to sit against rather than one to collide with.
fn frame_block(color: Color) -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(color))
        .padding(Padding::horizontal(1))
}

pub fn render(frame: &mut Frame, state: &mut AppState, theme: &Theme) {
    let palette = ColorPalette::from_theme(theme);

    // The input is one line inside its frame; the suggestion popup hangs below it and has to be
    // inside the chunk, so the chunk grows by exactly the rows the popup will use.
    let input_height = if state.pending_approval.is_some() {
        // The question takes the input's place entirely — there is nothing to type until it is
        // answered, and a prompt that still looked typeable would invite exactly that.
        APPROVAL_FRAME_HEIGHT
    } else if state.autocomplete_active && !state.autocomplete_matches.is_empty() {
        INPUT_FRAME_HEIGHT + autocomplete_popup_height(state.autocomplete_matches.len())
    } else {
        INPUT_FRAME_HEIGHT
    };

    // transcript / input / status line. No top bar, no sidebar: the transcript gets the screen.
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),
            Constraint::Length(input_height),
            Constraint::Length(1),
        ])
        .split(frame.area());

    // Two frames, and only two: the conversation and the place you type into it. Rounded, in the
    // quietest colour that still reads as a line — they are there to give the content an edge to
    // sit against, not to be looked at.
    let body = frame_block(palette.dim);
    let body_inner = body.inner(main_chunks[0]);
    frame.render_widget(body, main_chunks[0]);

    if has_conversation(state) {
        render_chat(frame, state, body_inner, &palette);
    } else {
        render_welcome(frame, state, body_inner, &palette);
    }
    render_input(frame, state, main_chunks[1], &palette);
    render_statusline(frame, state, main_chunks[2], &palette);

    if state.palette_open {
        render_palette(frame, state, &palette);
    }
}

/// True once anything has been said. Until then the welcome banner owns the transcript area; the
/// first message of any kind sends it away for good.
///
/// "Any kind" is load-bearing: slash commands answer with `System` messages and nothing else, so
/// restricting this to User/Agent left the banner covering the reply to every `/help`, `/status`
/// and `/doctor` — the commands ran and their output was drawn underneath.
fn has_conversation(state: &AppState) -> bool {
    // Steps count too. A status used to push a message as well, so `messages` alone happened to
    // cover it; now that a status is only a step, an execution trace could be drawn underneath a
    // welcome banner that still believed nothing had happened.
    !state.messages.is_empty() || !state.execution_steps.is_empty()
}

/// The Stellar monogram reduced to what a terminal cell grid can hold honestly: its three slanted
/// strokes, stacked into the mark's silhouette. Drawn in the brand yellow, and the only piece of
/// ornament in the whole interface — everywhere else the glyphs stay neutral, so this reads as a
/// signature rather than as decoration.
const STELLAR_MARK: [&str; 3] = [" ╱╱ ", "╱╱╱ ", " ╱╱ "];

fn render_welcome(frame: &mut Frame, state: &AppState, area: Rect, palette: &ColorPalette) {
    let dim = Style::default().fg(palette.dim);
    let mark = Style::default().fg(palette.accent);

    // The mark sits to the left of the wordmark, so the two read as one lockup.
    let lines = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled(format!("  {}  ", STELLAR_MARK[0]), mark),
            Span::styled(
                "procyon",
                Style::default().fg(palette.fg).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![
            Span::styled(format!("  {}  ", STELLAR_MARK[1]), mark),
            Span::styled("Stellar development harness", dim),
        ]),
        Line::from(Span::styled(format!("  {}", STELLAR_MARK[2]), mark)),
        Line::from(""),
        Line::from(vec![
            Span::styled("        ", dim),
            Span::styled(state.cwd_label.clone(), dim),
        ]),
        Line::from(vec![
            Span::styled("        ", dim),
            Span::styled(
                state.active_network.clone(),
                Style::default().fg(palette.network),
            ),
            // The project only earns a slot once there is one — "No project" on the welcome
            // screen is a placeholder announcing its own emptiness.
            Span::styled(
                match state.project_name.as_str() {
                    "No project" => String::new(),
                    name => format!(" · {}", name),
                },
                dim,
            ),
            Span::styled(
                {
                    // The model name is the long part — `qwen3:4b-instruct-2507-q4_K_M` is 29
                    // columns — and it was the renderer that cut it, mid-name and with nothing to
                    // say so. An ellipsis says "there is more"; a hard cut looks like a fault.
                    let spent = 8
                        + state.active_network.chars().count()
                        + match state.project_name.as_str() {
                            "No project" => 0,
                            name => name.chars().count() + 3,
                        }
                        + state.active_provider.chars().count()
                        + 4;
                    let room = (area.width as usize).saturating_sub(spent);
                    format!(
                        " · {} {}",
                        state.active_provider,
                        truncate_to(&state.active_model, room)
                    )
                },
                dim,
            ),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            // Sheds a phrase at a time before the renderer clips it. At 60 columns the full line
            // was cut mid-phrase — "· ?" with the rest gone — which reads as a rendering fault
            // rather than as a hint that did not fit. `area` is already the inside of the frame,
            // so these are the columns actually available.
            match area.width {
                w if w >= 78 => {
                    "        Type / for commands · ctrl+k for the palette · ? for shortcuts"
                }
                w if w >= 50 => "        / commands · ctrl+k palette · ? shortcuts",
                _ => "        / · ctrl+k · ?",
            },
            dim,
        )),
    ];

    frame.render_widget(Paragraph::new(lines), area);
}

/// One piece of the status line, and how readily it is given up when the row runs out.
///
/// The line has to carry seven things (network, account, project, contract, provider/model, risk
/// mode, operation) in one row that can be 30 columns wide. Truncating the whole line with an
/// ellipsis, which is what it used to do, cuts from the right — so on a narrow terminal the
/// operation in flight disappeared while the project name survived, purely because of where each
/// happened to sit. Dropping whole segments by priority instead means what is left is always the
/// part that matters most.
struct Segment {
    /// 0 is never dropped. Higher numbers go first.
    priority: u8,
    text: String,
    style: Style,
}

/// How many columns a name may spend before it is abbreviated. Enough for `anthropic
/// claude-sonnet-5` whole, and enough of a long local model tag to recognise which one it is.
const MODEL_BUDGET: usize = 26;
const NAME_BUDGET: usize = 20;

/// The risk posture, said out loud on every frame.
///
/// Mirrored from the gate rather than recomputed here, so the screen and `risk::assess` cannot
/// disagree about real funds. `armed` is process-wide: it means signing on mainnet is permitted,
/// whatever network happens to be selected right now.
fn risk_mode(state: &AppState) -> &'static str {
    if state.mainnet_allowed {
        "armed"
    } else {
        "guarded"
    }
}

fn render_statusline(frame: &mut Frame, state: &AppState, area: Rect, palette: &ColorPalette) {
    let dim = Style::default().fg(palette.dim);
    let mut segments: Vec<Segment> = Vec::new();

    // Network first, and never dropped. Mainnet switches to the brand yellow and goes bold — real
    // funds are the one piece of context worth interrupting for, and yellow is the colour the brand
    // already uses to draw the eye. Everything else stays in the calmer lavender.
    //
    // Mainnet with signing off is the one state where the network name alone misleads: it reads as
    // "you are working on mainnet" when every operation that signs will be refused.
    let mainnet = state.active_network == "mainnet";
    segments.push(Segment {
        priority: 0,
        text: if mainnet && !state.mainnet_allowed {
            format!("{} (read-only)", state.active_network)
        } else {
            state.active_network.clone()
        },
        style: if mainnet {
            Style::default()
                .fg(palette.accent)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(palette.network)
        },
    });

    // The risk posture outranks everything except the network: it is the answer to "can this
    // session move real money", and a line that sheds it to keep a project name is lying by
    // omission.
    let armed = state.mainnet_allowed;
    segments.push(Segment {
        priority: 1,
        text: risk_mode(state).to_string(),
        style: if armed {
            Style::default()
                .fg(palette.err)
                .add_modifier(Modifier::BOLD)
        } else {
            dim
        },
    });

    // Who would sign, and what would be signed against. Both were deliberately left out when the
    // status line replaced the sidebar, on the grounds that `/status` carries them — but a signing
    // identity nobody can see while they approve a transaction is the one place that reasoning
    // does not hold.
    segments.push(Segment {
        priority: 3,
        text: absent_as(&state.active_account, "no account"),
        style: dim,
    });
    segments.push(Segment {
        priority: 4,
        text: truncate_to(&absent_as(&state.project_name, "no project"), NAME_BUDGET),
        style: dim,
    });
    if let Some(contract) = &state.active_contract {
        segments.push(Segment {
            priority: 2,
            text: abbreviate(contract),
            style: dim,
        });
    }

    // Capped, because this is the one field with no natural length: a local model tag such as
    // `qwen3:4b-instruct-2507-q4_K_M` is 36 columns with the provider, which on a 100-column
    // terminal was enough to push the project name off the row entirely. An identifier gets
    // abbreviated here for the same reason a contract id does, rather than costing another field.
    segments.push(Segment {
        priority: 3,
        text: truncate_to(
            &format!("{} {}", state.active_provider, state.active_model),
            MODEL_BUDGET,
        ),
        style: dim,
    });

    // The fill gauge. Priority 5 — the first thing shed, because on a wide terminal it is worth a
    // glance and on a narrow one it is the least of what the line carries. It turns red past the
    // compaction threshold rather than at the window, since that is where the session actually
    // starts losing its early turns.
    if let Some((used, window)) = state.context_usage {
        let pressured = window > 0 && used * 5 >= window * 4;
        segments.push(Segment {
            priority: 5,
            text: format!("ctx {}", crate::app::context_meter(used, window)),
            style: if pressured {
                Style::default().fg(palette.err)
            } else {
                dim
            },
        });
    }

    match state.status {
        AppStatus::Working => {
            let spinner = SPINNER_FRAMES[state.spinner_frame % SPINNER_FRAMES.len()];
            let activity = state
                .current_activity
                .as_deref()
                .map(crate::app::activity_label)
                .unwrap_or("Working...");
            segments.push(Segment {
                priority: 0,
                text: format!("{} {}", spinner, activity),
                style: Style::default().fg(palette.accent),
            });
        }
        AppStatus::NeedsCredential => segments.push(Segment {
            priority: 0,
            text: "● needs login".to_string(),
            style: Style::default().fg(palette.err),
        }),
        // Ready is the resting state: saying so every frame is noise.
        AppStatus::Ready => {}
    }

    // Hints go right-aligned. While a turn runs, the one key worth knowing is the one that stops
    // it — a shortcut nobody can find is the same as not having it.
    let width = area.width as usize;
    let working = matches!(state.status, AppStatus::Working);
    let hint = match (working, width >= 60) {
        (true, true) => "esc interrupt · ctrl+k ",
        (true, false) => "esc interrupt ",
        (false, true) => "? shortcuts · ctrl+k ",
        (false, false) => "ctrl+k ",
    };

    // At least two columns of gap, or the hint reads as a word glued to the activity
    // ("Building contract? shortcuts").
    const INDENT: usize = 2;
    const GAP: usize = 2;
    let budget = width.saturating_sub(INDENT);
    let mut show_hint = true;

    // Shed the least important segment until what is left fits beside the hint. Only then give up
    // the hint, and only then cut with an ellipsis — by that point the terminal is too narrow for
    // any of this to be readable anyway.
    loop {
        let needed = laid_out_width(&segments)
            + if show_hint {
                hint.chars().count() + GAP
            } else {
                0
            };
        if needed <= budget {
            break;
        }
        match segments
            .iter()
            .enumerate()
            .filter(|(_, s)| s.priority > 0)
            .max_by_key(|(i, s)| (s.priority, *i))
            .map(|(i, _)| i)
        {
            Some(index) => {
                segments.remove(index);
            }
            None if show_hint => show_hint = false,
            None => break,
        }
    }
    let mut spans = vec![Span::raw(" ".repeat(INDENT))];
    for (index, segment) in segments.iter().enumerate() {
        if index > 0 {
            spans.push(Span::styled(" · ", dim));
        }
        spans.push(Span::styled(segment.text.clone(), segment.style));
    }

    // On a terminal too narrow even for one segment, cut with an ellipsis rather than let the
    // renderer clip mid-word: an ellipsis says "there is more", a hard cut looks like a bug.
    let mut used: usize = spans.iter().map(|s| s.content.chars().count()).sum();
    if used > width {
        let mut left = width;
        for span in spans.iter_mut() {
            let len = span.content.chars().count();
            if len <= left {
                left -= len;
            } else {
                span.content = truncate_to(span.content.as_ref(), left).into();
                left = 0;
            }
        }
        used = width;
    }

    if show_hint && used + hint.chars().count() + GAP <= width {
        spans.push(Span::raw(" ".repeat(width - used - hint.chars().count())));
        spans.push(Span::styled(hint, dim));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// How wide the segments render, separators included.
fn laid_out_width(segments: &[Segment]) -> usize {
    let text: usize = segments.iter().map(|s| s.text.chars().count()).sum();
    text + 3 * segments.len().saturating_sub(1)
}

/// Renders a slot the app fills with a placeholder as the absence it actually is.
///
/// `AppState` starts `active_account` at "None" and `project_name` at "No project", which read as
/// values rather than as gaps once they sit in a row of real ones.
fn absent_as(value: &str, absent: &'static str) -> String {
    match value.trim() {
        "" | "None" | "none" | "No project" => absent.to_string(),
        other => other.to_string(),
    }
}

/// Shortens a Stellar contract/account id to head…tail, which is how people actually recognise
/// one, without spending 56 columns of a one-line status bar on it.
fn abbreviate(id: &str) -> String {
    let chars: Vec<char> = id.chars().collect();
    if chars.len() <= 12 {
        return id.to_string();
    }
    let head: String = chars[..4].iter().collect();
    let tail: String = chars[chars.len() - 4..].iter().collect();
    format!("{}{}", head, tail)
}

fn render_palette(frame: &mut Frame, state: &AppState, palette: &ColorPalette) {
    let area = frame.area();
    let width = (area.width.saturating_sub(10)).clamp(40, 70);
    let height = (state.palette_matches.len().min(8) as u16 + 4).min(area.height.saturating_sub(4));
    let x = (area.width.saturating_sub(width)) / 2;
    let y = (area.height.saturating_sub(height)) / 2;
    let popup = Rect::new(x, y, width, height);

    let block = frame_block(palette.dim).title(" commands ");

    let inner = block.inner(popup);
    // Cleared one column wider than the frame, so a line of transcript peeking out beside the
    // border reads as a gutter rather than as leftover debris.
    let gutter = Rect::new(
        popup.x.saturating_sub(1),
        popup.y,
        (popup.width + 2).min(area.width - popup.x.saturating_sub(1)),
        popup.height,
    );
    frame.render_widget(ratatui::widgets::Clear, gutter);
    frame.render_widget(block, popup);

    // Input line at top of palette
    let input_line = Line::from(vec![
        Span::styled(USER_GLYPH, Style::default().fg(palette.accent)),
        Span::styled(
            state.palette_input.as_str(),
            Style::default().fg(palette.fg),
        ),
    ]);
    let input_area = Rect::new(inner.x, inner.y, inner.width, 1);
    frame.render_widget(Paragraph::new(input_line), input_area);

    // Matches below. The window is taken *after* scrolling to the selection — taking the first
    // `list_height` entries first and then filtering them by the offset (as this used to) means
    // that once the highlight moves past the first screenful every row is skipped and the list
    // renders blank.
    let list_y = inner.y + 2;
    let list_height = inner.height.saturating_sub(2) as usize;
    let offset = scroll_offset(
        state.palette_selected,
        state.palette_matches.len(),
        list_height,
    );

    let lines: Vec<Line<'static>> = state
        .palette_matches
        .iter()
        .enumerate()
        .skip(offset)
        .take(list_height)
        .map(|(idx, item)| {
            let style = if idx == state.palette_selected {
                Style::default()
                    .fg(palette.accent)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(palette.fg)
            };
            Line::from(vec![
                Span::styled(format!(" {:<16} ", item.value), style),
                Span::styled(item.description.clone(), Style::default().fg(palette.dim)),
            ])
        })
        .collect();

    let list_area = Rect::new(inner.x, list_y, inner.width, list_height as u16);
    frame.render_widget(Paragraph::new(lines), list_area);

    // Cursor inside palette input
    let cx = inner.x + 2 + state.palette_cursor as u16;
    let cy = inner.y;
    if cx < inner.x + inner.width {
        frame.set_cursor_position((cx, cy));
    }
}

// Width is counted in chars rather than display cells, so double-width glyphs (CJK) wrap a little
// early. Good enough here, and it avoids a unicode-width dependency.
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    if width == 0 {
        return vec![String::new()];
    }

    let mut lines = Vec::new();
    let mut current = String::new();
    let mut current_width = 0usize;

    for word in text.split(' ') {
        let word_width = word.chars().count();

        if word_width > width {
            if current_width > 0 {
                lines.push(std::mem::take(&mut current));
                current_width = 0;
            }
            let chars: Vec<char> = word.chars().collect();
            for chunk in chars.chunks(width) {
                lines.push(chunk.iter().collect());
            }
            // The trailing chunk stays open so following words can share the line.
            if let Some(last) = lines.pop() {
                current_width = last.chars().count();
                current = last;
            }
            continue;
        }

        let needed = if current_width == 0 {
            word_width
        } else {
            current_width + 1 + word_width
        };

        if needed > width {
            lines.push(std::mem::take(&mut current));
            current.push_str(word);
            current_width = word_width;
        } else {
            if current_width > 0 {
                current.push(' ');
            }
            current.push_str(word);
            current_width = needed;
        }
    }

    lines.push(current);
    lines
}

fn message_lines(msg: &ChatMessage, palette: &ColorPalette, width: usize) -> Vec<Line<'static>> {
    // Speaker labels are glyphs, not words: "You:"/"Agent:" spent five columns per line saying
    // something the colour and position already said. The agent — the bulk of the transcript —
    // gets no marker at all, so its prose reads as the body of the page.
    let (lead, lead_style, body_style) = match msg {
        ChatMessage::User(_) => (
            USER_GLYPH,
            Style::default()
                .fg(palette.accent)
                .add_modifier(Modifier::BOLD),
            Style::default().fg(palette.fg),
        ),
        ChatMessage::Agent(_) => ("", Style::default(), Style::default().fg(palette.fg)),
        ChatMessage::System(_) => (
            STEP_GLYPH,
            Style::default().fg(palette.dim),
            Style::default().fg(palette.dim),
        ),
    };

    let content = match msg {
        ChatMessage::User(text) | ChatMessage::Agent(text) | ChatMessage::System(text) => {
            text.as_str()
        }
    };

    // Continuations line up under the first character of the text, so a wrapped paragraph reads
    // as one block. With no lead glyph (the agent) there is nothing to line up under.
    let lead_width = lead.chars().count();
    let indent = " ".repeat(lead_width);
    let mut out = Vec::new();

    for logical in content.split('\n') {
        let budget = width.saturating_sub(lead_width).max(1);
        for (wrapped_index, piece) in wrap_text(logical, budget).into_iter().enumerate() {
            let is_first = out.is_empty() && wrapped_index == 0;
            if is_first && !lead.is_empty() {
                out.push(Line::from(vec![
                    Span::styled(lead, lead_style),
                    Span::styled(piece, body_style),
                ]));
            } else if lead.is_empty() {
                out.push(Line::from(Span::styled(piece, body_style)));
            } else {
                out.push(Line::from(vec![
                    Span::raw(indent.clone()),
                    Span::styled(piece, body_style),
                ]));
            }
        }
    }

    out
}

fn render_chat(frame: &mut Frame, state: &mut AppState, area: Rect, palette: &ColorPalette) {
    let inner_width = area.width.saturating_sub(1) as usize;
    let viewport = area.height as usize;

    // The execution trace flows in the transcript as indented steps rather than sitting inside a
    // hand-drawn box. Same information, none of the border arithmetic that used to slice
    // multibyte glyphs in half.
    //
    // Interleaved at each step's anchor, not appended: the trace used to be drawn after every
    // message, which put the tool calls of a turn below the answer they produced.
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut steps = state.execution_steps.iter().peekable();

    for (index, msg) in state.messages.iter().enumerate() {
        while steps.peek().is_some_and(|step| step.after <= index) {
            let step = steps.next().expect("peeked");
            lines.extend(execution_step_lines(step, palette, inner_width));
        }
        lines.extend(message_lines(msg, palette, inner_width));
    }

    // Whatever is still open belongs after the last message — a turn in flight, or steps that
    // outlived the transcript they were anchored to.
    for step in steps {
        lines.extend(execution_step_lines(step, palette, inner_width));
    }

    let max_scroll = lines.len().saturating_sub(viewport);
    let offset_from_top = state.resolve_scroll(max_scroll);

    frame.render_widget(
        Paragraph::new(lines).scroll((offset_from_top as u16, 0)),
        area,
    );

    // The old border title carried "(N lines below)". Without a border it becomes a floating
    // marker on the last row — only while scrolled back, so it costs nothing at rest.
    let below = max_scroll - offset_from_top;
    if !state.is_following_chat() && below > 0 && area.height > 0 {
        let marker = format!("{} more ", below);
        let w = (marker.chars().count() as u16).min(area.width);
        let row = Rect::new(
            area.x + area.width.saturating_sub(w),
            area.y + area.height - 1,
            w,
            1,
        );
        frame.render_widget(ratatui::widgets::Clear, row);
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                marker,
                Style::default().fg(palette.dim),
            ))),
            row,
        );
    }
}

fn execution_step_lines(
    step: &crate::app::ExecutionStep,
    palette: &ColorPalette,
    width: usize,
) -> Vec<Line<'static>> {
    let mut out = Vec::new();
    {
        // A tool call is detail hanging off whatever phase the agent announced; everything else
        // (Thinking, MCP notices, plain status) is a phase in its own right.
        let is_substep = step.label.to_lowercase().starts_with("using tool:");

        // State is carried by the glyph's colour on both levels. It used to be on phases only, so
        // a tool call that failed was drawn exactly like one that succeeded — the trace could
        // report that a step had started and nothing else.
        let color = match step.state {
            crate::app::ExecutionStepState::Done => palette.ok,
            crate::app::ExecutionStepState::Failed => palette.err,
            crate::app::ExecutionStepState::Running => palette.accent,
            crate::app::ExecutionStepState::Waiting => palette.accent,
        };
        let (glyph, indent) = if is_substep {
            (SUBSTEP_GLYPH, "  ")
        } else {
            (STEP_GLYPH, "")
        };
        let style = Style::default().fg(color);

        let lead_width = indent.chars().count() + glyph.chars().count();
        let budget = width.saturating_sub(lead_width).max(10);
        let pretty = pretty_execution_label(&step.label, &step.state);
        let body = if is_substep {
            Style::default().fg(palette.dim)
        } else {
            Style::default().fg(palette.fg)
        };

        for (i, piece) in wrap_text(&pretty, budget).into_iter().enumerate() {
            if i == 0 {
                out.push(Line::from(vec![
                    Span::raw(indent),
                    Span::styled(glyph, style),
                    Span::styled(piece, body),
                ]));
            } else {
                out.push(Line::from(vec![
                    Span::raw(" ".repeat(lead_width)),
                    Span::styled(piece, body),
                ]));
            }
        }
    }
    out
}

fn pretty_execution_label(raw: &str, state: &crate::app::ExecutionStepState) -> String {
    use crate::app::ExecutionStepState as S;

    let lower = raw.to_lowercase();
    if lower.contains("thinking") {
        // The ellipsis is the whole complaint in miniature: colour alone says a phase is over,
        // but "Thinking..." on a finished step still reads as something still happening.
        return match state {
            S::Done => "Thought".to_string(),
            _ => "Thinking...".to_string(),
        };
    }
    if lower.starts_with("using tool:") {
        let tool = raw.split(':').nth(1).unwrap_or("").trim();
        // The description is what the tool is *doing*, so it can only stand while it is doing it.
        // Leaving "writing file" on a finished call is how the trace came to read as a set of
        // steps that never ended.
        let suffix = match state {
            S::Running => friendly_tool_desc(tool),
            S::Waiting => "waiting for you",
            S::Done => "done",
            S::Failed => "failed",
        };
        return format!("{}{}", tool, suffix);
    }
    if lower.starts_with("mcp ") {
        return raw.to_string();
    }
    raw.to_string()
}

fn friendly_tool_desc(tool: &str) -> &'static str {
    match tool {
        "caatinga_build" => "building contract",
        "caatinga_deploy" => "deploying to network",
        "caatinga_doctor" => "checking environment",
        "caatinga_invoke" => "invoking contract",
        "caatinga_read" => "reading contract",
        "stellar_invoke" => "invoking via CLI",
        "read_file" => "reading file",
        "write_file" => "writing file",
        "edit_file" => "editing file",
        "grep" => "searching code",
        "glob" => "locating files",
        "list_dir" => "listing directory",
        "account_create" => "creating account",
        "account_balance" => "checking balance",
        _ if tool.starts_with("raven__") => "searching Stellar Docs",
        _ => "executing",
    }
}

/// Cuts `text` to at most `max_chars`, replacing the tail with an ellipsis.
fn truncate_to(text: &str, max_chars: usize) -> String {
    if max_chars == 0 {
        return String::new();
    }
    if text.chars().count() <= max_chars {
        return text.to_string();
    }
    let mut out: String = text.chars().take(max_chars.saturating_sub(1)).collect();
    out.push('');
    out
}

/// How many suggestion rows the popup shows at once before it starts scrolling.
const AUTOCOMPLETE_MAX_VISIBLE: usize = 5;

/// Width of the command-name column, so the descriptions line up under each other.
const AUTOCOMPLETE_NAME_COLUMN: usize = 20;

/// Width the popup needs so the longest description fits without being cut, clamped to the space
/// the input area actually has.
fn autocomplete_popup_width(items: &[AutocompleteItem], available: u16) -> u16 {
    let widest_name = items
        .iter()
        .map(|c| c.value.chars().count())
        .max()
        .unwrap_or(0)
        .max(AUTOCOMPLETE_NAME_COLUMN);
    let widest_desc = items
        .iter()
        .map(|c| c.description.chars().count())
        .max()
        .unwrap_or(0);

    // " name<pad> " + description + a trailing space, plus the two border columns and the
    // frame's one column of padding on each side.
    let content = 1 + widest_name + 1 + widest_desc + 1;
    (content as u16 + 4).min(available)
}

/// Rows the popup occupies for `match_count` suggestions, borders included.
fn autocomplete_popup_height(match_count: usize) -> u16 {
    match_count.min(AUTOCOMPLETE_MAX_VISIBLE) as u16 + 2
}

/// First index to draw so the highlighted row stays inside a window of `visible` rows. Shared by
/// the suggestion popup and the command palette — they are the same list-with-a-cursor problem,
/// and the palette's own hand-rolled copy of this got it wrong.
fn scroll_offset(selected: usize, count: usize, visible: usize) -> usize {
    if visible == 0 || count <= visible {
        return 0;
    }
    let max_offset = count - visible;
    selected.saturating_sub(visible - 1).min(max_offset)
}

/// First suggestion index to draw, so the highlighted row stays inside the visible window.
fn autocomplete_scroll_offset(selected: usize, match_count: usize) -> usize {
    scroll_offset(selected, match_count, AUTOCOMPLETE_MAX_VISIBLE)
}

/// The permission question, in the input frame's place.
///
/// It reuses that frame rather than floating over the transcript on purpose: the input frame is
/// already "the place the app is waiting on you", and this is the same thing being waited on.
fn render_approval(
    frame: &mut Frame,
    request: &crate::channels::ApprovalRequest,
    area: Rect,
    palette: &ColorPalette,
) {
    let frame_area = Rect {
        height: APPROVAL_FRAME_HEIGHT.min(area.height),
        ..area
    };
    let block = frame_block(palette.accent);
    let inner = block.inner(frame_area);
    frame.render_widget(block, frame_area);

    let lines = vec![
        Line::from(vec![
            Span::styled(STEP_GLYPH, Style::default().fg(palette.accent)),
            Span::styled(request.detail.clone(), Style::default().fg(palette.fg)),
        ]),
        // Spelled out rather than left to a legend elsewhere: this is the one prompt where
        // guessing wrong writes to the user's files.
        Line::from(Span::styled(
            // "always" is scoped to what this question names — this file, this contract on this
            // network — so the hint says "for this" rather than implying the whole tool.
            "  y allow · a always for this · n deny",
            Style::default().fg(palette.dim),
        )),
    ];
    frame.render_widget(Paragraph::new(lines), inner);
}

fn render_input(frame: &mut Frame, state: &AppState, area: Rect, palette: &ColorPalette) {
    if let Some(request) = &state.pending_approval {
        render_approval(frame, request, area, palette);
        return;
    }

    let show_autocomplete = state.autocomplete_active && !state.autocomplete_matches.is_empty();

    let input_area = Rect {
        x: area.x,
        y: area.y,
        width: area.width,
        height: INPUT_FRAME_HEIGHT,
    };

    // The input frame is the one piece of chrome drawn in the brand yellow: it is where the user
    // acts, and it is the only thing on screen that is always waiting on them.
    let block = frame_block(palette.accent);
    let inner = block.inner(input_area);
    frame.render_widget(block, input_area);

    // The prompt glyph is the same one that marks the user's turns above, so the connection
    // between "what I typed" and "what I said" is visual rather than stated.
    let line = Line::from(vec![
        Span::styled(USER_GLYPH, Style::default().fg(palette.accent)),
        Span::styled(state.input.as_str(), Style::default().fg(palette.fg)),
    ]);
    frame.render_widget(Paragraph::new(line), inner);

    let cursor_x = (inner.x + USER_GLYPH.chars().count() as u16 + state.input_cursor as u16)
        .min(inner.x + inner.width.saturating_sub(1));
    frame.set_cursor_position((cursor_x, inner.y));

    if show_autocomplete {
        let items = &state.autocomplete_matches;

        let popup_area = Rect {
            // Aligned under the typed text, not under the glyph.
            x: inner.x + USER_GLYPH.chars().count() as u16,
            y: area.y + INPUT_FRAME_HEIGHT,
            width: autocomplete_popup_width(items, area.width.saturating_sub(2)),
            height: autocomplete_popup_height(items.len()),
        };

        let offset = autocomplete_scroll_offset(state.autocomplete_selected, items.len());

        let lines: Vec<Line<'static>> = items
            .iter()
            .enumerate()
            .skip(offset)
            .take(AUTOCOMPLETE_MAX_VISIBLE)
            .map(|(i, item)| {
                let style = if i == state.autocomplete_selected {
                    Style::default()
                        .fg(palette.accent)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(palette.fg)
                };
                Line::from(vec![
                    Span::styled(
                        format!(" {:<width$} ", item.value, width = AUTOCOMPLETE_NAME_COLUMN),
                        style,
                    ),
                    Span::styled(item.description.clone(), Style::default().fg(palette.dim)),
                ])
            })
            .collect();

        let popup = Paragraph::new(lines).block(frame_block(palette.dim));

        frame.render_widget(ratatui::widgets::Clear, popup_area);
        frame.render_widget(popup, popup_area);
    }
}

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

    fn palette() -> ColorPalette {
        ColorPalette::from_theme(&Theme::Dark)
    }

    fn rendered(msg: &ChatMessage, width: usize) -> Vec<String> {
        message_lines(msg, &palette(), width)
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect()
    }

    // The input chunk has to reserve the popup's rows: sizing it to a fixed 8 clipped the last
    // suggestions, so a 10-match list rendered as 3.
    #[test]
    fn the_popup_reserves_a_row_per_visible_suggestion() {
        assert_eq!(autocomplete_popup_height(3), 5);
        assert_eq!(
            autocomplete_popup_height(10),
            AUTOCOMPLETE_MAX_VISIBLE as u16 + 2
        );
    }

    // The old fixed 52-column cap truncated the longer descriptions ("local/testne").
    #[test]
    fn the_popup_widens_to_fit_the_longest_description() {
        let items: Vec<AutocompleteItem> = AppState::slash_commands()
            .iter()
            .map(|c| AutocompleteItem {
                value: c.name.to_string(),
                description: c.description.to_string(),
            })
            .collect();

        let width = autocomplete_popup_width(&items, 200);
        let longest = items
            .iter()
            .map(|c| c.description.chars().count())
            .max()
            .unwrap();
        assert!(width as usize >= AUTOCOMPLETE_NAME_COLUMN + longest);

        // Never wider than the space it was given.
        assert_eq!(autocomplete_popup_width(&items, 30), 30);
    }

    #[test]
    fn the_popup_scrolls_to_keep_the_selection_visible() {
        // Short lists never scroll.
        assert_eq!(autocomplete_scroll_offset(2, 3), 0);
        // Long lists hold still until the highlight reaches the bottom row...
        assert_eq!(
            autocomplete_scroll_offset(AUTOCOMPLETE_MAX_VISIBLE - 1, 10),
            0
        );
        // ...then follow it, and stop once the last entry is on screen.
        assert_eq!(autocomplete_scroll_offset(AUTOCOMPLETE_MAX_VISIBLE, 10), 1);
        assert_eq!(
            autocomplete_scroll_offset(9, 10),
            10 - AUTOCOMPLETE_MAX_VISIBLE
        );
    }

    // Regression: the palette used to window the list before applying the scroll offset, so once
    // the highlight moved past the first screenful every row was filtered out and the popup went
    // blank below the first few entries.
    #[test]
    fn the_palette_keeps_showing_rows_as_the_selection_descends() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut state = AppState::new();
        state.handle_key(
            KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL),
            &tx,
        );
        assert!(state.palette_open, "ctrl+k should open the palette");
        let total = state.palette_matches.len();
        assert!(total > 5, "need a scrollable list, got {}", total);

        for step in 0..total {
            let screen = buffer_rows(80, 24, |frame, area| {
                let _ = area;
                render_palette(frame, &state, &palette())
            })
            .join("\n");

            let selected = &state.palette_matches[state.palette_selected].value;
            assert!(
                screen.contains(selected.as_str()),
                "selection {:?} off screen at step {}:\n{}",
                selected,
                step,
                screen
            );
            let before = state.palette_selected;
            state.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), &tx);
            assert_ne!(
                before, state.palette_selected,
                "Down must move the selection, or this test proves nothing"
            );
        }
    }

    #[test]
    fn a_windowed_list_scrolls_only_once_the_cursor_reaches_the_bottom() {
        // Fits entirely: never scrolls.
        assert_eq!(scroll_offset(2, 3, 5), 0);
        // Holds still until the highlight reaches the last visible row...
        assert_eq!(scroll_offset(4, 10, 5), 0);
        // ...then follows it, and stops with the final entry on screen.
        assert_eq!(scroll_offset(5, 10, 5), 1);
        assert_eq!(scroll_offset(9, 10, 5), 5);
        // A zero-row window is a degenerate layout, not a panic.
        assert_eq!(scroll_offset(3, 10, 0), 0);
    }

    #[test]
    fn wraps_at_the_given_width() {
        let lines = wrap_text("aaa bbb ccc ddd", 7);
        assert_eq!(lines, vec!["aaa bbb", "ccc ddd"]);
        assert!(lines.iter().all(|l| l.chars().count() <= 7));
    }

    #[test]
    fn short_text_stays_on_one_line() {
        assert_eq!(wrap_text("hello", 40), vec!["hello"]);
    }

    #[test]
    fn breaks_a_word_longer_than_the_line() {
        let lines = wrap_text("aaaaaaaaaa", 4);
        assert!(lines.iter().all(|l| l.chars().count() <= 4), "{:?}", lines);
        assert_eq!(lines.concat(), "aaaaaaaaaa");
    }

    #[test]
    fn wrapping_preserves_multibyte_content() {
        let lines = wrap_text("ação corrigida direito", 10);
        assert!(lines.iter().all(|l| l.chars().count() <= 10), "{:?}", lines);
        assert_eq!(lines.join(" "), "ação corrigida direito");
    }

    #[test]
    fn long_message_produces_multiple_lines_instead_of_truncating() {
        let long = "palavra ".repeat(20).trim_end().to_string();
        let lines = rendered(&ChatMessage::Agent(long), 20);
        assert!(lines.len() > 1, "expected wrapping, got {:?}", lines);
        assert!(lines.iter().all(|l| l.chars().count() <= 20), "{:?}", lines);
    }

    #[test]
    fn the_user_turn_is_marked_and_continuations_line_up_under_the_text() {
        let lines = rendered(&ChatMessage::User("um dois tres quatro".to_string()), 12);
        assert!(lines[0].starts_with(USER_GLYPH), "got {:?}", lines);
        assert!(lines[1].starts_with("  "), "got {:?}", lines);
    }

    // The agent produces most of the transcript, so it carries no marker at all — its prose is
    // the body of the page, not a quoted participant.
    #[test]
    fn the_agent_speaks_without_a_marker() {
        let lines = rendered(&ChatMessage::Agent("um\ndois".to_string()), 40);
        assert_eq!(lines, vec!["um", "dois"]);
    }

    #[test]
    fn embedded_newlines_start_new_lines() {
        let lines = rendered(&ChatMessage::System("um\ndois\ntres".to_string()), 40);
        assert_eq!(lines, vec!["⏺ um", "  dois", "  tres"]);
    }

    // The agent's own trace is not a chat participant. It used to be pushed as a message and
    // drawn with the user's glyph — the test that covered it was called "gets a trace glyph not a
    // speaker label" and asserted `› MCP raven connected`. There is no such message now: a status
    // is an execution step and only an execution step.
    #[test]
    fn only_the_user_speaks_with_the_user_glyph() {
        assert_eq!(
            rendered(&ChatMessage::User("oi".to_string()), 40),
            vec!["› oi"]
        );
        // A notice addressed to the user is chrome, not a turn.
        assert_eq!(
            rendered(&ChatMessage::System("MCP raven connected".to_string()), 40),
            vec!["⏺ MCP raven connected"]
        );
    }

    #[test]
    fn following_resolves_to_the_last_screenful() {
        let mut state = AppState::new();
        assert!(state.is_following_chat());
        assert_eq!(state.resolve_scroll(6), 6);
    }

    #[test]
    fn scrolling_forward_to_the_bottom_resumes_following() {
        let mut state = AppState::new();
        state.resolve_scroll(6);

        state.scroll_back(2);
        assert!(!state.is_following_chat());
        assert_eq!(state.resolve_scroll(6), 4);

        state.scroll_forward(2);
        assert_eq!(state.resolve_scroll(6), 6);
        assert!(
            state.is_following_chat(),
            "reaching the bottom must re-enable auto-follow"
        );
    }

    fn buffer_rows(width: u16, height: u16, draw: impl FnOnce(&mut Frame, Rect)) -> Vec<String> {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| {
                let area = frame.area();
                draw(frame, area);
            })
            .unwrap();

        let buffer = terminal.backend().buffer().clone();
        (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    // Renders through a real backend so the assertion is about what actually reaches the screen,
    // not about the intermediate offset arithmetic.
    fn visible_chat(state: &mut AppState, width: u16, height: u16) -> Vec<String> {
        buffer_rows(width, height, |frame, area| {
            render_chat(frame, state, area, &palette())
        })
    }

    fn numbered_state(count: usize) -> AppState {
        let mut state = AppState::new();
        state.messages.clear();
        for i in 0..count {
            state
                .messages
                .push(ChatMessage::System(format!("msg{}", i)));
        }
        state
    }

    #[test]
    fn at_rest_the_newest_messages_are_visible() {
        let mut state = numbered_state(20);
        let screen = visible_chat(&mut state, 30, 6).join("\n");

        assert!(screen.contains("msg19"), "newest missing:\n{}", screen);
        assert!(
            !screen.contains("msg0\n"),
            "oldest should be off-screen:\n{}",
            screen
        );
    }

    #[test]
    fn scrolling_up_reveals_older_messages() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);

        for _ in 0..5 {
            state.scroll_back(1);
        }
        let screen = visible_chat(&mut state, 30, 6).join("\n");

        assert!(
            screen.contains("msg14"),
            "expected older content:\n{}",
            screen
        );
        assert!(
            !screen.contains("msg19"),
            "newest should have scrolled off:\n{}",
            screen
        );
    }

    #[test]
    fn scrolling_back_down_returns_to_the_newest() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);
        state.scroll_back(5);
        visible_chat(&mut state, 30, 6);
        state.scroll_forward(5);

        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(
            screen.contains("msg19"),
            "should be back at the bottom:\n{}",
            screen
        );
    }

    // Scrolled back, the last row carries the "N more" marker, whose count legitimately changes
    // when a message arrives — so the comparison is over the rows above it.
    #[test]
    fn a_new_message_pins_the_view_to_the_bottom() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);

        state
            .messages
            .push(ChatMessage::Agent("recem chegada".to_string()));
        let screen = visible_chat(&mut state, 30, 6).join("\n");

        assert!(
            screen.contains("recem chegada"),
            "new message not shown:\n{}",
            screen
        );
    }

    #[test]
    fn scrolling_up_then_receiving_a_message_keeps_the_reader_in_place() {
        let body = |screen: Vec<String>| screen[..screen.len() - 1].to_vec();

        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);
        state.scroll_back(5);
        let before = body(visible_chat(&mut state, 30, 6));

        state.messages.push(ChatMessage::Agent("nova".to_string()));
        let after = body(visible_chat(&mut state, 30, 6));

        assert_eq!(
            before, after,
            "a message arriving must not yank a scrolled-back reader"
        );
    }

    #[test]
    fn scrolled_back_the_transcript_says_how_much_is_below() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);
        state.scroll_back(5);

        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(screen.contains("↓ 5 more"), "got:\n{}", screen);
    }

    #[test]
    fn at_rest_there_is_no_scroll_marker() {
        let mut state = numbered_state(20);
        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(!screen.contains("more"), "got:\n{}", screen);
    }

    #[test]
    fn scrolling_stops_at_the_oldest_message() {
        let mut state = numbered_state(20);
        for _ in 0..500 {
            state.scroll_back(1);
            visible_chat(&mut state, 30, 6);
        }
        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(
            screen.contains("msg0"),
            "oldest should be reachable:\n{}",
            screen
        );
    }

    #[test]
    fn runaway_scrolling_stops_at_the_first_line() {
        let mut state = AppState::new();
        state.resolve_scroll(7);
        for _ in 0..500 {
            state.scroll_back(1);
        }
        assert_eq!(
            state.resolve_scroll(7),
            0,
            "must not scroll above the first line"
        );
    }

    fn statusline(state: &AppState, width: u16) -> String {
        buffer_rows(width, 1, |frame, area| {
            render_statusline(frame, state, area, &palette())
        })
        .remove(0)
    }

    // The status line replaced a 34-column sidebar, so what it does and does not carry is the
    // whole design decision. Account was originally left to `/status` on the grounds that the row
    // was too precious; that reasoning does not survive an approval prompt for a transaction whose
    // signer is off screen, so it is here now — and MCP is still the thing that is not.
    #[test]
    fn the_statusline_carries_network_and_model() {
        let state = AppState::new();
        let row = statusline(&state, 90);

        assert!(row.contains(&state.active_network), "got: {:?}", row);
        assert!(row.contains(&state.active_model), "got: {:?}", row);
        assert!(row.contains("ctrl+k"), "got: {:?}", row);
    }

    // On a 4k local window a session is a handful of tool calls from compaction, and before this
    // nothing said so until the early turns were already gone.
    #[test]
    fn the_statusline_shows_how_full_the_context_window_is() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Context {
            used: 2_100,
            window: 4_096,
        });
        assert!(statusline(&state, 120).contains("ctx 2.1k/4.1k"));
    }

    // A gauge nobody has measured yet must not read as an empty one: for Ollama the window is
    // whatever the server loaded the model with, and nothing is loaded before the first request.
    #[test]
    fn the_context_gauge_is_absent_until_a_turn_has_run() {
        assert!(!statusline(&AppState::new(), 120).contains("ctx "));
    }

    // Everything §9 of the spec requires the interface to keep on screen, in one row.
    #[test]
    fn the_statusline_carries_the_whole_working_context() {
        let mut state = AppState::new();
        state.project_name = "demo".to_string();
        state.active_account = "alice".to_string();
        state.active_contract = Some("counter".to_string());
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        let row = statusline(&state, 120);
        for expected in [
            "testnet",           // network
            "alice",             // account
            "demo",              // project
            "counter",           // contract
            "anthropic",         // provider, from the default state
            "guarded",           // risk mode
            "Building contract", // operation in flight
        ] {
            assert!(
                row.contains(expected),
                "{:?} missing from {:?}",
                expected,
                row
            );
        }
    }

    // The posture has to be readable without doing arithmetic on the other fields: "mainnet" plus
    // "(read-only)" answers one question, and this answers the other one — whether anything in this
    // session may sign against real funds at all.
    #[test]
    fn the_risk_mode_says_whether_this_session_can_spend() {
        let mut state = AppState::new();
        assert!(statusline(&state, 90).contains("guarded"), "off by default");

        state.mainnet_allowed = true;
        let row = statusline(&state, 90);
        assert!(row.contains("armed"), "got: {:?}", row);
        assert!(!row.contains("guarded"), "got: {:?}", row);
    }

    // A slot the app has not filled yet must read as a gap, not as a value: "None" sitting between
    // a network and a model looks like the name of something.
    #[test]
    fn an_unset_account_or_project_reads_as_absent() {
        let row = statusline(&AppState::new(), 120);
        assert!(row.contains("no account"), "got: {:?}", row);
        assert!(row.contains("no project"), "got: {:?}", row);
        assert!(!row.contains("None"), "got: {:?}", row);
    }

    // Regression, found by driving the real binary: with an Ollama tag the provider/model segment
    // was 36 columns, and on a 100-column terminal that alone pushed the project name off the row.
    #[test]
    fn a_long_model_tag_is_abbreviated_rather_than_costing_another_field() {
        let mut state = AppState::new();
        state.active_provider = "ollama".to_string();
        state.active_model = "qwen3:4b-instruct-2507-q4_K_M".to_string();
        state.project_name = "demo".to_string();

        let row = statusline(&state, 100);
        assert!(row.contains("demo"), "the project must survive: {:?}", row);
        assert!(row.contains("ollama qwen3"), "got: {:?}", row);
        assert!(row.contains(''), "the tag must say it was cut: {:?}", row);
    }

    // Cutting the row from the right dropped whatever happened to sit rightmost — which was the
    // operation in flight, while a project name survived. Segments go by importance instead.
    #[test]
    fn a_narrow_row_gives_up_context_before_it_gives_up_the_operation() {
        let mut state = AppState::new();
        state.project_name = "some-rather-long-project-name".to_string();
        state.active_account = "alice".to_string();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_deploy".to_string(),
        ));

        let row = statusline(&state, 46);
        assert!(row.contains("testnet"), "got: {:?}", row);
        assert!(row.contains("Deploying"), "got: {:?}", row);
        assert!(
            !row.contains("some-rather-long-project-name"),
            "the project name is the first thing to go: {:?}",
            row
        );
    }

    #[test]
    fn the_statusline_shows_the_current_activity_while_working() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        let row = statusline(&state, 90);
        assert!(row.contains("Building contract"), "got: {:?}", row);
    }

    // One row is all the layout budgets. A long activity string, or a narrow terminal, must not
    // wrap into a second line — there is no second line to wrap into.
    #[test]
    fn the_statusline_never_overflows_its_single_row() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "a very long tool status that would otherwise overflow the whole status line"
                .to_string(),
        ));

        for width in [30u16, 45, 60, 90] {
            let row = statusline(&state, width);
            assert!(
                row.chars().count() <= width as usize,
                "overflowed at width {}: {:?}",
                width,
                row
            );
        }
    }

    // Regression: with the gap unenforced, a status line that filled the row exactly rendered
    // "Building contract? shortcuts · ctrl+k" — the hint read as part of the activity.
    #[test]
    fn the_hint_never_touches_the_text_on_its_left() {
        let mut state = AppState::new();
        state.active_model = "qwen3:4b-instruct-2507-q4_K_M".to_string();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        for width in 60..120u16 {
            let row = statusline(&state, width);
            // Whichever hint this state renders — searching for one spelling only would make the
            // assertion vanish the day the other applies, which is exactly what a `Status` update
            // does by flipping the app to Working.
            let at = ["esc interrupt", "? shortcuts"]
                .iter()
                .find_map(|marker| row.find(marker));
            if let Some(at) = at {
                assert!(
                    row[..at].ends_with("  "),
                    "hint glued to the activity at width {}: {:?}",
                    width,
                    row
                );
            }
        }
    }

    // The regression: the whole trace was appended after the last message, so the tool calls of a
    // turn were drawn below the answer they produced — the result above its own cause.
    #[test]
    fn a_tool_call_is_drawn_above_the_reply_it_fed() {
        let mut state = AppState::new();
        state.messages.push(ChatMessage::User("liste".to_string()));
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: list_dir".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::ToolFinished {
            name: "list_dir".to_string(),
            ok: true,
        });
        state.handle_agent_update(crate::channels::AgentUpdate::ResponseChunk(
            "aqui estao".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::ResponseEnd);

        let rows = buffer_rows(70, 20, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        });
        let row_of = |needle: &str| {
            rows.iter()
                .position(|r| r.contains(needle))
                .unwrap_or_else(|| panic!("{:?} not on screen: {:#?}", needle, rows))
        };

        assert!(row_of("liste") < row_of("list_dir"));
        assert!(
            row_of("list_dir") < row_of("aqui estao"),
            "the tool call was drawn below the answer it produced: {:#?}",
            rows
        );
    }

    // A second round trip's tools belong after the first reply, not bundled with the first.
    #[test]
    fn each_round_trip_keeps_its_own_place_in_the_transcript() {
        let mut state = AppState::new();
        state.messages.push(ChatMessage::User("faca".to_string()));
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: grep".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::ResponseChunk(
            "primeiro".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: write_file".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::ResponseChunk(
            "segundo".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::ResponseEnd);

        let rows = buffer_rows(70, 20, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        });
        let row_of = |needle: &str| {
            rows.iter()
                .position(|r| r.contains(needle))
                .unwrap_or_else(|| panic!("{:?} not on screen: {:#?}", needle, rows))
        };

        assert!(row_of("grep") < row_of("primeiro"), "{:#?}", rows);
        assert!(row_of("primeiro") < row_of("write_file"), "{:#?}", rows);
        assert!(row_of("write_file") < row_of("segundo"), "{:#?}", rows);
    }

    #[test]
    fn the_trace_says_how_each_tool_ended() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: read_file".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_deploy".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::ToolFinished {
            name: "read_file".to_string(),
            ok: true,
        });
        state.handle_agent_update(crate::channels::AgentUpdate::ToolFinished {
            name: "caatinga_deploy".to_string(),
            ok: false,
        });

        let screen = buffer_rows(90, 24, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        })
        .join("\n");

        assert!(screen.contains("read_file — done"), "{}", screen);
        assert!(screen.contains("caatinga_deploy — failed"), "{}", screen);
        // The present-tense description is what made the trace read as a set of steps that never
        // ended, so it must not survive the call it described.
        assert!(!screen.contains("deploying to network"), "{}", screen);
    }

    #[test]
    fn a_finished_phase_drops_its_ellipsis() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Thinking...".to_string(),
        ));

        let running = buffer_rows(90, 24, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        })
        .join("\n");
        assert!(running.contains("Thinking..."), "{}", running);

        state.handle_agent_update(crate::channels::AgentUpdate::ResponseEnd);
        let settled = buffer_rows(90, 24, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        })
        .join("\n");
        assert!(settled.contains("Thought"), "{}", settled);
        assert!(!settled.contains("Thinking..."), "{}", settled);
    }

    #[test]
    fn a_tool_parked_on_approval_does_not_claim_to_be_working() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: write_file".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::Approval(
            crate::channels::ApprovalRequest {
                tool: "write_file".to_string(),
                detail: "write_file → src/lib.rs".to_string(),
                scope: "write_file:src/lib.rs".to_string(),
            },
        ));

        let screen = buffer_rows(90, 24, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        })
        .join("\n");

        assert!(
            screen.contains("write_file — waiting for you"),
            "{}",
            screen
        );
        assert!(!screen.contains("write_file — writing file"), "{}", screen);
    }

    #[test]
    fn an_approval_replaces_the_prompt_with_the_question_and_its_keys() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Approval(
            crate::channels::ApprovalRequest {
                tool: "write_file".to_string(),
                detail: "write_file → src/lib.rs".to_string(),
                scope: "write_file:src/lib.rs".to_string(),
            },
        ));

        let rows = buffer_rows(90, 24, |frame, _| {
            render(frame, &mut state, &Theme::Dark);
        });
        let screen = rows.join("\n");

        assert!(screen.contains("src/lib.rs"), "{}", screen);
        // Spelled out on screen: nobody should have to guess the keys on the one prompt that
        // writes to their files.
        assert!(screen.contains("y allow"), "{}", screen);
        assert!(screen.contains("a always"), "{}", screen);
        assert!(screen.contains("n deny"), "{}", screen);

        // The input line is gone while the question stands — a prompt that still looked typeable
        // would invite typing into an input that cannot be submitted.
        let prompt_rows = rows.iter().filter(|r| r.contains("")).count();
        assert_eq!(prompt_rows, 0, "{}", screen);
    }

    // A turn the user cannot stop was the complaint; a stop key they cannot find is the same
    // complaint with extra steps.
    #[test]
    fn the_statusline_offers_the_stop_key_while_a_turn_runs() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Thinking...".to_string(),
        ));
        assert!(statusline(&state, 90).contains("esc interrupt"));

        // And gets out of the way once there is nothing to stop.
        state.handle_agent_update(crate::channels::AgentUpdate::ResponseEnd);
        let idle = statusline(&state, 90);
        assert!(!idle.contains("esc interrupt"), "got {:?}", idle);
        assert!(idle.contains("? shortcuts"));
    }

    // The status line is what persists — a switch message scrolls away — so it is where "mainnet
    // but nothing may sign" has to keep being said.
    // A hard cut looks like a rendering fault; an ellipsis says there is more. The banner had two
    // lines that the renderer clipped mid-word at 60 columns.
    #[test]
    fn the_welcome_banner_never_ends_mid_word() {
        let mut state = AppState::new();
        state.active_provider = "ollama".to_string();
        state.active_model = "qwen3:4b-instruct-2507-q4_K_M".to_string();
        state.project_name = "my-app".to_string();

        for width in [50u16, 60, 70, 78, 100] {
            let rows = buffer_rows(width, 16, |frame, _| {
                render(frame, &mut state, &Theme::Dark);
            });

            for row in &rows {
                assert!(
                    row.chars().count() <= width as usize,
                    "overflowed at {}: {:?}",
                    width,
                    row
                );
            }

            // The hint sheds a phrase at a time; whichever tier is chosen, it arrives whole.
            let hint = rows
                .iter()
                .find(|r| r.contains("ctrl+k"))
                .map(|r| r.trim_matches(|c: char| c == '' || c == ' ').to_string())
                .unwrap_or_else(|| panic!("no hint at {}", width));
            assert!(
                [
                    "Type / for commands · ctrl+k for the palette · ? for shortcuts",
                    "/ commands · ctrl+k palette · ? shortcuts",
                    "/ · ctrl+k · ?",
                ]
                .contains(&hint.as_str()),
                "hint was cut at {}: {:?}",
                width,
                hint
            );

            // The model name is the long part. Either it fits whole, or it ends in an ellipsis.
            let model_row = rows
                .iter()
                .find(|r| r.contains("ollama"))
                .unwrap_or_else(|| panic!("no model row at {}", width));
            assert!(
                model_row.contains(&state.active_model) || model_row.contains(''),
                "cut without an ellipsis at {}: {:?}",
                width,
                model_row
            );
        }
    }

    #[test]
    fn a_mainnet_that_cannot_sign_is_marked_read_only() {
        let mut state = AppState::new();
        state.active_network = "mainnet".to_string();
        state.mainnet_allowed = false;
        assert!(statusline(&state, 90).contains("mainnet (read-only)"));

        state.mainnet_allowed = true;
        let signing = statusline(&state, 90);
        assert!(signing.contains("mainnet"));
        assert!(!signing.contains("read-only"), "got {:?}", signing);
    }

    #[test]
    fn a_network_that_cannot_spend_carries_no_such_warning() {
        let mut state = AppState::new();
        state.active_network = "testnet".to_string();
        assert!(!statusline(&state, 90).contains("read-only"));
    }

    #[test]
    fn mainnet_is_called_out_in_the_statusline() {
        let mut state = AppState::new();
        state.active_network = "mainnet".to_string();
        assert!(statusline(&state, 90).contains("mainnet"));
    }

    #[test]
    fn a_contract_id_is_abbreviated_rather_than_eating_the_status_line() {
        assert_eq!(abbreviate("CABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), "CABC…4567");
        // Short enough to show whole: leave it alone.
        assert_eq!(abbreviate("CABCDEF"), "CABCDEF");
    }

    #[test]
    fn truncation_marks_what_it_cut() {
        assert_eq!(truncate_to("abcdef", 4), "abc…");
        assert_eq!(truncate_to("abc", 10), "abc");
    }

    fn whole_screen(state: &mut AppState, width: u16, height: u16) -> Vec<String> {
        buffer_rows(width, height, |frame, _area| {
            render(frame, state, &Theme::Dark)
        })
    }

    // The frames are the only chrome left, so they have to be exactly two — the conversation and
    // the input — and they have to be the rounded house frame, not ratatui's square default.
    #[test]
    fn the_conversation_and_the_input_each_get_a_rounded_frame() {
        let mut state = AppState::new();
        let rows = whole_screen(&mut state, 60, 12);

        let top_corners: Vec<usize> = rows
            .iter()
            .enumerate()
            .filter(|(_, r)| r.starts_with(''))
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            top_corners,
            vec![0, 8],
            "expected two frames, got:\n{}",
            rows.join("\n")
        );

        // The input frame is the last one, and the status line sits outside it, unframed.
        assert!(rows[10].starts_with(''), "got:\n{}", rows.join("\n"));
        assert!(
            !rows[11].contains('') && rows[11].contains("testnet"),
            "status line must stay outside the frames:\n{}",
            rows.join("\n")
        );
    }

    // Text inside a frame must not touch it: without the padding the transcript rendered as
    // "│Built it: …", which reads as a rendering fault rather than as a margin.
    #[test]
    fn framed_content_keeps_a_column_of_air() {
        let mut state = AppState::new();
        state.messages.push(ChatMessage::Agent("olá".to_string()));
        state.input = "oi".to_string();

        for row in whole_screen(&mut state, 60, 12) {
            if let Some(rest) = row.strip_prefix('') {
                assert!(
                    rest.starts_with(' '),
                    "content flush against the frame: {:?}",
                    row
                );
            }
        }
    }

    fn welcome(state: &AppState, width: u16, height: u16) -> String {
        buffer_rows(width, height, |frame, area| {
            render_welcome(frame, state, area, &palette())
        })
        .join("\n")
    }

    // The banner is the only place the product says what it is, so it has to carry the Stellar
    // mark, the name, where you are, and the way in — nothing else in the interface repeats them.
    #[test]
    fn the_banner_introduces_the_session() {
        let state = AppState::new();
        let screen = welcome(&state, 90, 10);

        assert!(screen.contains("procyon"), "got:\n{}", screen);
        assert!(screen.contains("Stellar"), "got:\n{}", screen);
        for row in STELLAR_MARK {
            assert!(screen.contains(row.trim()), "mark missing:\n{}", screen);
        }
        assert!(screen.contains(&state.cwd_label), "got:\n{}", screen);
        assert!(screen.contains(&state.active_network), "got:\n{}", screen);
        assert!(screen.contains("ctrl+k"), "got:\n{}", screen);
    }

    // The working directory is a label, not a lookup: it must not change between frames and must
    // never be an absolute /home path when $HOME covers it.
    #[test]
    fn the_working_directory_is_written_the_way_a_person_writes_it() {
        let state = AppState::new();
        if std::env::var_os("HOME").is_some() && state.cwd_label != "." {
            assert!(
                !state.cwd_label.starts_with("/home/"),
                "expected a ~-relative path, got {:?}",
                state.cwd_label
            );
        }
        assert_eq!(state.cwd_label, AppState::new().cwd_label, "must be stable");
    }

    // The banner is a first impression, not a permanent header: the moment there is anything to
    // read it steps aside and the transcript owns the area.
    #[test]
    fn the_banner_gives_way_to_the_transcript() {
        let mut state = AppState::new();
        assert!(!has_conversation(&state));

        state.messages.push(ChatMessage::User("oi".to_string()));
        assert!(has_conversation(&state));
    }

    // Regression: slash commands reply with `System` and nothing else. While the banner only
    // yielded to User/Agent messages it stayed pinned over their output, so every command looked
    // like it had silently done nothing.
    #[test]
    fn a_command_reply_is_enough_to_retire_the_banner() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut state = AppState::new();
        // Driven through the keyboard so the test covers the path a user actually takes.
        for c in "/help".chars() {
            state.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE), &tx);
        }
        state.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), &tx);

        assert!(has_conversation(&state), "banner would cover /help output");

        let screen = buffer_rows(90, 20, |frame, area| {
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Min(0)])
                .split(area);
            render_chat(frame, &mut state, chunks[0], &palette())
        })
        .join("\n");
        assert!(screen.contains("Quick actions"), "got:\n{}", screen);
    }

    fn execution_rows(state: &AppState, width: usize) -> Vec<String> {
        state
            .execution_steps
            .iter()
            .flat_map(|step| execution_step_lines(step, &palette(), width))
            .collect::<Vec<_>>()
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect()
    }

    #[test]
    fn a_phase_is_a_step_and_a_tool_call_hangs_off_it() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Thinking...".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        let rows = execution_rows(&state, 60);
        // The subject here is the hierarchy, not the wording: a phase carries `⏺` at the margin
        // and a tool call hangs off it, indented, under `⎿`. The phase reads "Thought" rather
        // than "Thinking..." because starting the tool closed it.
        assert!(
            rows.iter().any(|r| r.starts_with("⏺ Thought")),
            "got {:?}",
            rows
        );
        assert!(
            rows.iter()
                .any(|r| r.starts_with("  ⎿ caatinga_build — building contract")),
            "got {:?}",
            rows
        );
    }

    // Regression: the trace used to be wrapped in a hand-built border whose width arithmetic
    // sliced multibyte glyphs. There is no border now, and nothing may panic on multibyte labels.
    #[test]
    fn execution_labels_survive_multibyte_content_at_any_width() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "compilação atualizações — configuração".to_string(),
        ));

        for width in 1..40usize {
            let rows = execution_rows(&state, width);
            assert!(!rows.is_empty(), "no rows at width {}", width);
        }
    }
}