procyon 0.1.2

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
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
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
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),
}

/// 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",
    }
}

/// `2.1k/4k` — how full the context window is, in the same shape on the status line and in
/// `/status`.
///
/// Rounded hard on purpose. The number is an estimate anchored on the provider's own usage
/// report, so rendering it to the token would claim a precision it does not have; what the reader
/// needs is whether they are near the ceiling, and one decimal place answers that.
pub fn context_meter(used: usize, window: usize) -> String {
    fn thousands(n: usize) -> String {
        if n < 1_000 {
            return n.to_string();
        }
        let k = n as f64 / 1_000.0;
        if k < 10.0 {
            format!("{:.1}k", k)
        } else {
            format!("{:.0}k", k)
        }
    }
    format!("{}/{}", thousands(used), thousands(window))
}

/// 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,
    /// Index into `messages` this step belongs before — the transcript length when it opened.
    /// The trace is interleaved at these anchors rather than appended, so a tool call is drawn
    /// above the reply it fed rather than below it.
    pub after: usize,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ExecutionStepState {
    Running,
    /// Parked on the user — the approval prompt is up. Distinct from `Running` because a step that
    /// says "writing file" while it is actually waiting to be allowed to is claiming to have done
    /// something it has not.
    Waiting,
    Done,
    Failed,
}

