procyon 0.1.0

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
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
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
use std::path::PathBuf;

use crossterm::event::{KeyCode, KeyEventKind, KeyModifiers};
use tokio::sync::mpsc;

use crate::channels::{AgentUpdate, UserCommand};
use crate::config::Provider;
use crate::credentials::CredentialStore;

pub struct SlashCommand {
    pub name: &'static str,
    pub description: &'static str,
}

/// One suggestion in the autocomplete popup. Owned rather than an index into `SLASH_COMMANDS`,
/// since past the command name the candidates are generated on the fly — provider names, model
/// names, `/model`'s subcommands — and don't live in any static table.
#[derive(Clone, Debug, PartialEq)]
pub struct AutocompleteItem {
    pub value: String,
    pub description: String,
}

const SLASH_COMMANDS: &[SlashCommand] = &[
    SlashCommand {
        name: "/help",
        description: "Show this help",
    },
    SlashCommand {
        name: "/clear",
        description: "Clear chat history",
    },
    SlashCommand {
        name: "/status",
        description: "Show connection status",
    },
    SlashCommand {
        name: "/project",
        description: "Show project info",
    },
    SlashCommand {
        name: "/explain",
        description: "Toggle explain mode",
    },
    SlashCommand {
        name: "/network",
        description: "Switch network (local/testnet/mainnet)",
    },
    SlashCommand {
        name: "/model",
        description: "Show model status and suggestions",
    },
    SlashCommand {
        name: "/model set",
        description: "Switch provider and model",
    },
    SlashCommand {
        name: "/model provider",
        description: "Switch provider only",
    },
    SlashCommand {
        name: "/model model",
        description: "Switch model only",
    },
    SlashCommand {
        name: "/login",
        description: "Save an API key for a provider",
    },
    SlashCommand {
        name: "/logout",
        description: "Remove a stored API key",
    },
    SlashCommand {
        name: "/providers",
        description: "Show credential status for every provider",
    },
    SlashCommand {
        name: "/install-stellar-build",
        description: "Install the Stellar Build persona pack (third-party)",
    },
];

#[derive(Clone, Debug)]
pub enum ChatMessage {
    User(String),
    Agent(String),
    System(String),
    /// Agent-internal trace — tool calls, MCP status, "Thinking..." — as opposed to `System`,
    /// which is reserved for genuine notices addressed to the user (the welcome banner, `/help`
    /// output, command errors). Rendered distinctly so machine noise doesn't read as another chat
    /// participant.
    Event(String),
}

/// What the agent can do right now.
///
/// Not a connection state: every request is a fresh HTTP call, so there is nothing to stay
/// connected to. The old `Connected`/`Disconnected` pair reported a link that never existed and,
/// worse, latched — the first error of the session left the header claiming the tool was unusable
/// for as long as it ran.
#[derive(Clone, Debug, PartialEq)]
pub enum AppStatus {
    /// A credential resolved for the selected provider, so prompts will be sent.
    Ready,
    /// A request is in flight.
    Working,
    /// No credential for the selected provider. Prompts are refused until one is set, or until the
    /// provider is switched to one that needs none.
    NeedsCredential,
}

/// The one place a status is worded, so the header and `/status` cannot disagree.
pub fn status_label(status: &AppStatus) -> &'static str {
    match status {
        AppStatus::Ready => "Ready",
        AppStatus::Working => "Working...",
        AppStatus::NeedsCredential => "No API key",
    }
}

/// Rich execution phase derived from the free-form Status string — keeps the Context
/// header specific ("Building contract", "Deploying") without exploding AppStatus
/// into one variant per tool.
pub fn activity_label(activity: &str) -> &'static str {
    let lower = activity.to_lowercase();
    if lower.contains("thinking") {
        "Thinking"
    } else if lower.contains("caatinga_build") || lower.contains("building") {
        "Building contract"
    } else if lower.contains("caatinga_deploy") || lower.contains("deploying") {
        "Deploying"
    } else if lower.contains("caatinga_doctor") || lower.contains("doctor") {
        "Checking env"
    } else if lower.contains("stellar_invoke")
        || lower.contains("caatinga_invoke")
        || lower.contains("invok")
    {
        "Invoking"
    } else if lower.contains("run_tests") || lower.contains("test") {
        "Testing"
    } else if lower.contains("raven") {
        "Searching Stellar Docs"
    } else if lower.contains("search") || lower.contains("grep") || lower.contains("glob") {
        "Searching"
    } else if lower.contains("using tool") {
        "Executing"
    } else {
        "Working..."
    }
}

/// The working directory written the way a person writes it — `~/code/thing`, not
/// `/home/someone/code/thing`. Falls back to the raw path, and then to `.`, rather than failing:
/// this is a label on a banner, not something worth refusing to start over.
fn home_relative_cwd() -> String {
    let cwd = match std::env::current_dir() {
        Ok(p) => p,
        Err(_) => return ".".to_string(),
    };
    let home = std::env::var_os("HOME").map(PathBuf::from);
    match home {
        Some(home) => match cwd.strip_prefix(&home) {
            Ok(rest) if rest.as_os_str().is_empty() => "~".to_string(),
            Ok(rest) => format!("~/{}", rest.display()),
            Err(_) => cwd.display().to_string(),
        },
        None => cwd.display().to_string(),
    }
}

/// Execution trace — one entry per tool/status line, kept separately from chat
/// so we can render a bordered Execution block instead of scattering lines.
#[derive(Clone, Debug, PartialEq)]
pub struct ExecutionStep {
    pub label: String,
    pub state: ExecutionStepState,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ExecutionStepState {
    Running,
    Done,
    Failed,
}

pub struct AppState {
    pub messages: Vec<ChatMessage>,
    pub input: String,
    pub input_cursor: usize,
    pub status: AppStatus,
    pub chat_scroll: usize,
    chat_follow: bool,
    pub project_name: String,
    /// Where the session was launched, with `$HOME` collapsed to `~`. Resolved once at startup
    /// rather than per frame: it cannot change while the process runs, and the welcome banner
    /// would otherwise stat the filesystem on every redraw.
    pub cwd_label: String,
    pub active_network: String,
    pub active_account: String,
    pub active_contract: Option<String>,
    pub active_provider: String,
    pub active_model: String,
    pub mcp_servers: Vec<crate::channels::McpServerStatus>,
    /// Command palette (Ctrl+K) state.
    pub palette_open: bool,
    pub palette_input: String,
    pub palette_cursor: usize,
    pub palette_matches: Vec<AutocompleteItem>,
    pub palette_selected: usize,
    agent_streaming: bool,
    explain_mode: bool,
    /// Mirrors the agent's last `Ready` update, so `settle()` knows which resting state a turn
    /// returns to once it ends or fails.
    has_credential: bool,
    /// Overrides where `/login`, `/logout` and `/providers` look for stored credentials.
    /// `None` means the real `~/.config/procyon/credentials.toml`; tests point this at a tempdir
    /// so they never touch the user's actual file.
    credentials_path: Option<PathBuf>,
    // Autocomplete state
    pub autocomplete_active: bool,
    pub autocomplete_matches: Vec<AutocompleteItem>,
    pub autocomplete_selected: usize,
    pub autocomplete_prefix: String,
    /// The last `Status` text the agent sent for the turn in progress (e.g. "Thinking...",
    /// "Using tool: build"), shown next to the spinner in the context panel. Cleared once the
    /// turn settles or the response starts streaming text.
    pub current_activity: Option<String>,
    /// Advanced once per tick (see `tick()`) to animate the spinner while `status == Working`.
    /// Meaningless otherwise, but cheap enough to just let it free-run.
    pub spinner_frame: usize,
    /// Previously submitted lines (prompts and slash commands alike), oldest first.
    command_history: Vec<String>,
    /// Position within `command_history` while recalling with Alt+Up/Alt+Down. `None` means the
    /// user is editing fresh input, not paging through history.
    history_cursor: Option<usize>,
    /// What was being typed before history recall started, restored once Alt+Down pages past the
    /// newest entry — otherwise that in-progress line would be lost.
    history_draft: String,
    /// Execution trace for the current turn — rendered as a bordered block inside chat.
    pub execution_steps: Vec<ExecutionStep>,
    pub execution_failed: bool,
}

impl AppState {
    pub fn new() -> Self {
        Self {
            // Empty on purpose: the welcome banner owns the screen until there is a real
            // conversation, so a greeting message here would only reappear at the top of the
            // transcript once the banner stepped aside.
            messages: Vec::new(),
            input: String::new(),
            input_cursor: 0,
            // Corrected by the agent's first `Ready` update, which it sends before accepting any
            // command. Starting optimistic keeps the header from flashing red on a healthy boot.
            status: AppStatus::Ready,
            chat_scroll: 0,
            chat_follow: true,
            project_name: "No project".to_string(),
            cwd_label: home_relative_cwd(),
            active_network: "testnet".to_string(),
            active_account: "None".to_string(),
            active_contract: None,
            active_provider: "anthropic".to_string(),
            active_model: "claude-sonnet-5".to_string(),
            mcp_servers: Vec::new(),
            palette_open: false,
            palette_input: String::new(),
            palette_cursor: 0,
            palette_matches: Vec::new(),
            palette_selected: 0,
            agent_streaming: false,
            explain_mode: false,
            has_credential: true,
            credentials_path: None,
            autocomplete_active: false,
            autocomplete_matches: Vec::new(),
            autocomplete_selected: 0,
            autocomplete_prefix: String::new(),
            current_activity: None,
            spinner_frame: 0,
            command_history: Vec::new(),
            history_cursor: None,
            history_draft: String::new(),
            execution_steps: Vec::new(),
            execution_failed: false,
        }
    }

    /// Advances the spinner. Called on a fixed timer from the render loop, independently of
    /// keypresses or agent updates, since those are the only other things that trigger a redraw.
    pub fn tick(&mut self) {
        self.spinner_frame = self.spinner_frame.wrapping_add(1);
    }

    fn push_history(&mut self, line: String) {
        // Skip immediate repeats so mashing Enter on the same command doesn't bury history in
        // duplicates of it.
        if self.command_history.last() != Some(&line) {
            self.command_history.push(line);
        }
        self.history_cursor = None;
    }

    /// Steps through `command_history`. `delta < 0` moves to older entries, `delta > 0` moves
    /// back toward the newest and, past it, restores whatever was being typed before recall
    /// started.
    fn recall_history(&mut self, delta: isize) {
        if self.command_history.is_empty() {
            return;
        }

        let next = match self.history_cursor {
            None if delta < 0 => {
                self.history_draft = self.input.clone();
                self.command_history.len() - 1
            }
            None => return,
            Some(i) => {
                let next = i as isize + delta;
                if next < 0 {
                    return;
                }
                if next as usize >= self.command_history.len() {
                    self.input = std::mem::take(&mut self.history_draft);
                    self.input_cursor = self.input_char_count();
                    self.history_cursor = None;
                    return;
                }
                next as usize
            }
        };

        self.input = self.command_history[next].clone();
        self.input_cursor = self.input_char_count();
        self.history_cursor = Some(next);
    }

    fn cursor_byte_offset(&self) -> usize {
        self.input
            .char_indices()
            .nth(self.input_cursor)
            .map(|(i, _)| i)
            .unwrap_or(self.input.len())
    }

    fn input_char_count(&self) -> usize {
        self.input.chars().count()
    }

    /// Derives autocomplete state fresh from `self.input`, so it self-corrects on every
    /// keystroke — including one that lands the cursor back inside a context that had earlier
    /// closed the popup (e.g. backspacing out of a provider name once no matches were left).
    fn sync_autocomplete(&mut self) {
        if !self.input.starts_with('/') {
            self.autocomplete_active = false;
            self.autocomplete_matches.clear();
            return;
        }
        self.autocomplete_matches = self.compute_autocomplete_matches();
        self.autocomplete_selected = 0;
        self.autocomplete_active = !self.autocomplete_matches.is_empty();
    }

    /// Suggestions for whatever is being typed right now: the command name up to the first
    /// space, and past that whichever argument the command expects there — providers, models, or
    /// `/model`'s own subcommands. Each is generated on the fly rather than read from a table, so
    /// providers and models stay in sync with `Provider::ALL`/`suggested_models` with nothing to
    /// duplicate or fall out of date.
    fn compute_autocomplete_matches(&self) -> Vec<AutocompleteItem> {
        if !self.input.contains(' ') {
            return Self::filter_candidates(
                SLASH_COMMANDS
                    .iter()
                    .map(|c| (c.name.to_string(), c.description.to_string())),
                &self.input,
            );
        }

        let tokens: Vec<&str> = self.input.split_whitespace().collect();
        let (fixed, partial) = if self.input.ends_with(' ') {
            (tokens.as_slice(), "")
        } else {
            (&tokens[..tokens.len() - 1], *tokens.last().unwrap())
        };
        let fixed: Vec<String> = fixed.iter().map(|t| t.to_lowercase()).collect();
        let fixed: Vec<&str> = fixed.iter().map(String::as_str).collect();

        let model_names = |provider: &str| -> Vec<(String, String)> {
            provider
                .parse::<Provider>()
                .ok()
                .into_iter()
                .flat_map(|p| p.suggested_models())
                .map(|m| (m.to_string(), String::new()))
                .collect()
        };

        let candidates: Vec<(String, String)> = match fixed.as_slice() {
            ["/model"] => vec![
                (
                    "status".to_string(),
                    "Show model status and suggestions".to_string(),
                ),
                ("set".to_string(), "Switch provider and model".to_string()),
                ("provider".to_string(), "Switch provider only".to_string()),
                ("model".to_string(), "Switch model only".to_string()),
            ],
            ["/model", "provider"] | ["/model", "set"] | ["/login"] | ["/logout"] => {
                Self::provider_candidates()
            }
            ["/model", "model"] => model_names(&self.active_provider),
            ["/model", "set", provider] => model_names(provider),
            ["/network"] => vec![
                ("local".to_string(), String::new()),
                ("testnet".to_string(), String::new()),
                ("mainnet".to_string(), String::new()),
            ],
            ["/install-stellar-build"] => vec![(
                "confirm".to_string(),
                "Actually run the third-party installer".to_string(),
            )],
            _ => Vec::new(),
        };
        Self::filter_candidates(candidates.into_iter(), partial)
    }

    fn provider_candidates() -> Vec<(String, String)> {
        Provider::ALL
            .iter()
            .map(|p| {
                let hint = if p.is_local() {
                    "local, no credential needed"
                } else {
                    ""
                };
                (p.to_string(), hint.to_string())
            })
            .collect()
    }

    fn filter_candidates(
        candidates: impl Iterator<Item = (String, String)>,
        partial: &str,
    ) -> Vec<AutocompleteItem> {
        let partial = partial.to_lowercase();
        candidates
            .filter(|(value, _)| value.to_lowercase().starts_with(&partial))
            .map(|(value, description)| AutocompleteItem { value, description })
            .collect()
    }

    /// Moves the highlight by `delta`, wrapping at both ends.
    fn move_autocomplete_selection(&mut self, delta: isize) {
        let len = self.autocomplete_matches.len();
        if len == 0 {
            return;
        }
        let len_i = len as isize;
        let next = (self.autocomplete_selected as isize + delta).rem_euclid(len_i);
        self.autocomplete_selected = next as usize;
    }

    fn accept_autocomplete(&mut self) {
        if let Some(item) = self.autocomplete_matches.get(self.autocomplete_selected) {
            let value = item.value.clone();
            // Completing a command name (no space typed yet) replaces the whole line; completing
            // an argument replaces only the token in progress and leaves a trailing space, ready
            // for the next one.
            if self.input.contains(' ') {
                let base = self.input.rfind(' ').map(|i| i + 1).unwrap_or(0);
                self.input.truncate(base);
                self.input.push_str(&value);
                self.input.push(' ');
            } else {
                self.input = value;
            }
            self.input_cursor = self.input.chars().count();
        }
        self.autocomplete_active = false;
        self.autocomplete_matches.clear();
    }

    fn cancel_autocomplete(&mut self) {
        self.input = self.autocomplete_prefix.clone();
        self.input_cursor = self.input.chars().count();
        self.autocomplete_active = false;
        self.autocomplete_matches.clear();
    }

    // Only a test fixture now: real suggestion lookups go through `compute_autocomplete_matches`,
    // which reads `SLASH_COMMANDS` directly. `#[cfg(test)]` keeps it from being dead code in a
    // normal build now that ui.rs's tests are its only caller.
    #[cfg(test)]
    pub fn slash_commands() -> &'static [SlashCommand] {
        SLASH_COMMANDS
    }

    // `chat_scroll` is the first visible line, anchored at the top: a reader who scrolled back
    // stays on the same content as new messages arrive. `chat_follow` re-pins to the newest line,
    // and is what makes an idle chat auto-scroll.
    pub fn scroll_back(&mut self, lines: usize) {
        self.chat_follow = false;
        self.chat_scroll = self.chat_scroll.saturating_sub(lines);
    }

    pub fn scroll_forward(&mut self, lines: usize) {
        self.chat_scroll = self.chat_scroll.saturating_add(lines);
    }

    // Only the renderer knows the wrapped line count and viewport, so it resolves the final
    // offset and decides whether we are back at the bottom.
    pub fn resolve_scroll(&mut self, max_scroll: usize) -> usize {
        if self.chat_follow || self.chat_scroll >= max_scroll {
            self.chat_follow = true;
            self.chat_scroll = max_scroll;
        }
        self.chat_scroll
    }

    pub fn is_following_chat(&self) -> bool {
        self.chat_follow
    }

    pub fn is_explaining(&self) -> bool {
        self.explain_mode
    }

    // ---- Palette helpers ----
    fn palette_sync(&mut self) {
        let query = self.palette_input.trim().to_lowercase();
        let mut items: Vec<AutocompleteItem> = Vec::new();
        // Slash commands
        for cmd in SLASH_COMMANDS {
            if query.is_empty()
                || cmd.name.to_lowercase().contains(&query)
                || cmd.description.to_lowercase().contains(&query)
            {
                items.push(AutocompleteItem {
                    value: cmd.name.to_string(),
                    description: cmd.description.to_string(),
                });
            }
        }
        // Quick actions as palette entries
        let actions = [
            ("/build", "Build the project (Ctrl+B)"),
            ("/test", "Run tests (Ctrl+T)"),
            ("/deploy", "Deploy contract (Ctrl+D)"),
            ("/doctor", "Check environment / Caatinga doctor"),
        ];
        for (name, desc) in actions {
            if query.is_empty() || name.contains(&query) || desc.to_lowercase().contains(&query) {
                items.push(AutocompleteItem {
                    value: name.to_string(),
                    description: desc.to_string(),
                });
            }
        }
        self.palette_matches = items;
        if self.palette_selected >= self.palette_matches.len() {
            self.palette_selected = 0;
        }
    }

    pub fn palette_open(&mut self) {
        self.palette_open = true;
        self.palette_input.clear();
        self.palette_cursor = 0;
        self.palette_selected = 0;
        self.palette_sync();
    }

    pub fn palette_close(&mut self) {
        self.palette_open = false;
        self.palette_input.clear();
        self.palette_matches.clear();
        self.palette_selected = 0;
    }

    fn palette_cursor_byte(&self) -> usize {
        self.palette_input
            .char_indices()
            .nth(self.palette_cursor)
            .map(|(i, _)| i)
            .unwrap_or(self.palette_input.len())
    }