impl ExecutionStepState {
    /// Whether the step is still open, and so due a terminal state.
    fn is_open(&self) -> bool {
        matches!(self, Self::Running | Self::Waiting)
    }
}

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,
    /// Raised by Esc while a turn is in flight; read by the agent task. Defaults to a flag nobody
    /// else holds, so a state built in a test can be driven without wiring one up.
    pub cancel: crate::channels::CancelFlag,
    /// The tool call currently waiting on the user, if any. While this is set the prompt is not a
    /// prompt: every key is answering the question.
    pub pending_approval: Option<crate::channels::ApprovalRequest>,
    /// Where answers go. `None` in tests, which assert on `pending_approval` instead.
    pub approval_tx: Option<mpsc::UnboundedSender<crate::channels::ApprovalDecision>>,
    /// Whether signing on mainnet is permitted, as the agent reports it. Mirrored rather than
    /// read here so the screen and the gate cannot disagree about real funds.
    pub mainnet_allowed: bool,
    /// What the local server actually has, as the agent reports it. Empty means nobody could be
    /// asked — a remote provider, or a local server that is not running — and the built-in
    /// suggestions stand in.
    pub local_models: Vec<String>,
    /// Estimated prompt tokens over the window they have to fit in, as the agent last measured
    /// them. `None` until the first turn: the window is not knowable at boot for a locally served
    /// model, since Ollama only reports it once the weights are loaded.
    pub context_usage: Option<(usize, usize)>,
}

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,
            cancel: crate::channels::CancelFlag::default(),
            pending_approval: None,
            approval_tx: None,
            mainnet_allowed: false,
            local_models: Vec::new(),
            context_usage: None,
        }
    }

    /// 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)> {
            // Real names where they are known. Completing to a model the server does not have is
            // how `/model model <typo>` used to be reached in the first place.
            let local: Option<Provider> = provider.parse().ok().filter(|p: &Provider| p.is_local());
            if local.is_some() && !self.local_models.is_empty() {
                return self
                    .local_models
                    .iter()
                    .map(|m| (m.clone(), String::new()))
                    .collect();
            }

            provider
                .parse::<Provider>()
                .ok()
                .into_iter()
                .flat_map(|p| p.suggested_models())
                .map(|m| (m.to_string(), "suggestion".to_string()))
                .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(),
                    "Real funds — asks to confirm".to_string(),
                ),
            ],
            // So the second word is discoverable rather than something the message alone has to
            // teach.
            ["/network", "mainnet"] => vec![(
                "confirm".to_string(),
                "Actually switch to the public network".to_string(),
            )],
            ["/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" | "/test" | "/deploy" | "/doctor" => {
                                self.run_quick_action(&item.value, user_tx)
                            }
                            _ => 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
    }

    /// Answers the pending approval. Returns true only for quit, like every other key handler.
    ///
    /// Unrecognised keys are ignored rather than treated as either answer: this is the one prompt
    /// in the app where guessing wrong writes to the user's files.
    fn approval_handle_key(&mut self, key: crossterm::event::KeyEvent) -> bool {
        use crate::channels::ApprovalDecision;

        let decision = match (key.modifiers, key.code) {
            // Quit still outranks the question — an overlay that can trap you is worse than no
            // overlay, and this one blocks a running turn.
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => return true,
            (_, KeyCode::Char('y')) | (_, KeyCode::Enter) => ApprovalDecision::Once,
            (_, KeyCode::Char('a')) => ApprovalDecision::Always,
            (_, KeyCode::Char('n')) | (_, KeyCode::Esc) => ApprovalDecision::Deny,
            _ => return false,
        };

        let request = self.pending_approval.take();
        let tool = request.as_ref().map(|r| r.tool.clone()).unwrap_or_default();
        let scope = request
            .as_ref()
            .map(|r| r.scope.clone())
            .unwrap_or_else(|| tool.clone());
        // The detail, not just the tool name: this is the line someone comes back to when they
        // wonder what touched a file, and "Allowed write_file" does not answer that.
        let what = request.map(|r| r.detail).unwrap_or_else(|| tool.clone());

        // Said in the transcript, not just acted on: an approval is a decision the user should be
        // able to find again.
        self.messages.push(ChatMessage::System(match decision {
            ApprovalDecision::Once => format!("Allowed {}", what),
            // Names the scope, not the tool: the grant covers this tool acting on this target, and
            // saying "write_file" would report a wider permission than was actually given.
            ApprovalDecision::Always => {
                format!(
                    "Allowed {} — and {} for the rest of this session",
                    what, scope
                )
            }
            ApprovalDecision::Deny => format!("Declined {}", what),
        }));

        if let Some(tx) = &self.approval_tx {
            let _ = tx.send(decision);
        }
        false
    }

    /// Everything that happens when the user commits a line.
    ///
    /// Extracted because Enter has two arms — one that closes the autocomplete popup and one for a
    /// plain prompt — and they had drifted. A command submitted from the popup skipped both the
    /// command history and the fresh execution trace, so Alt+Up could not recall it and the last
    /// turn's steps stayed on screen underneath it.
    fn submit_line(&mut self, user_tx: &mpsc::UnboundedSender<UserCommand>) {
        let msg = self.input.trim().to_string();
        if msg.is_empty() {
            return;
        }

        self.push_history(msg.clone());
        // New user intent starts a fresh execution story.
        self.clear_execution();

        // Echoed whichever it was. A slash command used to answer with nothing above it, so
        // scrolling back through a long session found a run of replies with no questions — and no
        // way to tell which reply answered what.
        //
        // Pushed before the command runs, so `/clear` still takes it with everything else: an echo
        // that survived a clear would be the one line left on screen.
        self.messages.push(ChatMessage::User(Self::echo_of(&msg)));

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

        self.input.clear();
        self.input_cursor = 0;
        self.autocomplete_active = false;
        self.autocomplete_matches.clear();
    }

    /// What the transcript shows for a line the user submitted.
    ///
    /// Everything verbatim except a credential. `/login <provider> <key>` is the one command whose
    /// arguments must never reach `self.messages`: the transcript is rendered, scrolled and
    /// screenshotted, and the command handler already takes care not to put the key there.
    fn echo_of(submitted: &str) -> String {
        let mut parts = submitted.split_whitespace();
        if parts.next() != Some("/login") {
            return submitted.to_string();
        }

        match parts.next() {
            Some(provider) => format!("/login {} ••••••", provider),
            // Nothing to hide: the usage error is the reply.
            None => "/login".to_string(),
        }
    }

    /// Runs the tool a quick action stands for.
    ///
    /// These used to send a sentence to the model — "run tests" — which made a key labelled "Run
    /// tests" a suggestion the model could answer with an opinion. In a project whose `package.json`
    /// declares a test command, Ctrl+T replied that it could not find any tests.
    ///
    /// Deploy is deterministic too, on the session's network. It signs, so it is exactly what the
    /// approval gate is for: the user is asked, with the network named, before anything is
    /// submitted.
    fn run_quick_action(&mut self, action: &str, user_tx: &mpsc::UnboundedSender<UserCommand>) {
        let (name, input, label) = match action {
            "/build" => ("caatinga_build", serde_json::json!({}), "Building project"),
            "/test" => ("run_tests", serde_json::json!({}), "Running tests"),
            "/deploy" => (
                "caatinga_deploy",
                serde_json::json!({ "network": self.active_network }),
                "Deploying contract",
            ),
            "/doctor" => (
                "caatinga_doctor",
                serde_json::json!({}),
                "Checking environment",
            ),
            _ => return,
        };

        self.clear_execution();
        let _ = user_tx.send(UserCommand::RunTool {
            name: name.to_string(),
            input,
            label: label.to_string(),
        });
    }

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

        // An approval outranks even the palette: a turn is parked waiting on this answer, and any
        // other key would be typed into an input the user cannot submit anyway.
        if self.pending_approval.is_some() {
            return self.approval_handle_key(key);
        }

        // 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.run_quick_action("/deploy", user_tx);
            }
            (KeyModifiers::CONTROL, KeyCode::Char('t')) => {
                self.run_quick_action("/test", user_tx);
            }
            (KeyModifiers::CONTROL, KeyCode::Char('b')) => {
                self.run_quick_action("/build", user_tx);
            }
            // 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 {
                    self.submit_line(user_tx);
                } else {
                    self.accept_autocomplete();
                }
            }
            // Cancel autocomplete
            (KeyModifiers::NONE, KeyCode::Esc) if self.autocomplete_active => {
                self.cancel_autocomplete();
            }
            // Stop the turn in flight. Ordered after the autocomplete arm so an open popup is
            // still what Esc closes first; a turn can be running underneath one.
            (KeyModifiers::NONE, KeyCode::Esc) if matches!(self.status, AppStatus::Working) => {
                self.cancel.raise();
                // The agent only notices between steps, so say something now rather than leave
                // Esc looking dead while the current tool or request finishes unwinding.
                self.current_activity = Some("Interrupting...".to_string());
            }
            (KeyModifiers::NONE, KeyCode::Enter) => {
                self.submit_line(user_tx);
            }
            // 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\
                     Esc            - Stop the turn in flight\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();
                // The trace is part of the transcript, not a separate thing that outlives it:
                // clearing only `messages` left the last turn's steps on screen under the words
                // "Chat cleared."
                self.clear_execution();
                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,
                    // The place someone checks on purpose, so it carries the same caveat the
                    // status line does rather than making them infer it.
                    if self.active_network == "mainnet" && !self.mainnet_allowed {
                        "mainnet (signing disabled)".to_string()
                    } else {
                        self.active_network.clone()
                    },
                    self.active_account,
                    self.active_contract.as_deref().unwrap_or(""),
                    self.active_provider,
                    self.active_model,
                    if self.is_explaining() { "on" } else { "off" },
                );
                // The one number a user cannot otherwise find out. Compaction announces itself
                // only after it has already dropped the early turns; on a 4k local window that
                // arrives within a handful of tool calls, and until then nothing said the ceiling
                // was near. Absent before the first turn, because for Ollama the window is read
                // back from the loaded model and there is nothing loaded yet.
                out.push_str(&match self.context_usage {
                    Some((used, window)) => {
                        format!("\nContext: {}", context_meter(used, window))
                    }
                    None => "\nContext: not measured yet".to_string(),
                });
                // 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 {
                        // Mainnet is the one network where a mistake costs real money, and the
                        // switch used to be as quiet as any other. Typed twice, like
                        // `/install-stellar-build`, so it cannot be reached by a stray tab-complete.
                        "mainnet" if parts.get(2).copied() != Some("confirm") => {
                            self.messages.push(ChatMessage::System(
                                if self.mainnet_allowed {
                                    "Mainnet is the public network: operations there spend real \
                                     funds and cannot be undone. Signing is enabled on this \
                                     machine.\n\nRun `/network mainnet confirm` to switch."
                                } else {
                                    "Mainnet is the public network: operations there spend real \
                                     funds and cannot be undone. Signing is currently disabled, so \
                                     deploys and invokes would be refused — reading is \
                                     unaffected.\n\nRun `/network mainnet confirm` to switch \
                                     anyway."
                                }
                                .to_string(),
                            ));
                        }
                        "local" | "testnet" | "mainnet" => {
                            self.active_network = network.to_string();
                            // Says which of the two states the session is in, rather than leaving
                            // the screen claiming a network the harness will refuse to act on.
                            let note = match (*network == "mainnet", self.mainnet_allowed) {
                                (true, true) => " — signing enabled, operations spend real funds",
                                (true, false) => {
                                    " — signing disabled, so deploys and invokes will \
                                                  be refused"
                                }
                                _ => "",
                            };
                            self.messages.push(ChatMessage::System(format!(
                                "Network switched to {}{}",
                                network, note
                            )));
                        }
                        _ => {
                            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);
                        // "Available models" used to be a built-in list, which on this machine
                        // named three models that were not installed and omitted the one in use.
                        // What the server has is a fact; what this build ships is a suggestion,
                        // and the two are labelled as what they are.
                        let (heading, models) = if self.local_models.is_empty() {
                            (
                                "Suggested models:",
                                provider
                                    .suggested_models()
                                    .iter()
                                    .map(|m| m.to_string())
                                    .collect::<Vec<_>>(),
                            )
                        } else {
                            ("Installed models:", self.local_models.clone())
                        };

                        let mut msg = format!(
                            "Provider: {}\nModel: {}\n\n{}",
                            self.active_provider, self.active_model, heading
                        );
                        for model in models {
                            let active = crate::llm::is_installed(
                                std::slice::from_ref(&model),
                                &self.active_model,
                            );
                            msg.push_str(&format!(
                                "\n  {}{}",
                                model,
                                if active { "  (in use)" } else { "" }
                            ));
                        }
                        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
                )));
            }
        }
    }

    /// True for a step that stands for a tool call rather than a phase the agent announced.
    fn is_tool_step(label: &str) -> bool {
        label.to_lowercase().starts_with("using tool:")
    }

    /// Settles the most recent open *phase*, leaving tool steps to `ToolFinished`.
    fn close_phase(steps: &mut [ExecutionStep]) {
        if let Some(last) = steps.last_mut() {
            if last.state == ExecutionStepState::Running && !Self::is_tool_step(&last.label) {
                last.state = ExecutionStepState::Done;
            }
        }
    }

    /// The still-open step belonging to `tool`, searched from the newest.
    ///
    /// Matched by name rather than by taking the last open step: a tool result can arrive after
    /// the agent has already announced the next phase, and settling the wrong step would show one
    /// call's outcome against another call's label.
    fn open_step_for(&mut self, tool: &str) -> Option<&mut ExecutionStep> {
        let needle = format!("using tool: {}", tool.to_lowercase());
        self.execution_steps
            .iter_mut()
            .rev()
            .find(|step| step.state.is_open() && step.label.to_lowercase().starts_with(&needle))
    }

    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;
                // Text flowing means the phase that preceded it is over. A tool step is left
                // alone: its outcome is `ToolFinished`, and guessing "done" here is how a failed
                // call came to be drawn as a successful one.
                Self::close_phase(&mut self.execution_steps);
                self.status = AppStatus::Working;
            }
            AgentUpdate::ResponseEnd => {
                self.end_stream();
                // Finalise any running step
                for step in &mut self.execution_steps {
                    if step.state.is_open() {
                        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());
                // A new phase closes the one before it — but never a tool step, which only
                // `ToolFinished` may settle.
                Self::close_phase(&mut self.execution_steps);
                // Only a step. It used to also push a `ChatMessage`, so every status arrived
                // twice — once inline and once in the trace — and the renderer carried a list of
                // the two spellings it knew to suppress. Anything not on that list, such as the
                // Ollama truncation warning, showed up in full both times.
                self.execution_steps.push(ExecutionStep {
                    label: text,
                    state: ExecutionStepState::Running,
                    // Where in the transcript this happened. Without it the whole trace was drawn
                    // after the last message, so tool calls appeared below the answer they
                    // produced — the result above its own cause.
                    after: self.messages.len(),
                });
                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.is_open() {
                        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.mainnet_allowed = snap.mainnet_allowed;
                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;
            }
            AgentUpdate::Approval(request) => {
                // Nothing is written down yet. The prompt itself carries the detail while it is up,
                // and the decision below records it afterwards — one line for one decision. Pushing
                // a "requested" message here too meant two lines per approval, and the second
                // landed after the step it belonged to.
                //
                // The step for this tool is up but nothing is happening yet — it is waiting on the
                // very prompt being raised, and must not go on claiming to be doing the work.
                if let Some(step) = self.open_step_for(&request.tool) {
                    step.state = ExecutionStepState::Waiting;
                }
                self.pending_approval = Some(request);
            }
            AgentUpdate::RetractResponse => {
                self.end_stream();
                // Only the message the recovered call was streamed into. Recovery requires the
                // whole text block to be the call, so that message holds the JSON and nothing the
                // user would want kept.
                if matches!(self.messages.last(), Some(ChatMessage::Agent(_))) {
                    self.messages.pop();
                }
            }
            AgentUpdate::History(entries) => {
                use crate::channels::TranscriptEntry as Entry;

                // Replaces rather than appends: this arrives at boot, before anything else can
                // have been said, and appending would double a transcript on a second History.
                self.messages.clear();
                self.execution_steps.clear();
                self.execution_failed = false;

                for entry in entries {
                    match entry {
                        Entry::User(text) => self.messages.push(ChatMessage::User(text)),
                        Entry::Agent(text) => self.messages.push(ChatMessage::Agent(text)),
                        Entry::Tool { name, ok } => self.execution_steps.push(ExecutionStep {
                            label: format!("Using tool: {}", name),
                            state: if ok {
                                ExecutionStepState::Done
                            } else {
                                ExecutionStepState::Failed
                            },
                            after: self.messages.len(),
                        }),
                        Entry::Compacted => self.messages.push(ChatMessage::System(
                            "— earlier messages compacted to fit the context window —".to_string(),
                        )),
                    }
                }
                // A restored conversation is history, so the view opens at its end, where the
                // user left off.
                self.chat_follow = true;
            }
            AgentUpdate::LocalModels(models) => {
                self.local_models = models;
            }
            AgentUpdate::Context { used, window } => {
                self.context_usage = Some((used, window));
            }
            AgentUpdate::ToolFinished { name, ok } => {
                if let Some(step) = self.open_step_for(&name) {
                    step.state = if ok {
                        ExecutionStepState::Done
                    } else {
                        ExecutionStepState::Failed
                    };
                }
                // A failed tool is not a failed turn: the model is told and usually recovers. Only
                // `Error` — a turn that could not proceed — latches `execution_failed`.
                self.current_activity = None;
            }
        }
    }

    // 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) => t.as_str(),
            })
            .collect();
        // Two messages, not one: a tool call between them means the agent said two separate
        // things, and running them together would read as one paragraph.
        assert_eq!(rendered, vec!["antes", "depois"]);

        // The tool call itself is a step, anchored between them so the trace is drawn where it
        // happened rather than after everything.
        assert_eq!(state.execution_steps.len(), 1);
        assert_eq!(state.execution_steps[0].after, 1);
    }

    #[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_a_step_and_sets_current_activity() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Thinking...".to_string()));

        // A step and nothing else. It used to also push a message, so every status was rendered
        // twice and the renderer carried a list of the spellings it knew to suppress.
        assert_eq!(state.execution_steps.len(), 1);
        assert_eq!(state.execution_steps[0].label, "Thinking...");
        assert!(state.messages.is_empty(), "got {:?}", state.messages);

        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);
        // A remote provider cannot be enumerated from here, so what this build ships is offered as
        // what it is — suggestions, not an inventory.
        assert!(msg.contains("Suggested 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),
        }
    }

    // Every malformed or unrecognised `/model` invocation gets a usage or rejection message
    // rather than silently doing nothing or panicking.
    #[test]
    fn model_rejects_bad_input_with_a_usage_or_rejection_message() {
        let cases = [
            ("/model set ollama", "Usage: /model set"),
            ("/model provider", "Usage: /model provider"),
            ("/model model", "Usage: /model model"),
            ("/model foobar", "Unknown subcommand"),
            ("/model set fakeprovider gpt-4o", "Unknown provider"),
        ];
        for (command, expected) in cases {
            let mut state = AppState::new();
            submit(&mut state, command);
            let msg = last_system_message(&state);
            assert!(msg.contains(expected), "{}: got {}", command, 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_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");
    }

    // --- 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();
        // Whatever claude-sonnet-5 (the default active provider) offers, filtered by the typed
        // prefix — not the catalog's contents, which change independently of this behaviour.
        let expected: Vec<_> = Provider::Anthropic
            .suggested_models()
            .into_iter()
            .filter(|m| m.starts_with("claude-"))
            .collect();
        assert_eq!(matching, expected);
    }

    #[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, Provider::Groq.suggested_models());
    }

    // 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);
    }

    // --- the transcript shows what was asked --------------------------------------------------

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

        // Without the echo, scrolling back through a session found replies with no questions and
        // no way to tell which reply answered what.
        assert!(
            matches!(&state.messages[0], ChatMessage::User(t) if t == "/status"),
            "got {:?}",
            state.messages
        );
        assert!(state.messages.len() > 1, "the reply is still there");
    }

    // The echo must not become a way to put a credential on screen: the transcript is rendered,
    // scrolled and screenshotted.
    #[test]
    fn the_echo_hides_a_credential() {
        let mut state = AppState::new();
        state.credentials_path = Some(tempfile::tempdir().unwrap().keep().join("credentials.toml"));
        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) => t,
            };
            assert!(!text.contains("super-secret-key"), "leaked: {}", text);
        }
        // Still legible as what was run, so the reply below it has a cause.
        assert!(
            matches!(&state.messages[0], ChatMessage::User(t) if t.starts_with("/login groq")),
            "got {:?}",
            state.messages
        );
    }

    // Enter has two arms, and they had drifted: submitting from the popup skipped the command
    // history and the trace reset. Both arms must do the same things.
    #[test]
    fn submitting_from_the_popup_does_what_submitting_normally_does() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Using tool: grep".to_string()));
        let (tx, _rx) = mpsc::unbounded_channel();

        // Typed character by character until it matches a suggestion exactly, which is the state
        // where Enter submits instead of accepting.
        type_str_with_tx(&mut state, "/status", &tx);
        assert!(state.autocomplete_active, "the popup should be open");
        press(&mut state, KeyCode::Enter, KeyModifiers::NONE);

        assert!(
            matches!(&state.messages[0], ChatMessage::User(t) if t == "/status"),
            "no echo: {:?}",
            state.messages
        );
        assert!(state.execution_steps.is_empty(), "the old trace survived");

        // And Alt+Up can recall it, which it could not before.
        press(&mut state, KeyCode::Up, KeyModifiers::ALT);
        assert_eq!(state.input, "/status");
    }

    #[test]
    fn a_login_with_no_arguments_has_nothing_to_hide() {
        assert_eq!(AppState::echo_of("/login"), "/login");
        assert_eq!(AppState::echo_of("/status"), "/status");
        assert_eq!(AppState::echo_of("build the counter"), "build the counter");
    }

    // --- which models /model offers -----------------------------------------------------------

    fn with_local_models(models: &[&str]) -> AppState {
        let mut state = AppState::new();
        state.active_provider = "ollama".to_string();
        state.active_model = "qwen3:4b".to_string();
        state.handle_agent_update(AgentUpdate::LocalModels(
            models.iter().map(|m| m.to_string()).collect(),
        ));
        state
    }

    fn last_message(state: &AppState) -> String {
        format!("{:?}", state.messages.last().unwrap())
    }

    // The regression: the list was built in, so on this machine it named three models that were
    // not installed and left out the one actually in use.
    #[test]
    fn a_local_provider_lists_what_the_server_has() {
        let mut state = with_local_models(&["qwen3:4b", "llama3.1:8b"]);
        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command("/model", &tx);

        let msg = last_message(&state);
        assert!(msg.contains("Installed models:"), "got {}", msg);
        assert!(msg.contains("qwen3:4b"), "got {}", msg);
        assert!(msg.contains("llama3.1:8b"), "got {}", msg);
        // Nothing this build merely suggests may appear beside them.
        assert!(!msg.contains("codellama"), "got {}", msg);
    }

    #[test]
    fn the_model_in_use_is_marked_in_the_list() {
        let mut state = with_local_models(&["qwen3:4b", "llama3.1:8b"]);
        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command("/model", &tx);

        // Omitting the model in use was half the complaint: the list answered "what could I run"
        // without answering "what am I running".
        let msg = last_message(&state);
        assert!(msg.contains("qwen3:4b  (in use)"), "got {}", msg);
    }

    #[test]
    fn the_implicit_latest_tag_still_marks_the_model_in_use() {
        let mut state = with_local_models(&["llama3.2:latest"]);
        state.active_model = "llama3.2".to_string();
        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command("/model", &tx);

        assert!(
            last_message(&state).contains("(in use)"),
            "{}",
            last_message(&state)
        );
    }

    // A server that is not running, or a remote provider: nobody could be asked, so what this
    // build ships is offered as what it is.
    #[test]
    fn with_nothing_to_ask_the_suggestions_are_labelled_as_suggestions() {
        let mut state = AppState::new();
        state.active_provider = "ollama".to_string();
        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command("/model", &tx);

        assert!(last_message(&state).contains("Suggested models:"));
    }

    // Completing to a model the server does not have is how `/model model <typo>` was reachable.
    #[test]
    fn autocomplete_offers_installed_models_rather_than_suggestions() {
        let mut state = with_local_models(&["qwen3:4b", "llama3.1:8b"]);
        let (tx, _rx) = mpsc::unbounded_channel();

        type_str_with_tx(&mut state, "/model model ", &tx);

        let offered: Vec<&str> = state
            .autocomplete_matches
            .iter()
            .map(|item| item.value.as_str())
            .collect();
        assert!(offered.contains(&"qwen3:4b"), "got {:?}", offered);
        assert!(!offered.contains(&"codellama"), "got {:?}", offered);
    }

    // --- switching to mainnet -----------------------------------------------------------------

    fn on_network(command: &str, allowed: bool) -> AppState {
        let mut state = AppState::new();
        state.mainnet_allowed = allowed;
        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command(command, &tx);
        state
    }

    #[test]
    fn the_quiet_networks_switch_without_ceremony() {
        for network in ["local", "testnet"] {
            let state = on_network(&format!("/network {}", network), false);
            assert_eq!(state.active_network, network);
        }
    }

    // The regression: mainnet switched as quietly as any other network, and a mistake there costs
    // real money.
    #[test]
    fn mainnet_is_not_entered_on_one_word() {
        let state = on_network("/network mainnet", true);

        assert_eq!(
            state.active_network, "testnet",
            "switched without confirming"
        );
        let said = format!("{:?}", state.messages.last().unwrap());
        assert!(said.contains("real funds"), "got {}", said);
        assert!(said.contains("confirm"), "got {}", said);
    }

    #[test]
    fn confirming_switches() {
        let state = on_network("/network mainnet confirm", true);
        assert_eq!(state.active_network, "mainnet");
    }

    // The heart of it: the screen said mainnet while every signing operation was refused, and
    // nothing reconciled the two.
    #[test]
    fn a_mainnet_that_cannot_sign_says_so_everywhere_it_is_shown() {
        let mut state = on_network("/network mainnet confirm", false);

        let switch = format!("{:?}", state.messages.last().unwrap());
        assert!(switch.contains("signing disabled"), "got {}", switch);

        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command("/status", &tx);
        let status = format!("{:?}", state.messages.last().unwrap());
        assert!(
            status.contains("mainnet (signing disabled)"),
            "got {}",
            status
        );
    }

    #[test]
    fn a_mainnet_that_can_sign_says_that_instead() {
        let state = on_network("/network mainnet confirm", true);
        let said = format!("{:?}", state.messages.last().unwrap());
        assert!(said.contains("signing enabled"), "got {}", said);
        assert!(!said.contains("signing disabled"), "got {}", said);
    }

    #[test]
    fn the_agent_is_what_tells_the_ui_whether_signing_is_allowed() {
        let mut state = AppState::new();
        // Never read from the config here: two sources of truth on a question about real funds is
        // exactly the bug.
        assert!(!state.mainnet_allowed);

        state.handle_agent_update(AgentUpdate::Workspace(crate::channels::WorkspaceSnapshot {
            project_name: "demo".to_string(),
            contract_name: None,
            network: "testnet".to_string(),
            account: "None".to_string(),
            mcp_servers: Vec::new(),
            mainnet_allowed: true,
        }));

        assert!(state.mainnet_allowed);
    }

    // --- quick actions ------------------------------------------------------------------------
    //
    // Nothing covered these before, which is how a key labelled "Run tests" went on not running
    // tests: it sent a sentence to the model, and in a project with a `cargo test` command wired
    // up, the model answered that it could not find any tests.

    fn quick_action(key: KeyCode) -> UserCommand {
        let mut state = AppState::new();
        state.active_network = "testnet".to_string();
        let (tx, mut rx) = mpsc::unbounded_channel();
        state.handle_key(KeyEvent::new(key, KeyModifiers::CONTROL), &tx);
        rx.try_recv().expect("a quick action must send something")
    }

    #[test]
    fn the_shortcuts_run_the_tool_they_are_named_after() {
        for (key, tool) in [
            (KeyCode::Char('t'), "run_tests"),
            (KeyCode::Char('b'), "caatinga_build"),
            (KeyCode::Char('d'), "caatinga_deploy"),
        ] {
            match quick_action(key) {
                UserCommand::RunTool { name, .. } => assert_eq!(name, tool, "key {:?}", key),
                // The regression: a suggestion the model was free to answer with an opinion.
                other => panic!("expected a tool call for {:?}, got {:?}", key, other),
            }
        }
    }

    // The deploy tool refuses to guess a network, because it signs. The session already knows
    // which one the user is on, so the shortcut says it rather than leaving the tool to fail.
    #[test]
    fn deploy_names_the_network_the_session_is_on() {
        match quick_action(KeyCode::Char('d')) {
            UserCommand::RunTool { input, .. } => {
                assert_eq!(
                    input.get("network").and_then(|v| v.as_str()),
                    Some("testnet")
                );
            }
            other => panic!("got {:?}", other),
        }
    }

    #[test]
    fn a_quick_action_starts_a_fresh_execution_story() {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status("Using tool: grep".to_string()));
        let (tx, _rx) = mpsc::unbounded_channel();

        state.handle_key(
            KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
            &tx,
        );

        assert!(state.execution_steps.is_empty());
    }

    // --- a call the model wrote as text ------------------------------------------------------

    #[test]
    fn retracting_takes_the_streamed_json_off_the_screen() {
        let mut state = AppState::new();
        state.messages.push(ChatMessage::User("liste".to_string()));
        // The call reaches the screen chunk by chunk, before anything can tell it is a call.
        state.handle_agent_update(AgentUpdate::ResponseChunk(
            r#"{"name": "list_dir", "parameters": {}}"#.to_string(),
        ));
        assert_eq!(state.messages.len(), 2);

        state.handle_agent_update(AgentUpdate::RetractResponse);

        assert_eq!(state.messages.len(), 1, "got {:?}", state.messages);
        assert!(matches!(&state.messages[0], ChatMessage::User(t) if t == "liste"));
    }

    #[test]
    fn retracting_never_reaches_past_the_reply_into_the_conversation() {
        let mut state = AppState::new();
        state.messages.push(ChatMessage::User("liste".to_string()));
        state.handle_agent_update(AgentUpdate::RetractResponse);

        // Nothing was streamed, so there is nothing to take back — and the user's own turn is
        // never the thing being retracted.
        assert_eq!(state.messages.len(), 1);
    }

    // --- resuming a session -----------------------------------------------------------------

    #[test]
    fn a_resumed_session_is_put_back_on_screen() {
        use crate::channels::TranscriptEntry as Entry;

        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::History(vec![
            Entry::User("liste".to_string()),
            Entry::Tool {
                name: "list_dir".to_string(),
                ok: true,
            },
            Entry::Agent("sao estes".to_string()),
        ]));

        // The whole complaint: "Resumed session ... with 3 message(s)" over an empty transcript.
        assert_eq!(state.messages.len(), 2);
        assert!(matches!(&state.messages[0], ChatMessage::User(t) if t == "liste"));
        assert!(matches!(&state.messages[1], ChatMessage::Agent(t) if t == "sao estes"));

        // The tool sits between the two, as it did when it ran.
        assert_eq!(state.execution_steps.len(), 1);
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Done);
        assert_eq!(state.execution_steps[0].after, 1);
    }

    #[test]
    fn a_restored_failure_is_still_a_failure() {
        use crate::channels::TranscriptEntry as Entry;

        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::History(vec![Entry::Tool {
            name: "caatinga_deploy".to_string(),
            ok: false,
        }]));

        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Failed);
        // A past failure is not this session's failure — the next turn starts clean.
        assert!(!state.execution_failed);
    }

    #[test]
    fn compaction_is_marked_where_it_cut() {
        use crate::channels::TranscriptEntry as Entry;

        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::History(vec![
            Entry::Compacted,
            Entry::User("depois".to_string()),
        ]));

        // Without a marker the conversation looks as though it simply began mid-thought.
        let first = format!("{:?}", state.messages[0]);
        assert!(first.contains("compacted"), "got {}", first);
    }

    #[test]
    fn restoring_twice_does_not_double_the_transcript() {
        use crate::channels::TranscriptEntry as Entry;

        let mut state = AppState::new();
        let history = vec![Entry::User("oi".to_string())];
        state.handle_agent_update(AgentUpdate::History(history.clone()));
        state.handle_agent_update(AgentUpdate::History(history));

        assert_eq!(state.messages.len(), 1);
    }

    // --- tool approval ----------------------------------------------------------------------

    fn awaiting_approval(
        tool: &str,
    ) -> (
        AppState,
        mpsc::UnboundedReceiver<crate::channels::ApprovalDecision>,
    ) {
        let mut state = AppState::new();
        let (tx, rx) = mpsc::unbounded_channel();
        state.approval_tx = Some(tx);
        state.handle_agent_update(AgentUpdate::Approval(crate::channels::ApprovalRequest {
            tool: tool.to_string(),
            detail: format!("{} → src/lib.rs", tool),
            scope: format!("{}:src/lib.rs", tool),
        }));
        (state, rx)
    }

    #[test]
    fn a_request_parks_the_prompt_without_writing_anything_down_yet() {
        let (state, _rx) = awaiting_approval("write_file");

        assert!(state.pending_approval.is_some());
        // The prompt carries the detail while it is up, and the decision records it afterwards.
        // A "requested" line here as well meant two transcript lines per approval, and the second
        // landed after the execution step it belonged to.
        assert!(state.messages.is_empty(), "got {:?}", state.messages);
    }

    #[test]
    fn the_decision_records_what_was_allowed_not_just_which_tool() {
        for (key, expected) in [
            (KeyCode::Char('y'), "Allowed write_file → src/lib.rs"),
            (KeyCode::Char('n'), "Declined write_file → src/lib.rs"),
        ] {
            let (mut state, _rx) = awaiting_approval("write_file");
            press(&mut state, key, KeyModifiers::NONE);

            // "Allowed write_file" does not answer the question someone comes back with, which is
            // what touched this file.
            let said = format!("{:?}", state.messages.last().unwrap());
            assert!(said.contains(expected), "got {}", said);
        }
    }

    #[test]
    fn y_allows_once_and_a_allows_for_the_session() {
        for (key, expected) in [
            (KeyCode::Char('y'), crate::channels::ApprovalDecision::Once),
            (KeyCode::Enter, crate::channels::ApprovalDecision::Once),
            (
                KeyCode::Char('a'),
                crate::channels::ApprovalDecision::Always,
            ),
            (KeyCode::Char('n'), crate::channels::ApprovalDecision::Deny),
            (KeyCode::Esc, crate::channels::ApprovalDecision::Deny),
        ] {
            let (mut state, mut rx) = awaiting_approval("write_file");
            press(&mut state, key, KeyModifiers::NONE);

            assert_eq!(rx.try_recv().ok(), Some(expected), "key {:?}", key);
            assert!(state.pending_approval.is_none(), "key {:?}", key);
        }
    }

    // The one prompt in the app where guessing wrong writes to the user's files, so a stray key
    // must not count as either answer.
    #[test]
    fn an_unrecognised_key_answers_nothing() {
        let (mut state, mut rx) = awaiting_approval("write_file");

        for key in [KeyCode::Char('z'), KeyCode::Tab, KeyCode::Up] {
            press(&mut state, key, KeyModifiers::NONE);
        }

        assert!(rx.try_recv().is_err(), "a stray key decided something");
        assert!(state.pending_approval.is_some());
    }

    #[test]
    fn quitting_still_works_while_a_question_is_on_screen() {
        let (mut state, _rx) = awaiting_approval("caatinga_deploy");
        let (tx, _user_rx) = mpsc::unbounded_channel();

        // This prompt blocks a running turn, so an unquittable one would be a way to wedge the app.
        assert!(state.handle_key(
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &tx
        ));
    }

    #[test]
    fn the_question_outranks_the_palette() {
        let (mut state, mut rx) = awaiting_approval("write_file");
        state.palette_open = true;

        press(&mut state, KeyCode::Char('n'), KeyModifiers::NONE);

        assert_eq!(
            rx.try_recv().ok(),
            Some(crate::channels::ApprovalDecision::Deny),
            "the palette swallowed an answer the agent is blocked on"
        );
    }

    #[test]
    fn the_decision_is_written_into_the_transcript() {
        let (mut state, _rx) = awaiting_approval("write_file");
        press(&mut state, KeyCode::Char('a'), KeyModifiers::NONE);

        let last = format!("{:?}", state.messages.last().unwrap());
        assert!(last.contains("rest of this session"), "got {}", last);
    }

    // --- interrupting a turn ---------------------------------------------------------------

    #[test]
    fn escape_stops_a_turn_in_flight() {
        let mut state = AppState::new();
        state.status = AppStatus::Working;

        press(&mut state, KeyCode::Esc, KeyModifiers::NONE);

        assert!(state.cancel.is_raised());
        assert_eq!(state.current_activity.as_deref(), Some("Interrupting..."));
    }

    #[test]
    fn escape_while_idle_stops_nothing() {
        let mut state = AppState::new();
        state.status = AppStatus::Ready;

        press(&mut state, KeyCode::Esc, KeyModifiers::NONE);

        assert!(
            !state.cancel.is_raised(),
            "a stale flag would cancel the next turn the moment it was sent"
        );
    }

    // Esc has two jobs and the popup is the nearer one; cancelling the turn underneath it would
    // leave the popup open and the turn dead, which is neither of the things the user asked for.
    #[test]
    fn escape_closes_the_popup_before_it_stops_the_turn() {
        let mut state = AppState::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        state.status = AppStatus::Working;
        press(&mut state, KeyCode::Char('/'), KeyModifiers::NONE);
        type_str_with_tx(&mut state, "he", &tx);

        press(&mut state, KeyCode::Esc, KeyModifiers::NONE);
        assert!(!state.autocomplete_active);
        assert!(!state.cancel.is_raised());

        press(&mut state, KeyCode::Esc, KeyModifiers::NONE);
        assert!(state.cancel.is_raised());
    }

    #[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) => 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);
        // A phase is closed by whatever comes after it...
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Done);
        assert_eq!(state.execution_steps[2].state, ExecutionStepState::Running);

        // ...but a tool call is not. It stays open until its outcome is known: text arriving is
        // not evidence that the tool underneath it succeeded, and treating it as such is what made
        // a failed call indistinguishable from a successful one.
        state.handle_agent_update(AgentUpdate::ResponseChunk("done".to_string()));
        assert_eq!(state.execution_steps[2].state, ExecutionStepState::Running);

        state.handle_agent_update(AgentUpdate::ToolFinished {
            name: "caatinga_deploy".to_string(),
            ok: true,
        });
        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());
    }

    // --- a step reaching a terminal state ---------------------------------------------------

    fn running_tool(tool: &str) -> AppState {
        let mut state = AppState::new();
        state.handle_agent_update(AgentUpdate::Status(format!("Using tool: {}", tool)));
        state
    }

    #[test]
    fn a_tool_that_succeeds_settles_as_done() {
        let mut state = running_tool("read_file");
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Running);

        state.handle_agent_update(AgentUpdate::ToolFinished {
            name: "read_file".to_string(),
            ok: true,
        });
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Done);
    }

    // The regression this whole change is about: a failure reached the session log and the model,
    // and the trace went on showing the step exactly as it showed a successful one.
    #[test]
    fn a_tool_that_fails_settles_as_failed() {
        let mut state = running_tool("caatinga_deploy");

        state.handle_agent_update(AgentUpdate::ToolFinished {
            name: "caatinga_deploy".to_string(),
            ok: false,
        });
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Failed);
    }

    // A failed tool is not a failed turn — the model is told and usually recovers.
    #[test]
    fn a_failed_tool_does_not_condemn_the_turn() {
        let mut state = running_tool("read_file");
        state.handle_agent_update(AgentUpdate::ToolFinished {
            name: "read_file".to_string(),
            ok: false,
        });

        assert!(!state.execution_failed);
        state.handle_agent_update(AgentUpdate::ResponseEnd);
        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Failed);
    }

    #[test]
    fn an_outcome_settles_its_own_step_not_whichever_is_last() {
        let mut state = running_tool("grep");
        state.handle_agent_update(AgentUpdate::Status("Using tool: read_file".to_string()));

        // `grep` finishing must not be recorded against `read_file`, which is still going.
        state.handle_agent_update(AgentUpdate::ToolFinished {
            name: "grep".to_string(),
            ok: false,
        });

        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Failed);
        assert_eq!(state.execution_steps[1].state, ExecutionStepState::Running);
    }

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

        assert_eq!(state.execution_steps[0].state, ExecutionStepState::Waiting);
    }

    // A turn that ends while a step is parked on a question must not leave it parked forever.
    #[test]
    fn a_waiting_step_is_settled_when_the_turn_ends() {
        let mut state = running_tool("write_file");
        state.handle_agent_update(AgentUpdate::Approval(crate::channels::ApprovalRequest {
            tool: "write_file".to_string(),
            detail: "write_file → src/lib.rs".to_string(),
            scope: "write_file:src/lib.rs".to_string(),
        }));

        state.handle_agent_update(AgentUpdate::ResponseEnd);
        assert!(
            !state.execution_steps[0].state.is_open(),
            "left open: {:?}",
            state.execution_steps[0].state
        );
    }

    #[test]
    fn clearing_the_chat_clears_the_trace_under_it() {
        let mut state = running_tool("caatinga_build");
        state.handle_agent_update(AgentUpdate::ToolFinished {
            name: "caatinga_build".to_string(),
            ok: true,
        });

        let (tx, _rx) = mpsc::unbounded_channel();
        state.handle_command("/clear", &tx);

        assert!(
            state.execution_steps.is_empty(),
            "the last turn's steps outlived the words 'Chat cleared.'"
        );
    }
}