    fn palette_handle_key(
        &mut self,
        key: crossterm::event::KeyEvent,
        user_tx: &mpsc::UnboundedSender<UserCommand>,
    ) -> bool {
        match (key.modifiers, key.code) {
            // Quit has to outrank the overlay. The palette swallows every other key, so without
            // this arm Ctrl+C did nothing while it was open and the only way out was Esc first —
            // an overlay that can trap you is worse than no overlay.
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => return true,
            (KeyModifiers::NONE, KeyCode::Esc) => {
                self.palette_close();
            }
            (KeyModifiers::NONE, KeyCode::Enter) => {
                if let Some(item) = self.palette_matches.get(self.palette_selected).cloned() {
                    self.palette_close();
                    if item.value.starts_with('/') {
                        // Map quick actions to prompts, real slash commands to handle_command
                        match item.value.as_str() {
                            "/build" => {
                                self.messages
                                    .push(ChatMessage::System("Building project...".to_string()));
                                let _ = user_tx
                                    .send(UserCommand::SendPrompt("build the project".to_string()));
                            }
                            "/test" => {
                                self.messages
                                    .push(ChatMessage::System("Running tests...".to_string()));
                                let _ =
                                    user_tx.send(UserCommand::SendPrompt("run tests".to_string()));
                            }
                            "/deploy" => {
                                self.messages
                                    .push(ChatMessage::System("Deploying contract...".to_string()));
                                let _ = user_tx.send(UserCommand::SendPrompt(
                                    "deploy the current contract".to_string(),
                                ));
                            }
                            "/doctor" => {
                                let _ = user_tx.send(UserCommand::SendPrompt(
                                    "run caatinga doctor and summarize the results".to_string(),
                                ));
                            }
                            _ => self.handle_command(&item.value, user_tx),
                        }
                    }
                } else {
                    self.palette_close();
                }
            }
            (KeyModifiers::NONE, KeyCode::Up) => {
                if !self.palette_matches.is_empty() {
                    let len = self.palette_matches.len() as isize;
                    self.palette_selected =
                        (self.palette_selected as isize - 1).rem_euclid(len) as usize;
                }
            }
            (KeyModifiers::NONE, KeyCode::Down) | (KeyModifiers::NONE, KeyCode::Tab) => {
                if !self.palette_matches.is_empty() {
                    let len = self.palette_matches.len() as isize;
                    self.palette_selected =
                        (self.palette_selected as isize + 1).rem_euclid(len) as usize;
                }
            }
            (KeyModifiers::NONE, KeyCode::BackTab) | (KeyModifiers::SHIFT, KeyCode::BackTab) => {
                if !self.palette_matches.is_empty() {
                    let len = self.palette_matches.len() as isize;
                    self.palette_selected =
                        (self.palette_selected as isize - 1).rem_euclid(len) as usize;
                }
            }
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(c)) => {
                let at = self.palette_cursor_byte();
                self.palette_input.insert(at, c);
                self.palette_cursor += 1;
                self.palette_sync();
            }
            (KeyModifiers::NONE, KeyCode::Backspace) => {
                if self.palette_cursor > 0 {
                    self.palette_cursor -= 1;
                    let at = self.palette_cursor_byte();
                    self.palette_input.remove(at);
                    self.palette_sync();
                }
            }
            (KeyModifiers::NONE, KeyCode::Delete) => {
                if self.palette_cursor < self.palette_input.chars().count() {
                    let at = self.palette_cursor_byte();
                    self.palette_input.remove(at);
                    self.palette_sync();
                }
            }
            (KeyModifiers::NONE, KeyCode::Left) => {
                if self.palette_cursor > 0 {
                    self.palette_cursor -= 1;
                }
            }
            (KeyModifiers::NONE, KeyCode::Right) => {
                if self.palette_cursor < self.palette_input.chars().count() {
                    self.palette_cursor += 1;
                }
            }
            (KeyModifiers::NONE, KeyCode::Home) | (KeyModifiers::CONTROL, KeyCode::Char('a')) => {
                self.palette_cursor = 0;
            }
            (KeyModifiers::NONE, KeyCode::End) | (KeyModifiers::CONTROL, KeyCode::Char('e')) => {
                self.palette_cursor = self.palette_input.chars().count();
            }
            _ => {}
        }
        false
    }

    pub fn handle_key(
        &mut self,
        key: crossterm::event::KeyEvent,
        user_tx: &mpsc::UnboundedSender<UserCommand>,
    ) -> bool {
        if key.kind != KeyEventKind::Press {
            return false;
        }

        // Palette overlay captures all keys first.
        if self.palette_open {
            return self.palette_handle_key(key, user_tx);
        }

        match (key.modifiers, key.code) {
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => return true,
            (KeyModifiers::CONTROL, KeyCode::Char('k')) => {
                self.palette_open();
            }
            (KeyModifiers::CONTROL, KeyCode::Char('d')) => {
                self.clear_execution();
                self.messages
                    .push(ChatMessage::System("Deploying contract...".to_string()));
                let _ = user_tx.send(UserCommand::SendPrompt(
                    "deploy the current contract".to_string(),
                ));
            }
            (KeyModifiers::CONTROL, KeyCode::Char('t')) => {
                self.clear_execution();
                self.messages
                    .push(ChatMessage::System("Running tests...".to_string()));
                let _ = user_tx.send(UserCommand::SendPrompt("run tests".to_string()));
            }
            (KeyModifiers::CONTROL, KeyCode::Char('b')) => {
                self.clear_execution();
                self.messages
                    .push(ChatMessage::System("Building project...".to_string()));
                let _ = user_tx.send(UserCommand::SendPrompt("build the project".to_string()));
            }
            // Autocomplete navigation: Tab / Shift+Tab, and the arrow keys, which is where a hand
            // reaches first. Down/Up have to be matched here so the chat scroll arms below do not
            // swallow them while the popup is open.
            (KeyModifiers::NONE, KeyCode::Tab | KeyCode::Down) if self.autocomplete_active => {
                self.move_autocomplete_selection(1);
            }
            (KeyModifiers::NONE, KeyCode::BackTab | KeyCode::Up)
            | (KeyModifiers::SHIFT, KeyCode::BackTab)
                if self.autocomplete_active =>
            {
                self.move_autocomplete_selection(-1);
            }
            // Accept the highlighted suggestion — unless what's typed already matches it exactly,
            // in which case accepting would be a no-op and the user almost certainly means to
            // submit (e.g. having typed "/model set anthropic" character by character until it
            // stopped changing). Without this, Enter on an exact match would silently do nothing
            // and need a second press.
            (KeyModifiers::NONE, KeyCode::Enter) if self.autocomplete_active => {
                let already_typed = self
                    .autocomplete_matches
                    .get(self.autocomplete_selected)
                    .is_some_and(|item| {
                        let current_token = if self.input.ends_with(' ') {
                            ""
                        } else {
                            self.input.rsplit(' ').next().unwrap_or(&self.input)
                        };
                        current_token.eq_ignore_ascii_case(&item.value)
                    });
                if already_typed {
                    let msg = self.input.trim().to_string();
                    self.handle_command(&msg, user_tx);
                    self.input.clear();
                    self.input_cursor = 0;
                    self.autocomplete_active = false;
                    self.autocomplete_matches.clear();
                } else {
                    self.accept_autocomplete();
                }
            }
            // Cancel autocomplete
            (KeyModifiers::NONE, KeyCode::Esc) if self.autocomplete_active => {
                self.cancel_autocomplete();
            }
            (KeyModifiers::NONE, KeyCode::Enter) => {
                if !self.input.trim().is_empty() {
                    let msg = self.input.trim().to_string();
                    self.push_history(msg.clone());
                    // New user intent starts a fresh execution story.
                    self.clear_execution();

                    if msg.starts_with('/') {
                        self.handle_command(&msg, user_tx);
                    } else {
                        self.messages.push(ChatMessage::User(msg.clone()));
                        let _ = user_tx.send(UserCommand::SendPrompt(msg));
                    }

                    self.input.clear();
                    self.input_cursor = 0;
                    self.autocomplete_active = false;
                    self.autocomplete_matches.clear();
                }
            }
            // With the Help panel gone, `?` on an empty prompt is how you find the shortcuts.
            // Only when empty — mid-sentence a question mark has to stay a question mark.
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char('?'))
                if self.input.is_empty() =>
            {
                self.handle_command("/help", user_tx);
            }
            (KeyModifiers::ALT, KeyCode::Up) => self.recall_history(-1),
            (KeyModifiers::ALT, KeyCode::Down) => self.recall_history(1),
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(c)) => {
                self.history_cursor = None;
                let at = self.cursor_byte_offset();
                self.input.insert(at, c);
                self.input_cursor += 1;

                // Captured once, at the moment autocomplete opens, purely for Esc to revert to:
                // suggestions themselves are recomputed from scratch below on every keystroke.
                if c == '/' && self.input_cursor == 1 {
                    self.autocomplete_prefix = self.input.clone();
                }
                self.sync_autocomplete();
            }
            (KeyModifiers::NONE, KeyCode::Backspace) => {
                if self.input_cursor > 0 {
                    self.history_cursor = None;
                    self.input_cursor -= 1;
                    let at = self.cursor_byte_offset();
                    self.input.remove(at);
                    self.sync_autocomplete();
                }
            }
            (KeyModifiers::NONE, KeyCode::Delete) => {
                if self.input_cursor < self.input_char_count() {
                    self.history_cursor = None;
                    let at = self.cursor_byte_offset();
                    self.input.remove(at);
                    self.sync_autocomplete();
                }
            }
            (KeyModifiers::NONE, KeyCode::Left) => {
                if self.input_cursor > 0 {
                    self.input_cursor -= 1;
                }
            }
            (KeyModifiers::NONE, KeyCode::Right) => {
                if self.input_cursor < self.input_char_count() {
                    self.input_cursor += 1;
                }
            }
            (KeyModifiers::NONE, KeyCode::Home) | (KeyModifiers::CONTROL, KeyCode::Char('a')) => {
                self.input_cursor = 0;
            }
            (KeyModifiers::NONE, KeyCode::End) | (KeyModifiers::CONTROL, KeyCode::Char('e')) => {
                self.input_cursor = self.input_char_count();
            }
            (KeyModifiers::NONE, KeyCode::Up) => self.scroll_back(1),
            (KeyModifiers::NONE, KeyCode::Down) => self.scroll_forward(1),
            (KeyModifiers::NONE, KeyCode::PageUp) => self.scroll_back(10),
            (KeyModifiers::NONE, KeyCode::PageDown) => self.scroll_forward(10),
            _ => {}
        }
        false
    }

    /// Asks the agent to switch, and says so plainly if the agent is not there to hear it.
    ///
    /// The send result used to be discarded everywhere, so once the agent task had exited the UI
    /// went on reporting switches that reached nobody.
    fn request_switch(
        &mut self,
        user_tx: &mpsc::UnboundedSender<UserCommand>,
        provider: Provider,
        model: String,
    ) {
        if user_tx
            .send(UserCommand::SwitchModel { provider, model })
            .is_err()
        {
            self.messages.push(ChatMessage::System(
                "The agent is no longer running, so the model cannot be switched. Restart Procyon."
                    .to_string(),
            ));
        }
    }

    fn open_credential_store(&self) -> color_eyre::Result<CredentialStore> {
        match &self.credentials_path {
            Some(path) => CredentialStore::load(path.clone()),
            None => CredentialStore::load_default(),
        }
    }

    fn handle_command(&mut self, cmd: &str, user_tx: &mpsc::UnboundedSender<UserCommand>) {
        let parts: Vec<&str> = cmd.split_whitespace().collect();
        let command = parts[0];

        match command {
            "/help" => {
                self.messages.push(ChatMessage::System(
                    "Available commands:\n\
                     /help                    - Show this help\n\
                     /clear                   - Clear chat history\n\
                     /status                  - Show connection status\n\
                     /project                 - Show project info\n\
                     /network <net>           - Switch network (local/testnet/mainnet)\n\
                     /explain                 - Toggle explain mode\n\
                     /model                   - Show model status and suggestions\n\
                     /model set <prov> <mdl>  - Switch provider and model\n\
                     /model provider <name>   - Switch provider only\n\
                     /model model <name>      - Switch model only\n\
                     /login <prov> <key>      - Save an API key for a provider\n\
                     /logout <prov>           - Remove a stored API key\n\
                     /providers               - Show credential status for every provider\n\
                     /install-stellar-build   - Install the Stellar Build persona pack \
                     (third-party)\n\
                     \n\
                     Quick actions:\n\
                     Ctrl+B         - Build project\n\
                     Ctrl+T         - Run tests\n\
                     Ctrl+D         - Deploy contract\n\
                     \n\
                     Keyboard shortcuts:\n\
                     Ctrl+K         - Command palette\n\
                     Ctrl+C         - Quit\n\
                     ?              - This help (on an empty prompt)\n\
                     Up/Down        - Scroll chat\n\
                     Alt+Up/Down    - Command history"
                        .to_string(),
                ));
            }
            "/clear" => {
                self.messages.clear();
                self.messages
                    .push(ChatMessage::System("Chat cleared.".to_string()));
            }
            // The status line only has room for network, model and the current phase, so this is
            // where the rest of the old Context panel lives now: account, contract, explain mode
            // and the MCP servers.
            "/status" => {
                let mut out = format!(
                    "Status: {}\nProject: {}\nNetwork: {}\nAccount: {}\nContract: {}\n\
                     Provider: {} / {}\nExplain: {}",
                    status_label(&self.status),
                    self.project_name,
                    self.active_network,
                    self.active_account,
                    self.active_contract.as_deref().unwrap_or(""),
                    self.active_provider,
                    self.active_model,
                    if self.is_explaining() { "on" } else { "off" },
                );
                // The label carries a value on its own line rather than heading an indented list
                // that may hold exactly one entry — "MCP:" alone above a single server reads as a
                // heading someone forgot to fill in. One server sits inline; several announce
                // their count first, which is the part worth scanning.
                let mcp = |srv: &crate::channels::McpServerStatus| {
                    format!(
                        "{} {} {}",
                        if srv.connected { "" } else { "" },
                        srv.name,
                        srv.detail
                    )
                };
                match self.mcp_servers.as_slice() {
                    [] => out.push_str("\nMCP: none"),
                    [only] => out.push_str(&format!("\nMCP: {}", mcp(only))),
                    many => {
                        let connected = many.iter().filter(|s| s.connected).count();
                        out.push_str(&format!(
                            "\nMCP: {} servers, {} connected",
                            many.len(),
                            connected
                        ));
                        for srv in many {
                            out.push_str(&format!("\n  {}", mcp(srv)));
                        }
                    }
                }
                self.messages.push(ChatMessage::System(out));
            }
            "/project" => {
                self.messages.push(ChatMessage::System(format!(
                    "Project: {}\nNetwork: {}",
                    self.project_name, self.active_network
                )));
            }
            "/explain" => {
                self.explain_mode = !self.explain_mode;
                let _ = user_tx.send(UserCommand::SetExplain(self.explain_mode));
                self.messages.push(ChatMessage::System(
                    if self.explain_mode {
                        "Explain mode on: the agent will narrate each step it takes."
                    } else {
                        "Explain mode off."
                    }
                    .to_string(),
                ));
            }
            "/network" => {
                if let Some(network) = parts.get(1) {
                    match *network {
                        "local" | "testnet" | "mainnet" => {
                            self.active_network = network.to_string();
                            self.messages.push(ChatMessage::System(format!(
                                "Network switched to {}",
                                network
                            )));
                        }
                        _ => {
                            self.messages.push(ChatMessage::System(
                                "Invalid network. Use: local, testnet, or mainnet".to_string(),
                            ));
                        }
                    }
                } else {
                    self.messages.push(ChatMessage::System(format!(
                        "Current network: {}",
                        self.active_network
                    )));
                }
            }
            "/model" => {
                let sub = parts.get(1).copied();
                match sub {
                    None | Some("status") => {
                        let provider: Provider =
                            self.active_provider.parse().unwrap_or(Provider::Anthropic);
                        let mut msg = format!(
                            "Provider: {}\nModel: {}\n\nAvailable models:",
                            self.active_provider, self.active_model
                        );
                        for model in provider.suggested_models() {
                            msg.push_str(&format!("\n  {}", model));
                        }
                        self.messages.push(ChatMessage::System(msg));
                    }
                    Some("set") => {
                        let provider_str = parts.get(2);
                        let model_str = parts.get(3);
                        match (provider_str, model_str) {
                            (Some(p), Some(m)) => match p.parse::<Provider>() {
                                Ok(provider) => {
                                    // No optimistic bookkeeping: the agent confirms with a `Ready`
                                    // update, so a switch that was rejected — or that reached a
                                    // dead channel — cannot leave the header describing a client
                                    // nobody built.
                                    self.request_switch(user_tx, provider, m.to_string());
                                }
                                Err(e) => {
                                    self.messages.push(ChatMessage::System(e));
                                }
                            },
                            _ => {
                                self.messages.push(ChatMessage::System(
                                    "Usage: /model set <provider> <model>".to_string(),
                                ));
                            }
                        }
                    }
                    Some("provider") => match parts.get(2) {
                        Some(p) => match p.parse::<Provider>() {
                            Ok(provider) => {
                                // Carrying the old model across a provider switch produced pairs
                                // no endpoint serves — `ollama` still asking for
                                // `claude-sonnet-5`. It is kept only when the new provider offers
                                // it.
                                let model = if provider
                                    .suggested_models()
                                    .contains(&self.active_model.as_str())
                                {
                                    self.active_model.clone()
                                } else {
                                    provider.default_model().to_string()
                                };
                                if model.is_empty() {
                                    self.messages.push(ChatMessage::System(format!(
                                        "{} serves no model this build can name. Use `/model set \
                                         {} <model>`.",
                                        p, p
                                    )));
                                } else {
                                    self.request_switch(user_tx, provider, model);
                                }
                            }
                            Err(e) => {
                                self.messages.push(ChatMessage::System(e));
                            }
                        },
                        None => {
                            self.messages.push(ChatMessage::System(
                                "Usage: /model provider <name>".to_string(),
                            ));
                        }
                    },
                    Some("model") => match parts.get(2) {
                        Some(m) => {
                            let provider =
                                self.active_provider.parse().unwrap_or(Provider::Anthropic);
                            self.request_switch(user_tx, provider, m.to_string());
                        }
                        None => {
                            self.messages.push(ChatMessage::System(
                                "Usage: /model model <name>".to_string(),
                            ));
                        }
                    },
                    Some(unknown) => {
                        self.messages.push(ChatMessage::System(format!(
                            "Unknown subcommand: {}. Use: status, set, provider, model",
                            unknown
                        )));
                    }
                }
            }
            "/login" => {
                match (parts.get(1), parts.get(2)) {
                    (Some(p), Some(_)) => match p.parse::<Provider>() {
                        Ok(provider) => match self.open_credential_store() {
                            // The key itself never touches `self.messages`: it must not linger in
                            // the chat history that gets rendered and scrolled.
                            Ok(mut store) => {
                                // Joined rather than `parts[2]` alone: a key with an internal or
                                // trailing space (common after a clipboard paste) used to be
                                // silently truncated at the first token instead of stored whole.
                                let key = parts[2..].join(" ");
                                match store.set(&provider.to_string(), key) {
                                    Ok(()) => {
                                        self.messages.push(ChatMessage::System(format!(
                                            "Saved credential for {}.",
                                            provider
                                        )));
                                        if provider.to_string() == self.active_provider {
                                            self.request_switch(
                                                user_tx,
                                                provider,
                                                self.active_model.clone(),
                                            );
                                        } else {
                                            self.messages.push(ChatMessage::System(format!(
                                                "Run `/model provider {}` to switch to it.",
                                                provider
                                            )));
                                        }
                                    }
                                    Err(e) => {
                                        self.messages.push(ChatMessage::System(format!(
                                            "Failed to save credential: {}",
                                            e
                                        )));
                                    }
                                }
                            }
                            Err(e) => {
                                self.messages.push(ChatMessage::System(format!(
                                    "Failed to open credential store: {}",
                                    e
                                )));
                            }
                        },
                        Err(e) => {
                            self.messages.push(ChatMessage::System(e));
                        }
                    },
                    _ => {
                        self.messages.push(ChatMessage::System(
                            "Usage: /login <provider> <key>".to_string(),
                        ));
                    }
                }
            }
            "/logout" => match parts.get(1) {
                Some(p) => match p.parse::<Provider>() {
                    Ok(provider) => match self.open_credential_store() {
                        Ok(mut store) => match store.remove(&provider.to_string()) {
                            Ok(true) => {
                                self.messages.push(ChatMessage::System(format!(
                                    "Removed stored credential for {}.",
                                    provider
                                )));
                            }
                            Ok(false) => {
                                self.messages.push(ChatMessage::System(format!(
                                    "No stored credential for {}.",
                                    provider
                                )));
                            }
                            Err(e) => {
                                self.messages.push(ChatMessage::System(format!(
                                    "Failed to remove credential: {}",
                                    e
                                )));
                            }
                        },
                        Err(e) => {
                            self.messages.push(ChatMessage::System(format!(
                                "Failed to open credential store: {}",
                                e
                            )));
                        }
                    },
                    Err(e) => {
                        self.messages.push(ChatMessage::System(e));
                    }
                },
                None => {
                    self.messages
                        .push(ChatMessage::System("Usage: /logout <provider>".to_string()));
                }
            },
            "/providers" => {
                let store = self.open_credential_store().ok();
                let with_keys: std::collections::HashSet<&str> = store
                    .as_ref()
                    .map(|s| s.providers_with_keys().collect())
                    .unwrap_or_default();
                let mut msg = String::from("Provider credentials:");
                for provider in Provider::ALL {
                    let name = provider.to_string();
                    let stored = with_keys.contains(name.as_str());
                    let has_env = std::env::var(provider.default_key_env())
                        .ok()
                        .filter(|k| !k.is_empty())
                        .is_some();
                    let status = if provider.is_local() {
                        "local, no credential needed"
                    } else if stored {
                        "stored"
                    } else if has_env {
                        "env var set"
                    } else {
                        "missing"
                    };
                    msg.push_str(&format!("\n  {:<12} {}", name, status));
                }
                self.messages.push(ChatMessage::System(msg));
            }
            "/install-stellar-build" => {
                if parts.get(1).copied() == Some("confirm") {
                    if user_tx.send(UserCommand::InstallStellarBuild).is_err() {
                        self.messages.push(ChatMessage::System(
                            "The agent is no longer running, so Stellar Build cannot be \
                             installed. Restart Procyon."
                                .to_string(),
                        ));
                    }
                } else {
                    // Downloads and runs a shell script on the user's machine: this is not
                    // something to do on a bare `/install-stellar-build`, only once they've seen
                    // exactly what that means and typed the command again to mean it.
                    self.messages.push(ChatMessage::System(format!(
                        "This downloads and runs a shell script from a third party (not \
                         maintained by Procyon):\n  {}\n\nIt installs the Stellar Build persona \
                         pack (Justin, Nicole, Kaan, Tyler, Elliot, Bri) that `talk_to` and \
                         `party_mode` use. Unix/macOS only.\n\nRun `/install-stellar-build \
                         confirm` to proceed.",
                        crate::channels::STELLAR_BUILD_INSTALL_URL
                    )));
                }
            }
            _ => {
                self.messages.push(ChatMessage::System(format!(
                    "Unknown command: {}. Type /help for available commands.",
                    command
                )));
            }
        }
    }

    pub fn handle_agent_update(&mut self, update: AgentUpdate) {
        match update {
            AgentUpdate::ResponseChunk(text) => {
                if !self.agent_streaming {
                    self.messages.push(ChatMessage::Agent(String::new()));
                    self.agent_streaming = true;
                }
                if let Some(ChatMessage::Agent(buf)) = self.messages.last_mut() {
                    buf.push_str(&text);
                }
                // Text is now arriving, so whatever activity line was shown ("Thinking...")
                // no longer describes what's happening.
                self.current_activity = None;
                // Previous step (if any) completed when text starts flowing.
                if let Some(last) = self.execution_steps.last_mut() {
                    if last.state == ExecutionStepState::Running {
                        last.state = ExecutionStepState::Done;
                    }
                }
                self.status = AppStatus::Working;
            }
            AgentUpdate::ResponseEnd => {
                self.end_stream();
                // Finalise any running step
                for step in &mut self.execution_steps {
                    if step.state == ExecutionStepState::Running {
                        step.state = if self.execution_failed {
                            ExecutionStepState::Failed
                        } else {
                            ExecutionStepState::Done
                        };
                    }
                }
                self.settle();
                // Keep trace visible briefly — clear on next user prompt instead of immediately,
                // so success/failure checkmarks remain readable. For tests, clearing here keeps
                // old assertions (messages count) stable; execution block is additive.
            }
            AgentUpdate::Status(text) => {
                self.end_stream();
                self.current_activity = Some(text.clone());
                // Mark previous running step as done before starting new one
                if let Some(last) = self.execution_steps.last_mut() {
                    if last.state == ExecutionStepState::Running {
                        last.state = ExecutionStepState::Done;
                    }
                }
                self.execution_steps.push(ExecutionStep {
                    label: text.clone(),
                    state: ExecutionStepState::Running,
                });
                self.messages.push(ChatMessage::Event(text));
                self.status = AppStatus::Working;
            }
            AgentUpdate::Notice(text) => {
                self.messages.push(ChatMessage::System(text));
            }
            AgentUpdate::Error(text) => {
                self.end_stream();
                self.execution_failed = true;
                for step in &mut self.execution_steps {
                    if step.state == ExecutionStepState::Running {
                        step.state = ExecutionStepState::Failed;
                    }
                }
                self.messages
                    .push(ChatMessage::System(format!("Error: {}", text)));
                // A failed turn says nothing about whether the next one can be sent, so the header
                // returns to rest instead of latching. Only a `Ready` update moves the credential
                // state.
                self.settle();
            }
            AgentUpdate::Ready {
                provider,
                model,
                credential,
            } => {
                self.active_provider = provider;
                self.active_model = model;
                self.has_credential = credential;
                self.settle();
            }
            AgentUpdate::Workspace(snap) => {
                self.project_name = snap.project_name;
                self.active_network = snap.network;
                self.active_account = snap.account;
                self.active_contract = snap.contract_name;
                // Keep MCP in sync if workspace carries it (first paint after boot)
                if !snap.mcp_servers.is_empty() {
                    self.mcp_servers = snap.mcp_servers;
                }
            }
            AgentUpdate::McpStatus(servers) => {
                self.mcp_servers = servers;
            }
        }
    }

    // Returns to whichever resting state the credential allows.
    fn settle(&mut self) {
        self.current_activity = None;
        self.status = if self.has_credential {
            AppStatus::Ready
        } else {
            AppStatus::NeedsCredential
        };
    }

    /// Clears the execution trace — called when a new user prompt starts, so the block
    /// does not bleed into the next turn's story.
    pub fn clear_execution(&mut self) {
        self.execution_steps.clear();
        self.execution_failed = false;
    }

    fn end_stream(&mut self) {
        if !self.agent_streaming {
            return;
        }
        self.agent_streaming = false;
        if matches!(self.messages.last(), Some(ChatMessage::Agent(t)) if t.is_empty()) {
            self.messages.pop();
        }
    }
}

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

    fn press(state: &mut AppState, code: KeyCode, modifiers: KeyModifiers) {
        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_key(KeyEvent::new(code, modifiers), &tx);
    }

    fn type_str(state: &mut AppState, text: &str) {
        for c in text.chars() {
            let modifiers = if c.is_uppercase() {
                KeyModifiers::SHIFT
            } else {
                KeyModifiers::NONE
            };
            press(state, KeyCode::Char(c), modifiers);
        }
    }

    #[test]
    fn types_multibyte_text_without_panicking() {
        let mut state = AppState::new();
        type_str(&mut state, "ação corrigida");
        assert_eq!(state.input, "ação corrigida");
        assert_eq!(state.input_cursor, 14);
    }

    #[test]
    fn types_uppercase_characters() {
        let mut state = AppState::new();
        type_str(&mut state, "Deploy");
        assert_eq!(state.input, "Deploy");
    }

    #[test]
    fn backspace_removes_whole_multibyte_char() {
        let mut state = AppState::new();
        type_str(&mut state, "ação");
        press(&mut state, KeyCode::Backspace, KeyModifiers::NONE);
        assert_eq!(state.input, "açã");
        assert_eq!(state.input_cursor, 3);

        press(&mut state, KeyCode::Backspace, KeyModifiers::NONE);
        assert_eq!(state.input, "");
        assert_eq!(state.input_cursor, 2);
    }

    #[test]
    fn inserts_at_cursor_inside_multibyte_text() {
        let mut state = AppState::new();
        type_str(&mut state, "ção");
        press(&mut state, KeyCode::Home, KeyModifiers::NONE);
        type_str(&mut state, "a");
        assert_eq!(state.input, "ação");
    }

    #[test]
    fn delete_at_end_of_multibyte_text_is_noop() {
        let mut state = AppState::new();
        type_str(&mut state, "ç");
        press(&mut state, KeyCode::Delete, KeyModifiers::NONE);
        assert_eq!(state.input, "ç");
    }

    #[test]
    fn streaming_chunks_accumulate_into_one_message() {
        let mut state = AppState::new();
        let before = state.messages.len();

        for chunk in ["Olá", ", ", "mundo"] {
            state.handle_agent_update(AgentUpdate::ResponseChunk(chunk.to_string()));
        }
        state.handle_agent_update(AgentUpdate::ResponseEnd);

        assert_eq!(state.messages.len(), before + 1);
        assert!(
            matches!(state.messages.last(), Some(ChatMessage::Agent(t)) if t == "Olá, mundo"),
            "got {:?}",
            state.messages.last()
        );
    }

    #[test]
    fn status_between_chunks_splits_agent_messages() {
        let mut state = AppState::new();
        state.messages.clear();

        state.handle_agent_update(AgentUpdate::ResponseChunk("antes".to_string()));
        state.handle_agent_update(AgentUpdate::Status("Using tool: build".to_string()));
        state.handle_agent_update(AgentUpdate::ResponseChunk("depois".to_string()));
        state.handle_agent_update(AgentUpdate::ResponseEnd);

        let rendered: Vec<_> = state
            .messages
            .iter()
            .map(|m| match m {
                ChatMessage::User(t)
                | ChatMessage::Agent(t)
                | ChatMessage::System(t)
                | ChatMessage::Event(t) => t.as_str(),
            })
            .collect();
        assert_eq!(rendered, vec!["antes", "Using tool: build", "depois"]);
    }

    #[test]
    fn stream_with_no_text_leaves_no_empty_message() {
        let mut state = AppState::new();
        let before = state.messages.len();
        state.handle_agent_update(AgentUpdate::ResponseEnd);
        assert_eq!(state.messages.len(), before);
    }

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

        assert!(matches!(state.messages.last(), Some(ChatMessage::Event(t)) if t == "Thinking..."));
        assert_eq!(state.current_activity.as_deref(), Some("Thinking..."));
        assert_eq!(state.status, AppStatus::Working);
    }

    #[test]
    fn current_activity_clears_once_text_starts_streaming() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Using tool: build".to_string()));
        state.handle_agent_update(AgentUpdate::ResponseChunk("hi".to_string()));

        assert_eq!(state.current_activity, None);
    }

    #[test]
    fn current_activity_clears_when_the_turn_settles() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Thinking...".to_string()));
        state.handle_agent_update(AgentUpdate::ResponseEnd);

        assert_eq!(state.current_activity, None);
        assert_eq!(state.status, AppStatus::Ready);
    }

    #[test]
    fn current_activity_clears_on_error_too() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Thinking...".to_string()));
        state.handle_agent_update(AgentUpdate::Error("boom".to_string()));

        assert_eq!(state.current_activity, None);
    }

    #[test]
    fn tick_advances_the_spinner_frame() {
        let mut state = AppState::new();
        let before = state.spinner_frame;
        state.tick();
        assert_eq!(state.spinner_frame, before + 1);
    }

    fn submit(state: &mut AppState, text: &str) -> mpsc::UnboundedReceiver<UserCommand> {
        let (tx, rx) = mpsc::unbounded_channel();
        for c in text.chars() {
            state.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE), &tx);
        }
        state.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), &tx);
        rx
    }

    fn last_system_message(state: &AppState) -> String {
        match state.messages.last() {
            Some(ChatMessage::System(t)) => t.clone(),
            other => panic!("expected a system message, got {:?}", other),
        }
    }

    #[test]
    fn alt_up_recalls_the_previous_submission() {
        let mut state = AppState::new();
        submit(&mut state, "first prompt");
        submit(&mut state, "second prompt");

        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "second prompt");

        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "first prompt");
    }

    #[test]
    fn alt_up_stops_at_the_oldest_entry() {
        let mut state = AppState::new();
        submit(&mut state, "only prompt");

        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "only prompt");
    }

    #[test]
    fn alt_down_past_the_newest_entry_restores_the_in_progress_draft() {
        let mut state = AppState::new();
        submit(&mut state, "old prompt");
        type_str(&mut state, "still typing");

        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "old prompt");

        press(&mut state, KeyCode::Down, KeyModifiers::ALT);
        assert_eq!(state.input, "still typing");
    }

    #[test]
    fn typing_during_recall_resets_history_navigation() {
        let mut state = AppState::new();
        submit(&mut state, "first");
        submit(&mut state, "second");

        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "second");

        type_str(&mut state, "!");
        assert_eq!(state.input, "second!");

        // Recall now starts fresh from the edited line, not from the middle of the old walk.
        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "second");
    }

    #[test]
    fn history_skips_immediate_duplicates() {
        let mut state = AppState::new();
        submit(&mut state, "repeat me");
        submit(&mut state, "repeat me");

        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "repeat me");
        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(
            state.input, "repeat me",
            "a second, distinct entry should not exist to recall into"
        );
    }

    #[test]
    fn explain_is_not_an_unknown_command() {
        let mut state = AppState::new();
        submit(&mut state, "/explain");
        let msg = last_system_message(&state);
        assert!(
            !msg.contains("Unknown command"),
            "/explain is advertised in /help but was rejected: {}",
            msg
        );
    }

    #[test]
    fn explain_toggles_and_reports_both_directions() {
        let mut state = AppState::new();
        assert!(!state.is_explaining());

        submit(&mut state, "/explain");
        assert!(state.is_explaining());
        assert!(last_system_message(&state).contains("on"));

        submit(&mut state, "/explain");
        assert!(!state.is_explaining());
        assert!(last_system_message(&state).contains("off"));
    }

    #[test]
    fn explain_tells_the_agent_task() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/explain");

        match rx.try_recv() {
            Ok(UserCommand::SetExplain(true)) => {}
            other => panic!("expected SetExplain(true), got {:?}", other),
        }

        let mut rx = submit(&mut state, "/explain");
        match rx.try_recv() {
            Ok(UserCommand::SetExplain(false)) => {}
            other => panic!("expected SetExplain(false), got {:?}", other),
        }
    }

    #[test]
    fn every_command_in_help_is_handled() {
        let mut state = AppState::new();
        submit(&mut state, "/help");
        let help = last_system_message(&state);

        let advertised: Vec<String> = help
            .lines()
            .filter_map(|line| line.split_whitespace().next())
            .filter(|word| word.starts_with('/'))
            .map(|word| word.to_string())
            .collect();
        assert!(advertised.len() >= 6, "parsed too few: {:?}", advertised);

        for command in advertised {
            let mut probe = AppState::new();
            submit(&mut probe, &command);
            let reply = last_system_message(&probe);
            assert!(
                !reply.contains("Unknown command"),
                "{} is listed in /help but not handled",
                command
            );
        }
    }

    #[test]
    fn model_without_args_shows_current() {
        let mut state = AppState::new();
        submit(&mut state, "/model");
        let msg = last_system_message(&state);
        assert!(msg.contains("Provider: anthropic"), "got: {}", msg);
        assert!(msg.contains("Model: claude-sonnet-5"), "got: {}", msg);
        assert!(msg.contains("Available models:"), "got: {}", msg);
    }

    #[test]
    fn model_status_shows_current() {
        let mut state = AppState::new();
        submit(&mut state, "/model status");
        let msg = last_system_message(&state);
        assert!(msg.contains("Provider: anthropic"), "got: {}", msg);
        assert!(msg.contains("Model: claude-sonnet-5"), "got: {}", msg);
    }

    // The request is the assertion, not the local fields: the UI no longer writes them itself, so
    // that a switch the agent rejected — or never received — cannot leave the header describing a
    // client that was never built. `Ready` is what moves them; see `ready_is_what_moves_the_pair`.
    #[test]
    fn model_set_asks_for_both() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/model set ollama llama3.2");

        assert_eq!(
            state.active_provider, "anthropic",
            "not applied optimistically"
        );

        match rx.try_recv() {
            Ok(UserCommand::SwitchModel { provider, model }) => {
                assert_eq!(provider, Provider::Ollama);
                assert_eq!(model, "llama3.2");
            }
            other => panic!("expected SwitchModel, got {:?}", other),
        }
    }

    #[test]
    fn model_set_requires_two_args() {
        let mut state = AppState::new();
        submit(&mut state, "/model set ollama");
        let msg = last_system_message(&state);
        assert!(msg.contains("Usage: /model set"), "got: {}", msg);
    }

    // A model belongs to a provider. Carrying `claude-sonnet-5` into deepseek produced a pair no
    // endpoint serves, which is exactly what the screenshot of `ollama` + `claude-sonnet-5` showed.
    #[test]
    fn switching_provider_carries_a_model_that_provider_serves() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/model provider deepseek");

        match rx.try_recv() {
            Ok(UserCommand::SwitchModel { provider, model }) => {
                assert_eq!(provider, Provider::Deepseek);
                assert_eq!(model, Provider::Deepseek.default_model());
                assert_ne!(model, "claude-sonnet-5");
            }
            other => panic!("expected SwitchModel, got {:?}", other),
        }
    }

    // Switching provider must not throw away a model the new provider does offer.
    #[test]
    fn switching_provider_keeps_a_model_the_target_still_serves() {
        let mut state = AppState::new();
        state.active_model = "claude-haiku".to_string();
        let mut rx = submit(&mut state, "/model provider anthropic");

        match rx.try_recv() {
            Ok(UserCommand::SwitchModel { model, .. }) => assert_eq!(model, "claude-haiku"),
            other => panic!("expected SwitchModel, got {:?}", other),
        }
    }

    #[test]
    fn model_provider_requires_arg() {
        let mut state = AppState::new();
        submit(&mut state, "/model provider");
        let msg = last_system_message(&state);
        assert!(msg.contains("Usage: /model provider"), "got: {}", msg);
    }

    #[test]
    fn model_model_asks_for_the_model() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/model model gpt-4o");

        assert_eq!(
            state.active_model, "claude-sonnet-5",
            "not applied optimistically"
        );

        match rx.try_recv() {
            Ok(UserCommand::SwitchModel { provider, model }) => {
                assert_eq!(provider, Provider::Anthropic);
                assert_eq!(model, "gpt-4o");
            }
            other => panic!("expected SwitchModel, got {:?}", other),
        }
    }

    // The agent's confirmation is the only thing that moves the displayed pair.
    #[test]
    fn ready_is_what_moves_the_pair() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Ready {
            provider: "ollama".to_string(),
            model: "llama3.2".to_string(),
            credential: true,
        });

        assert_eq!(state.active_provider, "ollama");
        assert_eq!(state.active_model, "llama3.2");
        assert_eq!(state.status, AppStatus::Ready);
    }

    // The boot with no key used to leave the header red for the whole session, because the only
    // path back to a resting state was a successful turn that could never happen.
    #[test]
    fn a_missing_credential_is_reported_as_such_and_is_recoverable() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Ready {
            provider: "anthropic".to_string(),
            model: "claude-sonnet-5".to_string(),
            credential: false,
        });
        assert_eq!(state.status, AppStatus::NeedsCredential);

        // Switching to a local provider is the documented way out.
        state.handle_agent_update(AgentUpdate::Ready {
            provider: "ollama".to_string(),
            model: "llama3.2".to_string(),
            credential: true,
        });
        assert_eq!(state.status, AppStatus::Ready);
    }

    // A failed turn says nothing about whether the next one can be sent. The old status latched on
    // the first error and never recovered.
    #[test]
    fn an_error_does_not_latch_the_status() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Error("the tool blew up".to_string()));

        assert_eq!(state.status, AppStatus::Ready);
        assert!(last_system_message(&state).contains("blew up"));
    }

    // With the agent gone there is nothing to switch, and saying "switched" would be a lie — which
    // is exactly what the UI used to do, because every send result was discarded.
    #[test]
    fn a_switch_with_no_agent_listening_says_so() {
        let mut state = AppState::new();
        let (tx, rx) = mpsc::unbounded_channel();
        drop(rx);

        state.handle_command("/model provider ollama", &tx);

        let msg = last_system_message(&state);
        assert!(msg.contains("no longer running"), "got: {}", msg);
        assert_eq!(state.active_provider, "anthropic");
    }

    #[test]
    fn model_model_requires_arg() {
        let mut state = AppState::new();
        submit(&mut state, "/model model");
        let msg = last_system_message(&state);
        assert!(msg.contains("Usage: /model model"), "got: {}", msg);
    }

    #[test]
    fn model_rejects_unknown_subcommand() {
        let mut state = AppState::new();
        submit(&mut state, "/model foobar");
        let msg = last_system_message(&state);
        assert!(msg.contains("Unknown subcommand"), "got: {}", msg);
    }

    #[test]
    fn model_set_rejects_unknown_provider() {
        let mut state = AppState::new();
        submit(&mut state, "/model set fakeprovider gpt-4o");
        let msg = last_system_message(&state);
        assert!(msg.contains("Unknown provider"), "got: {}", msg);
    }

    // --- Autocomplete tests ---

    #[test]
    fn typing_slash_activates_autocomplete() {
        let mut state = AppState::new();
        let (_tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);

        assert!(state.autocomplete_active);
        assert!(!state.autocomplete_matches.is_empty());
    }

    #[test]
    fn autocomplete_filters_by_prefix() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "he", &tx);

        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(matching, vec!["/help"]);
    }

    #[test]
    fn autocomplete_filters_model_subcommands() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "model", &tx);

        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert!(
            matching.contains(&"/model"),
            "expected /model in matches, got: {:?}",
            matching
        );
        assert!(
            matching.contains(&"/model set"),
            "expected /model set in matches, got: {:?}",
            matching
        );
    }

    // A space used to always close the popup, so nothing ever suggested provider or model names
    // for `/login`, `/logout`, `/model provider`, `/model model` or `/model set`'s arguments.
    #[test]
    fn a_trailing_space_suggests_the_next_argument_instead_of_closing() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/model ", &tx);

        assert!(state.autocomplete_active);
        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(matching, vec!["status", "set", "provider", "model"]);
    }

    #[test]
    fn model_provider_suggests_provider_names() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/model provider anth", &tx);

        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(matching, vec!["anthropic"]);
    }

    #[test]
    fn login_suggests_provider_names_with_local_ones_flagged() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/login oll", &tx);

        let item = &state.autocomplete_matches[0];
        assert_eq!(item.value, "ollama");
        assert_eq!(item.description, "local, no credential needed");
    }

    #[test]
    fn logout_suggests_provider_names() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/logout xa", &tx);

        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(matching, vec!["xai"]);
    }

    #[test]
    fn model_model_suggests_models_for_the_active_provider() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/model model claude-", &tx);

        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(
            matching,
            vec!["claude-sonnet-5", "claude-opus-5", "claude-haiku"]
        );
    }

    #[test]
    fn model_set_suggests_models_once_a_provider_is_typed() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/model set groq ", &tx);

        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(
            matching,
            vec![
                "llama-3.3-70b-versatile",
                "llama-3.1-8b-instant",
                "mixtral-8x7b-32768"
            ]
        );
    }

    // The key is a secret, never a suggestion source.
    #[test]
    fn login_offers_no_suggestions_for_the_key_itself() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/login anthropic ", &tx);

        assert!(!state.autocomplete_active);
        assert!(state.autocomplete_matches.is_empty());
    }

    // Once the typed text exactly matches the highlighted suggestion, Enter used to "accept" it —
    // a no-op that left the command sitting in the input box requiring a second Enter to run.
    #[test]
    fn enter_submits_once_the_typed_argument_exactly_matches_the_suggestion() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/model provider ollama");

        assert!(
            state.input.is_empty(),
            "Enter should have submitted, not just accepted in place"
        );
        match rx.try_recv() {
            Ok(UserCommand::SwitchModel { provider, .. }) => {
                assert_eq!(provider, Provider::Ollama);
            }
            other => panic!("expected the command to actually run, got {:?}", other),
        }
    }

    #[test]
    fn backspacing_out_of_a_dead_end_revives_suggestions() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        // The key portion offers nothing (see above), so autocomplete closes here...
        type_str_with_tx(&mut state, "/login anthropic k", &tx);
        assert!(!state.autocomplete_active);

        // ...but deleting back into the provider name (dropping " k") should bring suggestions
        // back rather than requiring the whole line to be retyped from a fresh "/".
        press(&mut state, KeyCode::Backspace, KeyModifiers::NONE);
        press(&mut state, KeyCode::Backspace, KeyModifiers::NONE);
        assert_eq!(state.input, "/login anthropic");
        assert!(state.autocomplete_active);
        let matching: Vec<_> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert_eq!(matching, vec!["anthropic"]);
    }

    #[test]
    fn tab_cycles_through_matches() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "m", &tx);

        assert_eq!(state.autocomplete_selected, 0);
        press(&mut state, KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(state.autocomplete_selected, 1);
        press(&mut state, KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(state.autocomplete_selected, 2);
    }

    #[test]
    fn tab_wraps_around() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "m", &tx);

        let count = state.autocomplete_matches.len();
        for _ in 0..count {
            press(&mut state, KeyCode::Tab, KeyModifiers::NONE);
        }
        assert_eq!(state.autocomplete_selected, 0);
    }

    #[test]
    fn shift_tab_cycles_backwards() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "m", &tx);

        let count = state.autocomplete_matches.len();
        press(&mut state, KeyCode::BackTab, KeyModifiers::SHIFT);
        assert_eq!(state.autocomplete_selected, count - 1);
    }

    // The arrow keys reach the popup instead of the chat scroll while it is open — and go back to
    // scrolling the chat once it closes.
    #[test]
    fn arrow_keys_navigate_the_popup() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "m", &tx);
        let count = state.autocomplete_matches.len();
        assert!(count > 1);

        press(&mut state, KeyCode::Down, KeyModifiers::NONE);
        assert_eq!(state.autocomplete_selected, 1);

        press(&mut state, KeyCode::Up, KeyModifiers::NONE);
        assert_eq!(state.autocomplete_selected, 0);

        // Wraps to the last entry rather than sticking at the top.
        press(&mut state, KeyCode::Up, KeyModifiers::NONE);
        assert_eq!(state.autocomplete_selected, count - 1);
    }

    #[test]
    fn arrows_scroll_the_chat_once_the_popup_is_closed() {
        let mut state = AppState::new();
        state.scroll_forward(5);
        press(&mut state, KeyCode::Up, KeyModifiers::NONE);
        assert_eq!(state.chat_scroll, 4);
    }

    #[test]
    fn enter_accepts_autocomplete() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "he", &tx);
        press(&mut state, KeyCode::Enter, KeyModifiers::NONE);

        assert_eq!(state.input, "/help");
        assert!(!state.autocomplete_active);
    }

    #[test]
    fn escape_cancels_autocomplete() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "he", &tx);
        press(&mut state, KeyCode::Esc, KeyModifiers::NONE);

        assert_eq!(state.input, "/");
        assert!(!state.autocomplete_active);
    }

    #[test]
    fn enter_submits_full_command_even_with_autocomplete_active() {
        let mut state = AppState::new();
        let (_tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        submit(&mut state, "/help");

        let msg = last_system_message(&state);
        assert!(msg.contains("Available commands"), "got: {}", msg);
    }

    #[test]
    fn backspace_deactivates_autocomplete_when_not_slash_prefix() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "h", &tx);
        assert!(state.autocomplete_active);

        // Backspace removes "h", input becomes "/" - still a valid prefix
        press(&mut state, KeyCode::Backspace, KeyModifiers::NONE);
        assert!(state.autocomplete_active);
        assert_eq!(state.input, "/");
    }

    #[test]
    fn space_deactivates_autocomplete() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "help", &tx);
        assert!(state.autocomplete_active);

        press(&mut state, KeyCode::Char(' '), KeyModifiers::NONE);
        assert!(!state.autocomplete_active);
    }

    #[test]
    fn no_matches_deactivates_autocomplete() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "xyz", &tx);

        assert!(!state.autocomplete_active);
        assert!(state.autocomplete_matches.is_empty());
    }

    #[test]
    fn enter_without_autocomplete_submits_command() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        type_str_with_tx(&mut state, "/status", &tx);
        press(&mut state, KeyCode::Enter, KeyModifiers::NONE);

        let msg = last_system_message(&state);
        assert!(msg.contains("Status: Ready"), "got: {}", msg);
    }

    // `/status` is where the old Context panel went, so every line of it has to stand on its own —
    // no label left dangling above a list, whatever the server count happens to be.
    fn status_of(servers: Vec<crate::channels::McpServerStatus>) -> String {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();
        state.mcp_servers = servers;
        state.handle_command("/status", &tx);
        last_system_message(&state)
    }

    fn server(name: &str, connected: bool) -> crate::channels::McpServerStatus {
        crate::channels::McpServerStatus {
            name: name.to_string(),
            connected,
            detail: format!("https://{}.example/mcp", name),
        }
    }

    // Regression: the palette overlay captures every key before the main handler sees it, and it
    // had no Ctrl+C arm — so with the palette open the app could not be quit at all.
    #[test]
    fn ctrl_c_quits_even_with_the_palette_open() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel::<UserCommand>();

        state.palette_open();
        assert!(state.palette_open);
        assert!(
            state.handle_key(
                KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
                &tx
            ),
            "ctrl+c must quit from inside the palette"
        );
    }

    #[test]
    fn status_says_none_when_no_mcp_server_is_configured() {
        assert!(status_of(Vec::new()).contains("MCP: none"));
    }

    // A lone server goes on the label's own line: "MCP:" heading a one-item list reads as a
    // heading someone forgot to fill in.
    #[test]
    fn status_puts_a_single_mcp_server_inline() {
        let msg = status_of(vec![server("raven", true)]);
        assert!(
            msg.contains("MCP: ● raven https://raven.example/mcp"),
            "got: {}",
            msg
        );
        assert!(!msg.contains("MCP:\n"), "label left dangling: {}", msg);
    }

    #[test]
    fn status_counts_mcp_servers_before_listing_them() {
        let msg = status_of(vec![
            server("raven", true),
            server("other", false),
            server("third", true),
        ]);
        assert!(msg.contains("MCP: 3 servers, 2 connected"), "got: {}", msg);
        assert!(msg.contains("\n  ○ other"), "got: {}", msg);
    }

    fn type_str_with_tx(state: &mut AppState, text: &str, tx: &mpsc::UnboundedSender<UserCommand>) {
        for c in text.chars() {
            let modifiers = if c.is_uppercase() {
                KeyModifiers::SHIFT
            } else {
                KeyModifiers::NONE
            };
            state.handle_key(KeyEvent::new(KeyCode::Char(c), modifiers), tx);
        }
    }

    // --- /login, /logout, /providers ---

    // A tempdir keeps these tests off the real `~/.config/procyon/credentials.toml`.
    fn state_with_tempdir() -> (AppState, tempfile::TempDir) {
        let temp = tempfile::tempdir().unwrap();
        let mut state = AppState::new();
        state.credentials_path = Some(temp.path().join("credentials.toml"));
        (state, temp)
    }

    #[test]
    fn login_stores_a_key_retrievable_afterward() {
        let (mut state, temp) = state_with_tempdir();
        submit(&mut state, "/login groq gsk-secret");

        let store = crate::credentials::CredentialStore::load(temp.path().join("credentials.toml"))
            .unwrap();
        assert_eq!(store.get("groq"), Some("gsk-secret"));
    }

    // A key split across more than one whitespace token used to be silently truncated to the
    // first token alone.
    #[test]
    fn login_keeps_a_key_containing_internal_whitespace() {
        let (mut state, temp) = state_with_tempdir();
        submit(&mut state, "/login groq gsk part-two");

        let store = crate::credentials::CredentialStore::load(temp.path().join("credentials.toml"))
            .unwrap();
        assert_eq!(store.get("groq"), Some("gsk part-two"));
    }

    #[test]
    fn login_overwriting_the_active_provider_triggers_a_live_switch() {
        let (mut state, _temp) = state_with_tempdir();
        let active_model = state.active_model.clone();
        let mut rx = submit(&mut state, "/login anthropic sk-ant-secret");

        match rx.try_recv() {
            Ok(UserCommand::SwitchModel { provider, model }) => {
                assert_eq!(provider, Provider::Anthropic);
                assert_eq!(model, active_model);
            }
            other => panic!("expected SwitchModel, got {:?}", other),
        }
    }

    #[test]
    fn login_for_an_inactive_provider_just_confirms_and_suggests_the_switch() {
        let (mut state, _temp) = state_with_tempdir();
        let mut rx = submit(&mut state, "/login groq gsk-secret");
        assert!(rx.try_recv().is_err(), "should not have asked to switch");

        let msg = last_system_message(&state);
        assert!(msg.contains("/model provider groq"), "got: {}", msg);
    }

    #[test]
    fn login_with_an_invalid_provider_reports_an_error_and_does_not_crash() {
        let (mut state, _temp) = state_with_tempdir();
        submit(&mut state, "/login fakeprovider somekey");
        let msg = last_system_message(&state);
        assert!(msg.contains("Unknown provider"), "got: {}", msg);
    }

    #[test]
    fn login_never_leaks_the_raw_key_into_messages() {
        let (mut state, _temp) = state_with_tempdir();
        submit(&mut state, "/login groq super-secret-key");

        for message in &state.messages {
            let text = match message {
                ChatMessage::User(t)
                | ChatMessage::Agent(t)
                | ChatMessage::System(t)
                | ChatMessage::Event(t) => t,
            };
            assert!(
                !text.contains("super-secret-key"),
                "the raw key leaked into a message: {}",
                text
            );
        }
    }

    #[test]
    fn login_requires_both_a_provider_and_a_key() {
        let (mut state, _temp) = state_with_tempdir();
        submit(&mut state, "/login groq");
        let msg = last_system_message(&state);
        assert!(msg.contains("Usage: /login"), "got: {}", msg);
    }

    #[test]
    fn logout_removes_a_known_providers_credential() {
        let (mut state, temp) = state_with_tempdir();
        submit(&mut state, "/login groq gsk-1");
        submit(&mut state, "/logout groq");

        let msg = last_system_message(&state);
        assert!(msg.contains("Removed stored credential"), "got: {}", msg);

        let store = crate::credentials::CredentialStore::load(temp.path().join("credentials.toml"))
            .unwrap();
        assert_eq!(store.get("groq"), None);
    }

    #[test]
    fn logout_reports_when_there_is_nothing_to_remove() {
        let (mut state, _temp) = state_with_tempdir();
        submit(&mut state, "/logout groq");
        let msg = last_system_message(&state);
        assert!(msg.contains("No stored credential"), "got: {}", msg);
    }

    #[test]
    fn providers_lists_every_named_provider_and_flags_local_ones() {
        let (mut state, _temp) = state_with_tempdir();
        submit(&mut state, "/providers");
        let msg = last_system_message(&state);

        for provider in Provider::ALL {
            assert!(
                msg.contains(&provider.to_string()),
                "{} missing from: {}",
                provider,
                msg
            );
        }
        assert!(msg.contains("local, no credential needed"), "got: {}", msg);
    }

    #[test]
    fn providers_reflects_a_credential_saved_through_login() {
        let (mut state, _temp) = state_with_tempdir();
        submit(&mut state, "/login groq gsk-1");
        submit(&mut state, "/providers");
        let msg = last_system_message(&state);

        let line = msg
            .lines()
            .find(|line| line.trim_start().starts_with("groq"))
            .unwrap_or_else(|| panic!("no groq line in: {}", msg));
        assert!(line.contains("stored"), "got: {}", line);
    }

    // Downloading and running a shell script on the user's machine is not something a bare
    // `/install-stellar-build` should ever trigger — only a second, explicit `confirm`.
    #[test]
    fn install_stellar_build_without_confirm_explains_but_does_not_run_anything() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/install-stellar-build");

        let msg = last_system_message(&state);
        assert!(
            msg.contains(crate::channels::STELLAR_BUILD_INSTALL_URL),
            "got: {}",
            msg
        );
        assert!(msg.contains("confirm"), "got: {}", msg);
        assert!(rx.try_recv().is_err(), "should not have sent anything yet");
    }

    #[test]
    fn install_stellar_build_confirm_sends_the_install_command() {
        let mut state = AppState::new();
        let mut rx = submit(&mut state, "/install-stellar-build confirm");

        match rx.try_recv() {
            Ok(UserCommand::InstallStellarBuild) => {}
            other => panic!("expected InstallStellarBuild, got {:?}", other),
        }
    }

    #[test]
    fn activity_label_maps_status_to_semantic_phase() {
        assert_eq!(activity_label("Thinking..."), "Thinking");
        assert_eq!(
            activity_label("Using tool: caatinga_build"),
            "Building contract"
        );
        assert_eq!(activity_label("Using tool: caatinga_deploy"), "Deploying");
        assert_eq!(
            activity_label("Using tool: raven__search"),
            "Searching Stellar Docs"
        );
        assert_eq!(activity_label("Using tool: grep"), "Searching");
    }

    #[test]
    fn execution_trace_groups_tool_status_into_steps() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Thinking...".to_string()));
        state.handle_agent_update(AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));
        state.handle_agent_update(AgentUpdate::Status(
            "Using tool: caatinga_deploy".to_string(),
        ));
        assert_eq!(state.execution_steps.len(), 3);
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Done);
        assert_eq!(state.execution_steps[2].state, ExecutionStepState::Running);
        state.handle_agent_update(AgentUpdate::ResponseChunk("done".to_string()));
        assert_eq!(state.execution_steps[2].state, ExecutionStepState::Done);
    }

    #[test]
    fn execution_trace_marks_failed_on_error() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));
        state.handle_agent_update(AgentUpdate::Error("boom".to_string()));
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Failed);
        assert!(state.execution_failed);
    }

    #[test]
    fn new_user_prompt_clears_execution_trace() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));
        submit(&mut state, "hello");
        assert!(state.execution_steps.is_empty());
    }
}