mermaid-cli 0.12.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
Documentation
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
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
//! The pure reducer: `fn update(State, Msg) -> (State, Vec<Cmd>)`.
//!
//! Four rules — every future change to this file is checked against them:
//!
//!   1. **No I/O, no async.** The function is `sync`, never awaits,
//!      never opens files. All side-effects are returned as `Cmd`.
//!   2. **No wildcards.** The `match msg` is exhaustive. Adding a new
//!      `Msg` variant is a compile error until every arm is handled.
//!   3. **Stale-filter first.** Any `Msg` carrying a `TurnId` that
//!      doesn't match `state.turn.id()` is dropped without state
//!      change. This is the architectural safeguard that the previous
//!      `check_interrupt` polling tried to enforce by convention.
//!   4. **Cancellation is explicit.** The way to stop in-flight work is
//!      `Cmd::CancelScope(turn)`, which cancels the turn's token so every
//!      scoped task unwinds at its next `.await`. The sole `JoinHandle::abort`
//!      is in `providers::tool::exec`: the detachable command driver is a raw
//!      (non-scoped) task by design — Ctrl+B lets it outlive the turn — so on
//!      Esc-cancel it's aborted explicitly after its process tree is killed.
//!
//! Internal split:
//!
//!   - `update_step(State, Msg) -> (State, Vec<Cmd>)` — a single
//!     reducer call. Pure, deterministic, exhaustive match.
//!   - `update(State, Msg) -> (State, Vec<Cmd>)` — runs a step,
//!     then drains `state.ui.pending_msgs` in a bounded loop so
//!     handlers can enqueue follow-up events (Enter-on-slash,
//!     queued-message auto-submit) without self-invoking the
//!     reducer.

use crate::constants::{DEFAULT_MAX_TOKENS, DEFAULT_TEMPERATURE};
use crate::models::{ChatMessage, MessageRole};
use crate::prompts::get_system_prompt;
use crate::runtime::TaskStatus;

use super::cmd::{ChatRequest, Cmd};
use super::compaction::{
    CompactionArchive, CompactionPolicy, CompactionRequest, CompactionResult, CompactionTrigger,
    context_exceeds_hard_limit, should_auto_compact,
};
use super::ids::TurnId;
use super::msg::{KeyCode, KeyMods, Msg, Paste, SlashCmd};
use super::state::{
    GenPhase, McpServerEntry, McpServerStatus, State, StatusKind, TokenUsageTotals, ToolOutcome,
    TurnState, UiMode,
};
use super::transition::{
    action_display_for, commit_assistant_message, fill_outcome, start_generating,
    tool_result_messages, try_complete_outcomes,
};
use super::{COMMAND_GROUPS, COMMAND_REGISTRY};

/// Cap on how many queued follow-up messages get drained per
/// external `update()` call. Arms typically enqueue zero or one
/// follow-up; this cap catches runaway loops from future arms that
/// might enqueue unboundedly.
const MAX_PENDING_DRAIN: usize = 16;

/// The public reducer entry point. Runs one `update_step` for the
/// incoming `msg`, then drains any follow-up `Msg`s the handler
/// pushed onto `state.ui.pending_msgs`. All emitted `Cmd`s coalesce
/// into the returned vector.
pub fn update(mut state: State, msg: Msg) -> (State, Vec<Cmd>) {
    let (new_state, mut cmds) = update_step(state, msg);
    state = new_state;
    let mut depth = 0usize;
    while let Some(follow) = state.ui.pending_msgs.pop_front() {
        if depth >= MAX_PENDING_DRAIN {
            tracing::warn!(
                max = MAX_PENDING_DRAIN,
                remaining = state.ui.pending_msgs.len(),
                "reducer: pending_msgs drain cap hit — follow-ups dropped this tick"
            );
            state.ui.pending_msgs.clear();
            break;
        }
        let (s, c) = update_step(state, follow);
        state = s;
        cmds.extend(c);
        depth += 1;
    }
    (state, cmds)
}

/// Single-step reducer: one `Msg` in, new `State` + `Cmd`s out.
/// Callers interested in re-entry (queued follow-up messages) go
/// through `update()`; this function returns after a single pass.
pub fn update_step(mut state: State, msg: Msg) -> (State, Vec<Cmd>) {
    let mut cmds = Vec::new();

    // Stale-event filter: if this is an effect result for a turn we're
    // no longer on, drop without state change. `turn_id()` returns
    // `None` for non-turn-scoped messages, which short-circuits the
    // check (Some(id) != None).
    if let Some(event_turn) = msg.turn_id()
        && !state.turn.accepts(event_turn)
    {
        tracing::trace!(
            event_turn = %event_turn,
            active_turn = ?state.turn.id(),
            kind = ?msg.kind(),
            "reducer: dropped stale message"
        );
        return (state, cmds);
    }

    match msg {
        // ── User intent ─────────────────────────────────────────────
        Msg::Key(key) => {
            handle_key(&mut state, &mut cmds, key.code, key.modifiers);
        },
        Msg::Paste(paste) => {
            handle_paste(&mut state, &mut cmds, paste);
        },
        Msg::SubmitPrompt {
            text,
            attachment_ids,
        } => {
            handle_submit_prompt(&mut state, &mut cmds, text, &attachment_ids);
        },
        Msg::Slash(cmd) => {
            handle_slash(&mut state, &mut cmds, cmd);
        },
        Msg::CancelTurn => {
            handle_cancel_turn(&mut state, &mut cmds);
        },
        Msg::ConfirmAccepted => {
            handle_confirm_accepted(&mut state, &mut cmds);
        },
        Msg::ConfirmDeclined => {
            state.confirm = None;
        },
        Msg::Quit => {
            request_exit(&mut state, &mut cmds);
        },
        Msg::RuntimeSignal(signal) => {
            state.runtime.record_signal(signal);
            request_exit(&mut state, &mut cmds);
        },

        // ── Streaming ───────────────────────────────────────────────
        Msg::StreamText { turn, chunk } => {
            if let TurnState::Generating {
                id,
                partial_text,
                phase,
                tokens,
                ..
            } = &mut state.turn
                && *id == turn
            {
                partial_text.push_str(&chunk);
                *phase = GenPhase::Streaming;
                // Rough token estimate — actual count comes in `Done`.
                *tokens = partial_text.len() / 4;
            }
        },
        Msg::StreamReasoning { turn, chunk } => {
            if let TurnState::Generating {
                id,
                partial_reasoning,
                phase,
                thinking_signature,
                ..
            } = &mut state.turn
                && *id == turn
            {
                partial_reasoning.push_str(&chunk.text);
                *phase = GenPhase::Thinking;
                if let Some(sig) = chunk.signature {
                    *thinking_signature = Some(sig);
                }
            }
        },
        Msg::StreamToolCall { turn, call } => {
            handle_stream_tool_call(&mut state, turn, call);
        },
        Msg::ContextUsageEstimated { turn, snapshot } => {
            if state.turn.accepts(turn) {
                state.session.context_usage = Some(snapshot);
            }
        },
        Msg::BuiltinToolSchemaTokens(tokens) => {
            state.runtime.builtin_tool_schema_tokens = tokens;
        },
        Msg::CompactionFinished { turn, result } => {
            handle_compaction_finished(&mut state, &mut cmds, turn, result);
        },
        Msg::CompactionFailed {
            turn,
            trigger,
            message,
            kind,
        } => {
            handle_compaction_failed(&mut state, turn, trigger, message, kind);
        },
        Msg::StreamDone {
            turn,
            usage,
            thinking_signature,
            stop_reason,
        } => {
            handle_stream_done(
                &mut state,
                &mut cmds,
                turn,
                usage,
                thinking_signature,
                stop_reason,
            );
        },
        Msg::UpstreamError { turn, error } => {
            handle_upstream_error(&mut state, turn, error);
        },
        Msg::TurnCancelled(turn) => {
            handle_turn_cancelled(&mut state, turn);
        },

        // ── Tools ───────────────────────────────────────────────────
        Msg::ToolStarted {
            turn: _,
            call_id: _,
        } => {
            // Informational — render layer derives spinner state from
            // `outcomes[i].is_none()`, so no state change needed yet.
        },
        Msg::ToolProgress {
            turn,
            call_id: _,
            event,
        } => {
            handle_tool_progress(&mut state, &mut cmds, turn, event);
        },
        Msg::ToolFinished {
            turn,
            call_id,
            outcome,
        } => {
            handle_tool_finished(&mut state, &mut cmds, turn, call_id, outcome);
        },
        Msg::ApprovalRequested {
            turn,
            call_id,
            tool,
            risk,
            kind,
            prompt,
            allowlist_scope,
        } => {
            // Drop approval requests for a turn that's already being cancelled:
            // its tool task is unwinding, so surfacing (and parking on) a modal
            // would outlive the turn (#74). The stale-filter lets a same-id
            // `Cancelling` turn through, so guard the state explicitly here.
            if matches!(state.turn, TurnState::Cancelling { .. }) {
                return (state, cmds);
            }
            // Enqueue a modal; the parked tool task waits until the user
            // answers (key handler → Cmd::ResolveApproval). FIFO so multiple
            // gated tools in one turn are shown one at a time.
            state
                .pending_approval
                .push_back(super::state::PendingApproval {
                    turn,
                    call_id,
                    tool,
                    risk,
                    kind,
                    prompt,
                    allowlist_scope,
                    selected_option: 0,
                });
        },

        // ── MCP ─────────────────────────────────────────────────────
        // F5: upsert semantics. State::new seeds entries for configured
        // servers in `Starting` status, so these handlers normally find
        // an existing entry to update. But a server discovered at
        // runtime (hypothetical future path) should still land in the
        // map — insert rather than silently drop.
        Msg::McpServerReady { name, tools } => {
            state
                .mcp
                .servers
                .entry(name)
                .and_modify(|e| {
                    e.status = McpServerStatus::Ready;
                    e.tools = tools.clone();
                })
                .or_insert_with(|| McpServerEntry {
                    config: crate::app::McpServerConfig {
                        command: String::new(),
                        args: Vec::new(),
                        env: std::collections::HashMap::new(),
                    },
                    status: McpServerStatus::Ready,
                    tools,
                });
        },
        Msg::McpServerErrored { name, reason } => {
            let status = McpServerStatus::Errored {
                reason: reason.clone(),
            };
            state
                .mcp
                .servers
                .entry(name.clone())
                .and_modify(|e| e.status = status.clone())
                .or_insert_with(|| McpServerEntry {
                    config: crate::app::McpServerConfig {
                        command: String::new(),
                        args: Vec::new(),
                        env: std::collections::HashMap::new(),
                    },
                    status,
                    tools: Vec::new(),
                });
            push_system(
                &mut state,
                &mut cmds,
                format!("MCP server {} errored: {}", name, reason),
            );
        },
        Msg::McpServerStopped { name } => {
            if let Some(entry) = state.mcp.servers.get_mut(&name) {
                entry.status = McpServerStatus::Stopped;
            }
        },

        // ── Persistence / misc ─────────────────────────────────────
        Msg::InstructionsChanged(loaded) => {
            state.instructions = loaded;
        },
        Msg::MemoryChanged(loaded) => {
            state.memory = loaded;
        },
        Msg::SessionSaved => {
            // Silent. Reducer already committed; save is just durability.
        },
        Msg::ConversationLoaded(history) => {
            // If a turn was in flight when the user loaded another conversation
            // (`/load` mid-generation), cancel its scope first. Otherwise we
            // overwrite `state.turn` to `Idle` below and lose the only handle —
            // the turn's CancellationToken + JoinSet — that could stop the
            // running model call and tool tasks, orphaning them uncancellable;
            // their parked approval requests could never be answered either (#2).
            if let Some(id) = state.turn.id() {
                cmds.push(Cmd::CancelScope(id));
                state.pending_approval.clear();
            }
            state.session.conversation = history;
            state.turn = TurnState::Idle;
            state.ui.mode = UiMode::EditingInput;
            emit_title_if_changed(&mut state, &mut cmds);
        },
        Msg::ConversationsListed(candidates) => {
            if let UiMode::ConversationList { .. } = state.ui.mode {
                state.ui.mode = UiMode::ConversationList {
                    candidates,
                    cursor: 0,
                };
            }
            // If the user already navigated away (Esc before the
            // list landed), the event silently drops.
        },
        Msg::RuntimeTasksListed(tasks) => {
            state
                .session
                .append(ChatMessage::system(tasks_text(&tasks)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::RuntimeTaskLoaded { task, events } => {
            state.session.append(ChatMessage::system(task_detail_text(
                task.as_ref(),
                &events,
            )));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::RuntimeProcessesListed(processes) => {
            state
                .session
                .append(ChatMessage::system(processes_text(&processes)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::RuntimeText(text) => {
            state.session.append(ChatMessage::system(text));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::RuntimeApprovalsListed(approvals) => {
            state
                .session
                .append(ChatMessage::system(approvals_text(&approvals)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::RuntimeCheckpointsListed(checkpoints) => {
            state
                .session
                .append(ChatMessage::system(checkpoints_text(&checkpoints)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::RuntimePluginsListed(plugins) => {
            state
                .session
                .append(ChatMessage::system(plugins_text(&plugins)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        Msg::ModelPullFinished { model } => {
            push_system(&mut state, &mut cmds, format!("Pulled {}", model));
        },
        Msg::ModelPullProgress(_line) => {
            // Pull progress used to stream into the status banner. With the
            // banner gone we don't surface line-by-line progress (it would spam
            // the transcript); the final ModelPullFinished posts one line.
        },

        // ── Housekeeping ────────────────────────────────────────────
        Msg::Tick => {
            // No state change here. The driver stamps `state.now` before every
            // tick (Cause 3), and render derives the elapsed-time spinner from
            // `state.now` — so a 60 Hz Tick advances the display without the
            // reducer or render ever reading the wall clock.
        },
        Msg::StatusDismiss => {
            state.status = None;
        },
        Msg::Resize { .. } => {
            // Render layer recomputes layout from the new area — no
            // reducer state depends on raw terminal dimensions.
        },
        Msg::MouseScroll { delta } => {
            // F13: accumulate into a counter. Render layer diffs
            // against its last-seen value and applies the resulting
            // delta to ChatState. `saturating_add` never overflows.
            state.ui.mouse_scroll_accum = state.ui.mouse_scroll_accum.saturating_add(delta as i32);
        },
        Msg::TransientStatus {
            text,
            kind: _,
            dismiss_ms: _,
        } => {
            // Generic async feedback from effect handlers ("clipboard is empty",
            // "config saved", etc.). Routed into the chat transcript instead of
            // the old transient banner above the input.
            push_system(&mut state, &mut cmds, text);
        },
        Msg::OpenImageAt {
            message_index,
            image_index,
        } => {
            handle_open_image_at(&mut state, &mut cmds, message_index, image_index);
        },
        Msg::CopySelection(text) => {
            // The selection itself lives in the render layer; the main loop
            // resolves it to text and hands it here so the clipboard write is an
            // `update()`-emitted Cmd (recorded for replay) rather than an
            // out-of-band dispatch (#18).
            if !text.is_empty() {
                cmds.push(Cmd::CopyToClipboard(text));
            }
        },
    }

    (state, cmds)
}

/// Emit `Cmd::SetTerminalTitle` iff the derived title changed since
/// the last emission. Called from arms that actually mutate
/// `state.session.conversation.title` (SubmitPrompt, ConversationLoaded,
/// ConfirmAccepted → ClearConversation) — never at the tail of every
/// update() so `Tick`/resize/etc. stay free.
fn emit_title_if_changed(state: &mut State, cmds: &mut Vec<Cmd>) {
    let current = state.session.conversation.title.clone();
    if state.ui.last_title_dispatched.as_deref() != Some(current.as_str()) {
        cmds.push(Cmd::SetTerminalTitle(format!("mermaid - {}", current)));
        state.ui.last_title_dispatched = Some(current);
    }
}

// ─── helpers ────────────────────────────────────────────────────────

fn handle_key(state: &mut State, cmds: &mut Vec<Cmd>, code: KeyCode, mods: KeyMods) {
    // Ctrl+C is the hard "leave the TUI" path. If work is active,
    // emit a cancellation first so shutdown does not wait on a live
    // provider/tool scope before returning the terminal.
    if mods.ctrl && code == KeyCode::Char('c') {
        request_exit(state, cmds);
        return;
    }

    // Ctrl+B: send a running foreground command to the background (it keeps
    // running as a `/processes` entry) instead of waiting on it. Only
    // meaningful while tools are executing; a swallowed no-op otherwise.
    if mods.ctrl && code == KeyCode::Char('b') {
        if let TurnState::ExecutingTools { id, .. } = &state.turn {
            cmds.push(Cmd::BackgroundScope(*id));
        }
        return;
    }

    // Inline approval modal: while a tool awaits approval the prompt is
    // exclusive. Direct keys resolve immediately — 1/y approve · 2/a approve +
    // don't-ask-again · 3/n/Esc deny. Or move the highlight with ↑/↓ and press
    // Enter on it. Sits ABOVE the Esc-cancel guard so Esc denies just this tool
    // (keeping the turn alive) rather than cancelling the whole turn. Any other
    // key is swallowed. Resolving emits `Cmd::ResolveApproval`, which unblocks
    // the parked tool task via the broker.
    if !state.pending_approval.is_empty() {
        use crate::domain::ApprovalChoice;
        // Content-bearing external tools are non-allowlistable: the gate signals
        // this with an empty allowlist scope, and the modal then omits the
        // middle "approve always" option (#6, #31). Layout:
        //   allowlistable:     0 = Yes, 1 = Yes-always, 2 = No
        //   non-allowlistable: 0 = Yes,                 1 = No
        let allowlistable = state
            .pending_approval
            .front()
            .map(|i| !i.allowlist_scope.is_empty())
            .unwrap_or(false);
        let option_count = if allowlistable { 3 } else { 2 };
        let choice_for = |idx: usize| match (allowlistable, idx) {
            (true, 0) | (false, 0) => ApprovalChoice::Approve,
            (true, 1) => ApprovalChoice::ApproveAlways,
            _ => ApprovalChoice::Deny,
        };
        // Copy the current highlight out so the ↑/↓ arms can take a fresh
        // mutable borrow without conflicting.
        let selected = state
            .pending_approval
            .front()
            .map(|i| i.selected_option)
            .unwrap_or(0);
        let choice = match code {
            KeyCode::Char('1') | KeyCode::Char('y') | KeyCode::Char('Y') => {
                Some(ApprovalChoice::Approve)
            },
            // 'a'/'A' and '2' select approve-always only when allowlistable;
            // when not, '2' is the (second, final) "No" option.
            KeyCode::Char('a') | KeyCode::Char('A') if allowlistable => {
                Some(ApprovalChoice::ApproveAlways)
            },
            KeyCode::Char('2') => Some(if allowlistable {
                ApprovalChoice::ApproveAlways
            } else {
                ApprovalChoice::Deny
            }),
            KeyCode::Char('3') | KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Escape => {
                Some(ApprovalChoice::Deny)
            },
            KeyCode::Enter => Some(choice_for(selected)),
            KeyCode::Up => {
                if let Some(front) = state.pending_approval.front_mut() {
                    front.selected_option = selected.saturating_sub(1);
                }
                None
            },
            KeyCode::Down => {
                if let Some(front) = state.pending_approval.front_mut() {
                    front.selected_option = (selected + 1).min(option_count - 1);
                }
                None
            },
            _ => None,
        };
        if let Some(decision) = choice
            && let Some(call_id) = state.pending_approval.front().map(|i| i.call_id)
        {
            state.pending_approval.pop_front();
            cmds.push(Cmd::ResolveApproval { call_id, decision });
        }
        return;
    }

    // Pending confirmation modal (e.g. `/clear`): y/Enter accepts, n/Esc
    // declines. (This handler — and the render side — were missing, so the
    // confirmation was previously inert.)
    if state.confirm.is_some() {
        match code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                handle_confirm_accepted(state, cmds);
            },
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Escape => {
                state.confirm = None;
            },
            _ => {},
        }
        return;
    }

    // Esc interrupts active work by cancelling the current turn. It must NEVER
    // exit mermaid — only Ctrl+C (or `/quit`) does that. A second Esc while the
    // turn is already cancelling is a no-op: the cancellation is underway, and
    // Ctrl+C is the escalation path if it ever wedges. (Previously a second Esc
    // mid-cancel force-exited, which booted users out unexpectedly and could
    // leave a backgrounded process holding the terminal.) When idle, Esc falls
    // through to the palette/input/focus handlers below.
    if mods.is_empty() && code == KeyCode::Escape && state.is_busy() {
        if !matches!(state.turn, TurnState::Cancelling { .. }) {
            handle_cancel_turn(state, cmds);
        }
        return;
    }

    // Ctrl+D on empty input quits.
    if mods.ctrl && code == KeyCode::Char('d') && state.ui.input_buffer.is_empty() {
        request_exit(state, cmds);
        return;
    }

    // Ctrl+V: read the system clipboard and paste its contents. Gate
    // on `EditingInput` + no confirmation modal so the palette and
    // conversation-list picker don't swallow the keystroke. The
    // actual clipboard read happens off-thread in the effect runner
    // (xclip / wl-paste / pngpaste / PowerShell can block for
    // hundreds of ms on macOS); result comes back as
    // `Msg::Paste(Image|Text)` or `Msg::TransientStatus` on failure.
    if mods.ctrl
        && code == KeyCode::Char('v')
        && matches!(state.ui.mode, UiMode::EditingInput)
        && state.confirm.is_none()
    {
        cmds.push(Cmd::ReadClipboard);
        return;
    }

    // Alt+T cycles reasoning depth. Persists per-model so cycling on
    // Sonnet doesn't bleed into the next session with Ollama.
    if mods.alt && code == KeyCode::Char('t') {
        let next = cycle_reasoning(state.session.reasoning);
        state.session.reasoning = next;
        cmds.push(Cmd::PersistReasoningFor {
            model_id: state.session.model_id.clone(),
            level: next,
        });
        // The bottom status bar already shows the new reasoning level — no banner.
        return;
    }

    // Shift+Tab cycles the safety mode (read-only → ask → auto → full-access).
    // Session-scoped: the `[safety]` config value stays the persistent default,
    // so a session never silently inherits a more-permissive mode from a
    // previous run. Mirrors the Alt+T reasoning cycle above.
    if code == KeyCode::BackTab {
        let next = cycle_safety(state.session.safety_mode);
        state.session.safety_mode = next;
        // The bottom status bar already shows the new safety mode — no banner.
        return;
    }

    // Conversation-list picker (UiMode::ConversationList): ↑/↓
    // navigate, Enter loads the highlighted session, Esc dismisses.
    if matches!(state.ui.mode, UiMode::ConversationList { .. }) {
        handle_conversation_list_key(state, cmds, code);
        return;
    }

    // Attachment-focus mode: keyboard navigates the bar.
    if state.ui.attachment_focused {
        handle_attachment_key(state, code);
        return;
    }

    // Slash-palette navigation — intercepts ↑/↓/Tab/Esc while the
    // input buffer opens with `/`. Enter falls through to the normal
    // handler below so the command actually dispatches.
    if state.ui.input_buffer.starts_with('/') {
        use crate::domain::slash_commands::filter_by_prefix;
        let typed = state
            .ui
            .input_buffer
            .trim_start_matches('/')
            .split_whitespace()
            .next()
            .unwrap_or("");
        let candidates = filter_by_prefix(typed);
        match code {
            KeyCode::Up => {
                let cur = state.ui.palette_cursor.unwrap_or(0);
                state.ui.palette_cursor = Some(cur.saturating_sub(1));
                return;
            },
            KeyCode::Down => {
                let max = candidates.len().saturating_sub(1);
                let cur = state.ui.palette_cursor.unwrap_or(0);
                state.ui.palette_cursor = Some((cur + 1).min(max));
                return;
            },
            KeyCode::Tab => {
                let sel = state.ui.palette_cursor.unwrap_or(0);
                if let Some(cmd) = candidates.get(sel) {
                    state.ui.input_buffer = format!("/{} ", cmd.name);
                    state.ui.input_cursor = state.ui.input_buffer.len();
                    state.ui.palette_cursor = Some(0);
                }
                return;
            },
            KeyCode::Escape => {
                state.ui.input_buffer.clear();
                state.ui.input_cursor = 0;
                state.ui.palette_cursor = None;
                return;
            },
            KeyCode::Enter if !mods.shift => {
                // Complete-then-execute: replace the command word with
                // the highlighted candidate (preserving any args the
                // user already typed), then fall through to the Enter
                // handler below so the command actually dispatches.
                let sel = state.ui.palette_cursor.unwrap_or(0);
                if let Some(cmd) = candidates.get(sel) {
                    let raw = state.ui.input_buffer.clone();
                    let after_slash = raw.trim_start_matches('/');
                    let rest = match after_slash.find(char::is_whitespace) {
                        Some(idx) => &after_slash[idx..],
                        None => "",
                    };
                    state.ui.input_buffer = format!("/{}{}", cmd.name, rest);
                    state.ui.input_cursor = state.ui.input_buffer.len();
                }
                // Fall through to the Enter handler below.
            },
            _ => {
                // Fall through to normal key handling (char/Backspace
                // update the filter; palette_cursor gets reset below).
            },
        }
    }

    // Enter submits the current input (or triggers the slash palette
    // pick). Shift+Enter is a newline for multi-line input. This arm
    // enqueues a synthetic `Msg` on `pending_msgs` rather than
    // invoking the dispatch directly — the outer `update()` drain
    // will run the follow-up with stale-filter + pending-msgs
    // guarantees intact.
    if code == KeyCode::Enter && !mods.shift {
        let buf = state.ui.input_buffer.trim().to_string();
        if buf.is_empty() {
            return;
        }
        if let Some(rest) = buf.strip_prefix('/') {
            let slash = crate::app::event_source::parse_slash_command(rest);
            state.ui.input_buffer.clear();
            state.ui.input_cursor = 0;
            state.ui.palette_cursor = None;
            state.ui.pending_msgs.push_back(Msg::Slash(slash));
        } else {
            let text = std::mem::take(&mut state.ui.input_buffer);
            state.ui.input_cursor = 0;
            let attachment_ids: Vec<u64> = state.ui.attachments.iter().map(|a| a.id).collect();
            state.ui.pending_msgs.push_back(Msg::SubmitPrompt {
                text,
                attachment_ids,
            });
        }
        return;
    }

    if mods.is_empty() || mods.shift {
        match code {
            KeyCode::Char(c) => {
                // Any text mutation resets history nav — the user's
                // typing wins over whatever historical entry was
                // on-screen.
                state.ui.input_history_cursor = None;
                state.ui.history_draft.clear();
                let pos = clamp_cursor(&state.ui.input_buffer, state.ui.input_cursor);
                state.ui.input_buffer.insert(pos, c);
                state.ui.input_cursor = clamp_cursor(&state.ui.input_buffer, pos + c.len_utf8());
                // Opening the palette, or editing its filter, resets
                // the cursor to the first candidate — stops stale
                // indices from pointing past the end of a shrinking
                // filter result.
                if state.ui.input_buffer.starts_with('/') {
                    state.ui.palette_cursor = Some(0);
                }
            },
            KeyCode::Backspace => {
                state.ui.input_history_cursor = None;
                state.ui.history_draft.clear();
                let pos = clamp_cursor(&state.ui.input_buffer, state.ui.input_cursor);
                if pos > 0 {
                    let new_pos = state.ui.input_buffer.floor_char_boundary(pos - 1);
                    state.ui.input_buffer.drain(new_pos..pos);
                    state.ui.input_cursor = new_pos;
                }
                if state.ui.input_buffer.starts_with('/') {
                    state.ui.palette_cursor = Some(0);
                } else {
                    state.ui.palette_cursor = None;
                }
            },
            KeyCode::Delete => {
                state.ui.input_history_cursor = None;
                state.ui.history_draft.clear();
                let pos = clamp_cursor(&state.ui.input_buffer, state.ui.input_cursor);
                if pos < state.ui.input_buffer.len() {
                    let next = state.ui.input_buffer.ceil_char_boundary(pos + 1);
                    state.ui.input_buffer.drain(pos..next);
                }
                if state.ui.input_buffer.starts_with('/') {
                    state.ui.palette_cursor = Some(0);
                } else {
                    state.ui.palette_cursor = None;
                }
            },
            KeyCode::Left => {
                let pos = clamp_cursor(&state.ui.input_buffer, state.ui.input_cursor);
                if pos > 0 {
                    state.ui.input_cursor = state.ui.input_buffer.floor_char_boundary(pos - 1);
                }
            },
            KeyCode::Right => {
                let pos = clamp_cursor(&state.ui.input_buffer, state.ui.input_cursor);
                if pos < state.ui.input_buffer.len() {
                    state.ui.input_cursor = state.ui.input_buffer.ceil_char_boundary(pos + 1);
                }
            },
            KeyCode::Home => state.ui.input_cursor = 0,
            KeyCode::End => state.ui.input_cursor = state.ui.input_buffer.len(),
            KeyCode::Up => {
                // Up precedence: attachment focus wins ONLY when the
                // input is empty AND attachments exist — otherwise
                // step back through input history.
                if state.ui.input_buffer.is_empty() && !state.ui.attachments.is_empty() {
                    state.ui.attachment_focused = true;
                    state.ui.attachment_selected = state
                        .ui
                        .attachment_selected
                        .min(state.ui.attachments.len() - 1);
                } else {
                    history_nav_back(state);
                }
            },
            KeyCode::Down => {
                history_nav_forward(state);
            },
            KeyCode::Escape => {
                state.ui.attachment_focused = false;
                // Also clear any in-progress history nav.
                state.ui.input_history_cursor = None;
                state.ui.history_draft.clear();
            },
            _ => {},
        }
    }
}

/// Handle keyboard input while the conversation-list picker is open.
/// Up/Down walk the cursor within the candidate list; Enter loads the
/// highlighted session; Esc dismisses.
fn handle_conversation_list_key(state: &mut State, cmds: &mut Vec<Cmd>, code: KeyCode) {
    let UiMode::ConversationList {
        ref candidates,
        ref mut cursor,
    } = state.ui.mode
    else {
        return;
    };
    match code {
        KeyCode::Up => {
            *cursor = cursor.saturating_sub(1);
        },
        KeyCode::Down => {
            let max = candidates.len().saturating_sub(1);
            if *cursor < max {
                *cursor += 1;
            }
        },
        KeyCode::Enter => {
            if let Some(summary) = candidates.get(*cursor) {
                cmds.push(Cmd::LoadConversation(summary.id.clone()));
            }
            // Mode flips on `Msg::ConversationLoaded` — leave as-is
            // until then so the user sees the list until the load
            // completes.
        },
        KeyCode::Escape => {
            state.ui.mode = UiMode::EditingInput;
        },
        _ => {},
    }
}

/// Handle keyboard input while the attachment bar has keyboard
/// focus. Returns without emitting Cmds; attachment removal happens
/// inline on state.ui.attachments.
fn handle_attachment_key(state: &mut State, code: KeyCode) {
    match code {
        KeyCode::Escape | KeyCode::Down => {
            state.ui.attachment_focused = false;
        },
        KeyCode::Left => {
            if !state.ui.attachments.is_empty() {
                state.ui.attachment_selected = state
                    .ui
                    .attachment_selected
                    .checked_sub(1)
                    .unwrap_or(state.ui.attachments.len() - 1);
            }
        },
        KeyCode::Right => {
            if !state.ui.attachments.is_empty() {
                state.ui.attachment_selected =
                    (state.ui.attachment_selected + 1) % state.ui.attachments.len();
            }
        },
        KeyCode::Delete | KeyCode::Backspace => {
            let idx = state.ui.attachment_selected;
            if idx < state.ui.attachments.len() {
                state.ui.attachments.remove(idx);
            }
            if state.ui.attachments.is_empty() {
                state.ui.attachment_focused = false;
                state.ui.attachment_selected = 0;
            } else if state.ui.attachment_selected >= state.ui.attachments.len() {
                state.ui.attachment_selected = state.ui.attachments.len() - 1;
            }
        },
        _ => {},
    }
}

/// Clamp a raw byte offset onto the nearest preceding char boundary
/// in `s`. Callers that trust their cursor is already valid can skip
/// this; paste + multi-step transformations should use it.
fn clamp_cursor(s: &str, pos: usize) -> usize {
    let capped = pos.min(s.len());
    s.floor_char_boundary(capped)
}

/// Step BACK through input history (Up arrow). The first press saves
/// the user's in-progress draft and replaces the buffer with the
/// newest history entry; subsequent presses step older.
fn history_nav_back(state: &mut State) {
    let history = &state.session.conversation.input_history;
    if history.is_empty() {
        return;
    }
    let next_cursor = match state.ui.input_history_cursor {
        None => {
            // First Up press — snapshot the current draft.
            state.ui.history_draft = state.ui.input_buffer.clone();
            0
        },
        Some(i) => (i + 1).min(history.len() - 1),
    };
    state.ui.input_history_cursor = Some(next_cursor);
    // `input_history` is a VecDeque with newest at the back. Index
    // 0 from the end = newest, 1 = one older, etc.
    let historical = history
        .iter()
        .rev()
        .nth(next_cursor)
        .cloned()
        .unwrap_or_default();
    state.ui.input_buffer = historical;
    state.ui.input_cursor = state.ui.input_buffer.len();
}

/// Step FORWARD through input history (Down arrow). Stepping past
/// the newest entry restores the user's original draft.
fn history_nav_forward(state: &mut State) {
    let Some(cursor) = state.ui.input_history_cursor else {
        return;
    };
    if cursor == 0 {
        // Back to the live draft.
        state.ui.input_buffer = std::mem::take(&mut state.ui.history_draft);
        state.ui.input_cursor = state.ui.input_buffer.len();
        state.ui.input_history_cursor = None;
        return;
    }
    let new_cursor = cursor - 1;
    state.ui.input_history_cursor = Some(new_cursor);
    let historical = state
        .session
        .conversation
        .input_history
        .iter()
        .rev()
        .nth(new_cursor)
        .cloned()
        .unwrap_or_default();
    state.ui.input_buffer = historical;
    state.ui.input_cursor = state.ui.input_buffer.len();
}

/// Cycle ReasoningLevel through every variant, wrapping around. Used
/// by Alt+T. Order matches the `Ord` impl so the cycle walks from
/// lowest to highest and back to None.
fn cycle_reasoning(current: crate::models::ReasoningLevel) -> crate::models::ReasoningLevel {
    use crate::models::ReasoningLevel as R;
    match current {
        R::None => R::Minimal,
        R::Minimal => R::Low,
        R::Low => R::Medium,
        R::Medium => R::High,
        R::High => R::XHigh,
        R::XHigh => R::Max,
        R::Max => R::None,
    }
}

/// Cycle SafetyMode by increasing permissiveness, wrapping around. Used by
/// Shift+Tab: ReadOnly → Ask → Auto → FullAccess → ReadOnly.
fn cycle_safety(current: crate::runtime::SafetyMode) -> crate::runtime::SafetyMode {
    use crate::runtime::SafetyMode as S;
    match current {
        S::ReadOnly => S::Ask,
        S::Ask => S::Auto,
        S::Auto => S::FullAccess,
        S::FullAccess => S::ReadOnly,
    }
}

fn handle_paste(state: &mut State, cmds: &mut Vec<Cmd>, paste: Paste) {
    match paste {
        Paste::Text(t) => {
            // Insert at the cursor and advance it, exactly like typing. Pasted
            // text and individual key presses MUST agree on position: on the
            // Windows console a paste arrives as a mix of coalesced `Paste`
            // chunks and stray `Char` key events, so appending to the end here
            // while keys insert at the cursor scrambled the result (uppercase
            // letters piled at the front).
            state.ui.input_history_cursor = None;
            state.ui.history_draft.clear();
            let pos = clamp_cursor(&state.ui.input_buffer, state.ui.input_cursor);
            state.ui.input_buffer.insert_str(pos, &t);
            state.ui.input_cursor = clamp_cursor(&state.ui.input_buffer, pos + t.len());
            if state.ui.input_buffer.starts_with('/') {
                state.ui.palette_cursor = Some(0);
            }
        },
        Paste::Image { bytes, format } => {
            let id = state.ids.tool_call.next();
            let temp_path = state
                .temp_dir
                .join(format!("mermaid-img-{}.{}", id, format));
            state.ui.attachments.push(super::state::Attachment {
                id,
                base64_data: base64::Engine::encode(
                    &base64::engine::general_purpose::STANDARD,
                    &bytes,
                ),
                temp_path: temp_path.clone(),
                size_bytes: bytes.len(),
                format: format.clone(),
            });
            cmds.push(Cmd::WriteImageToTemp {
                path: temp_path,
                bytes,
                format,
            });
        },
    }
}

fn handle_submit_prompt(
    state: &mut State,
    cmds: &mut Vec<Cmd>,
    text: String,
    attachment_ids: &[u64],
) {
    if text.trim().is_empty() {
        return;
    }
    // If a turn is already in flight, queue this message. The
    // reducer's StreamDone arm pops the oldest queued message and
    // auto-submits it.
    if !matches!(state.turn, TurnState::Idle) {
        state
            .ui
            .queued_messages
            .push_back(super::state::QueuedMessage {
                text,
                attachment_ids: attachment_ids.to_vec(),
            });
        return;
    }

    // Consume attachments by ID — ignoring stale IDs gracefully.
    let mut images: Vec<String> = Vec::new();
    state.ui.attachments.retain(|a| {
        if attachment_ids.contains(&a.id) {
            images.push(a.base64_data.clone());
            false
        } else {
            true
        }
    });
    // Submitting consumes attachments while the bar may still be focused;
    // re-clamp the selection so the render layer never indexes past the
    // shrunken list (mirrors the Delete-key path in handle_key).
    if state.ui.attachments.is_empty() {
        state.ui.attachment_focused = false;
        state.ui.attachment_selected = 0;
    } else if state.ui.attachment_selected >= state.ui.attachments.len() {
        state.ui.attachment_selected = state.ui.attachments.len() - 1;
    }

    let mut user_msg = ChatMessage::user(text.clone());
    if !images.is_empty() {
        user_msg = user_msg.with_images(images);
    }
    state.session.append(user_msg);
    state.session.conversation.add_to_input_history(text);
    state.ui.input_buffer.clear();

    // The first user message derives the conversation title; every
    // subsequent message keeps it. Either way, emit SetTerminalTitle
    // only on actual change.
    emit_title_if_changed(state, cmds);

    // Instructions/memory are kept fresh by the background config watcher (#45),
    // which stamps `state.instructions`/`state.memory` via
    // `Msg::InstructionsChanged`/`MemoryChanged`. The reducer reads them here as
    // injected data — no inline I/O — so `update()` stays pure and a recorded
    // session replays without re-statting the live filesystem.
    let turn = state.ids.fresh_turn();
    state.turn = start_generating(turn, std::time::SystemTime::from(state.now));
    cmds.push(Cmd::CallModel {
        turn,
        request: build_chat_request(state),
    });
}

fn handle_slash(state: &mut State, cmds: &mut Vec<Cmd>, cmd: SlashCmd) {
    match cmd {
        SlashCmd::Model(None) => {
            push_system(
                state,
                cmds,
                format!("Current model: {}", state.session.model_id),
            );
        },
        SlashCmd::Model(Some(new_model)) => {
            let pull_target = ollama_pull_target(&new_model);
            state.session.model_id = new_model.clone();
            state.runtime.set_model(&new_model);
            // The bottom status bar shows the new model — no banner.
            cmds.push(Cmd::PersistLastModel(new_model));
            if let Some(model) = pull_target {
                cmds.push(Cmd::PullOllamaModel { model });
            }
        },
        SlashCmd::Reasoning(None) => {
            push_system(
                state,
                cmds,
                format!("Reasoning: {}", state.session.reasoning.as_str()),
            );
        },
        SlashCmd::Reasoning(Some(level)) => {
            state.session.reasoning = level;
            cmds.push(Cmd::PersistReasoningFor {
                model_id: state.session.model_id.clone(),
                level,
            });
        },
        SlashCmd::Safety(None) => {
            push_system(
                state,
                cmds,
                format!(
                    "Safety: {} — options: read_only, ask, auto, full_access (Shift+Tab cycles)",
                    state.session.safety_mode.as_str()
                ),
            );
        },
        SlashCmd::Safety(Some(mode)) => {
            // Session-scoped (mirrors Shift+Tab) — not written to the config.
            state.session.safety_mode = mode;
            // The bottom status bar shows the new mode — no banner.
        },
        SlashCmd::VisibleReasoning(arg) => {
            match visible_reasoning_value(arg.as_deref(), state.ui.show_reasoning) {
                Ok(next) => {
                    state.ui.show_reasoning = next;
                    set_status(
                        state,
                        cmds,
                        if next {
                            "Visible reasoning: on"
                        } else {
                            "Visible reasoning: off"
                        },
                        StatusKind::Info,
                        3_000,
                    );
                },
                Err(usage) => {
                    set_status(state, cmds, usage, StatusKind::Warn, 4_000);
                },
            }
        },
        SlashCmd::Clear => {
            // Guard with a confirmation modal.
            state.confirm = Some(super::state::Confirmation {
                prompt: "Clear conversation history?".to_string(),
                accept_msg_token: super::state::ConfirmationTarget::ClearConversation,
            });
        },
        SlashCmd::Save(_name) => {
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Load(Some(id)) => {
            cmds.push(Cmd::LoadConversation(id));
        },
        SlashCmd::Load(None) | SlashCmd::List => {
            // Transition to the picker. Effect handler scans the
            // conversations directory; the reducer fills in
            // candidates when `Msg::ConversationsListed` arrives.
            state.ui.mode = UiMode::ConversationList {
                candidates: Vec::new(),
                cursor: 0,
            };
            cmds.push(Cmd::ListConversations);
        },
        SlashCmd::Usage => {
            state.session.append(ChatMessage::system(usage_text(state)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Context => {
            state
                .session
                .append(ChatMessage::system(context_text(state)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Compact(instructions) => {
            handle_manual_compact(state, cmds, instructions);
        },
        SlashCmd::Memory => {
            cmds.push(Cmd::ListMemory);
        },
        SlashCmd::Remember(Some(text)) => {
            cmds.push(Cmd::RememberMemory { text });
        },
        SlashCmd::Remember(None) => {
            set_status(
                state,
                cmds,
                "Usage: /remember <fact to remember>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Forget(Some(id)) => {
            cmds.push(Cmd::ForgetMemory { id });
        },
        SlashCmd::Forget(None) => {
            set_status(
                state,
                cmds,
                "Usage: /forget <memory name> (see /memory for names)",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::ConsolidateMemory => {
            cmds.push(Cmd::ConsolidateMemory {
                model_id: state.session.model_id.clone(),
            });
        },
        SlashCmd::Doctor => {
            state
                .session
                .append(ChatMessage::system(doctor_text(state)));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Tasks => {
            cmds.push(Cmd::ListRuntimeTasks { limit: 10 });
        },
        SlashCmd::Task(Some(id)) => {
            cmds.push(Cmd::LoadRuntimeTask { id });
        },
        SlashCmd::Task(None) => {
            set_status(state, cmds, "Usage: /task <id>", StatusKind::Info, 3_000);
        },
        SlashCmd::Pause(Some(id)) => {
            cmds.push(Cmd::UpdateRuntimeTaskStatus {
                id,
                status: TaskStatus::Blocked,
                final_report: Some("Paused from TUI".to_string()),
            });
        },
        SlashCmd::Pause(None) => {
            set_status(
                state,
                cmds,
                "Usage: /pause <task-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Resume(Some(id)) => {
            cmds.push(Cmd::UpdateRuntimeTaskStatus {
                id,
                status: TaskStatus::Running,
                final_report: None,
            });
        },
        SlashCmd::Resume(None) => {
            set_status(
                state,
                cmds,
                "Usage: /resume <task-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Cancel(Some(id)) => {
            cmds.push(Cmd::UpdateRuntimeTaskStatus {
                id,
                status: TaskStatus::Cancelled,
                final_report: Some("Cancelled from TUI".to_string()),
            });
        },
        SlashCmd::Cancel(None) => {
            if matches!(state.turn, TurnState::Idle) {
                set_status(
                    state,
                    cmds,
                    "No active turn to cancel.",
                    StatusKind::Info,
                    2_500,
                );
            } else {
                handle_cancel_turn(state, cmds);
            }
        },
        SlashCmd::Handoff(Some(id)) | SlashCmd::Report(Some(id)) => {
            cmds.push(Cmd::LoadRuntimeTask { id });
        },
        SlashCmd::Handoff(None) => {
            let text = format!(
                "Handoff report\n\n{}\n\n{}",
                context_text(state),
                usage_text(state)
            );
            state.session.append(ChatMessage::system(text));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Report(None) => {
            let text = format!(
                "Runtime report\n\n{}\n\n{}",
                context_text(state),
                usage_text(state)
            );
            state.session.append(ChatMessage::system(text));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Processes => {
            cmds.push(Cmd::ListRuntimeProcesses { limit: 10 });
        },
        SlashCmd::Logs(Some(id)) => {
            cmds.push(Cmd::ShowRuntimeProcessLogs { id });
        },
        SlashCmd::Logs(None) => {
            set_status(
                state,
                cmds,
                "Usage: /logs <process-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Stop(Some(id)) => {
            cmds.push(Cmd::StopRuntimeProcess { id });
        },
        SlashCmd::Stop(None) => {
            set_status(
                state,
                cmds,
                "Usage: /stop <process-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Restart(Some(id)) => {
            cmds.push(Cmd::RestartRuntimeProcess { id });
        },
        SlashCmd::Restart(None) => {
            set_status(
                state,
                cmds,
                "Usage: /restart <process-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Open(Some(target)) => {
            cmds.push(Cmd::OpenRuntimeTarget { target });
        },
        SlashCmd::Open(None) => {
            set_status(
                state,
                cmds,
                "Usage: /open <url|path|process-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Ports => {
            cmds.push(Cmd::ShowRuntimePorts);
        },
        SlashCmd::Approvals => {
            cmds.push(Cmd::ListRuntimeApprovals);
        },
        SlashCmd::Approve(Some(id)) => {
            cmds.push(Cmd::DecideRuntimeApproval {
                id,
                decision: "approved".to_string(),
            });
        },
        SlashCmd::Approve(None) => {
            set_status(
                state,
                cmds,
                "Usage: /approve <approval-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Deny(Some(id)) => {
            cmds.push(Cmd::DecideRuntimeApproval {
                id,
                decision: "denied".to_string(),
            });
        },
        SlashCmd::Deny(None) => {
            set_status(
                state,
                cmds,
                "Usage: /deny <approval-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Checkpoint(Some(paths)) => {
            let paths = paths
                .split_whitespace()
                .map(std::path::PathBuf::from)
                .collect::<Vec<_>>();
            cmds.push(Cmd::CreateRuntimeCheckpoint { paths });
        },
        SlashCmd::Checkpoint(None) => {
            set_status(
                state,
                cmds,
                "Usage: /checkpoint <path...>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Checkpoints => {
            cmds.push(Cmd::ListRuntimeCheckpoints { limit: 10 });
        },
        SlashCmd::Restore(Some(id)) => {
            cmds.push(Cmd::RestoreRuntimeCheckpoint { id });
        },
        SlashCmd::Restore(None) => {
            set_status(
                state,
                cmds,
                "Usage: /restore <checkpoint-id>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::Plugins => {
            cmds.push(Cmd::ListRuntimePlugins);
        },
        SlashCmd::ModelInfo(Some(model)) => {
            cmds.push(Cmd::ShowRuntimeModelInfo { model });
        },
        SlashCmd::ModelInfo(None) => {
            set_status(
                state,
                cmds,
                "Usage: /model-info <model>",
                StatusKind::Info,
                3_000,
            );
        },
        SlashCmd::CloudSetup => {
            // Cloud setup needs interactive stdin (rpassword) which
            // fights with ratatui's raw mode. The in-TUI command
            // points users at the `mermaid cloud-setup` subcommand
            // instead — clean separation of modes.
            push_system(
                state,
                cmds,
                "Run `mermaid cloud-setup` from your shell, then restart mermaid.",
            );
        },
        SlashCmd::Help => {
            state.session.append(ChatMessage::system(help_text()));
            cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
        },
        SlashCmd::Quit => {
            request_exit(state, cmds);
        },
        SlashCmd::Unknown(name) => {
            push_system(state, cmds, format!("Unknown command: /{}", name));
        },
    }
}

fn visible_reasoning_value(arg: Option<&str>, current: bool) -> Result<bool, &'static str> {
    match arg.map(str::trim).filter(|s| !s.is_empty()) {
        None | Some("toggle") => Ok(!current),
        Some("on") | Some("true") | Some("yes") | Some("show") => Ok(true),
        Some("off") | Some("false") | Some("no") | Some("hide") => Ok(false),
        Some(_) => Err("Usage: /visible-reasoning [on|off|toggle]"),
    }
}

/// Append a one-off system note to the chat transcript (and persist it).
///
/// This is where command feedback, errors, and query answers go now that the
/// transient status banner above the input is gone — they live in the
/// scrollable transcript instead of flashing in the spinner's row. The zone
/// above the input is reserved for the generation spinner alone.
fn push_system(state: &mut State, cmds: &mut Vec<Cmd>, text: impl Into<String>) {
    state.session.append(ChatMessage::system(text.into()));
    cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
}

/// Back-compat shim for the many call sites that used the old transient banner.
/// Routes their text into the chat transcript via [`push_system`]; the severity
/// and dismiss timeout no longer mean anything (there's no banner to color or
/// auto-clear).
fn set_status(
    state: &mut State,
    cmds: &mut Vec<Cmd>,
    text: impl Into<String>,
    _kind: StatusKind,
    _dismiss_ms: u64,
) {
    push_system(state, cmds, text);
}

fn ollama_pull_target(model_id: &str) -> Option<String> {
    let model_id = model_id.trim();
    if model_id.is_empty() {
        return None;
    }
    let (provider, model) = match model_id.split_once('/') {
        Some((provider, model)) => (provider, model),
        None => ("ollama", model_id),
    };
    if !provider.eq_ignore_ascii_case("ollama") {
        return None;
    }
    let model = model.trim();
    if model.is_empty() || model.ends_with(":cloud") {
        None
    } else {
        Some(model.to_string())
    }
}

fn handle_manual_compact(state: &mut State, cmds: &mut Vec<Cmd>, instructions: Option<String>) {
    if !matches!(state.turn, TurnState::Idle) {
        push_system(state, cmds, "Cannot compact while a turn is active.");
        return;
    }

    if state.session.messages().len() < 3 {
        push_system(state, cmds, "Not enough conversation history to compact.");
        return;
    }

    // Instructions/memory are kept fresh by the config watcher (#45); read as
    // injected data so the reducer does no I/O before building the request.
    let turn = state.ids.fresh_turn();
    state.turn = TurnState::Compacting {
        id: turn,
        started: std::time::SystemTime::from(state.now),
        trigger: CompactionTrigger::Manual,
    };
    // The live "Compacting…" status comes from the TurnState::Compacting status
    // line (the blue indicator); no separate gray status message — it was a
    // redundant duplicate. The completion receipt is set on CompactionFinished.
    cmds.push(Cmd::CompactConversation {
        turn,
        request: CompactionRequest::manual(build_chat_request(state), instructions),
    });
}

fn help_text() -> String {
    let mut lines = Vec::with_capacity(COMMAND_REGISTRY.len() + COMMAND_GROUPS.len() + 2);
    lines.push("Mermaid commands".to_string());
    lines.push(
        "Everyday commands are first; daemon/task/process commands are advanced runtime."
            .to_string(),
    );
    for group in COMMAND_GROUPS {
        lines.push(String::new());
        lines.push(format!("{}:", group.title()));
        for command in COMMAND_REGISTRY
            .iter()
            .filter(|command| command.group == *group)
        {
            let hint = command.arg_hint.unwrap_or("");
            let aliases = if command.aliases.is_empty() {
                String::new()
            } else {
                format!(" ({})", command.aliases.join(", "))
            };
            let suffix = if hint.is_empty() {
                String::new()
            } else {
                format!(" {}", hint)
            };
            lines.push(format!(
                "  /{}{}{} - {}",
                command.name, suffix, aliases, command.description
            ));
        }
    }
    lines.join("\n")
}

fn doctor_text(state: &State) -> String {
    let mut lines = Vec::new();
    lines.push("Mermaid Doctor".to_string());
    lines.push(format!("Project: {}", state.cwd.display()));
    lines.push(format!("Active model: {}", state.session.model_id));
    lines.push(format!("Reasoning: {}", state.session.reasoning.as_str()));
    lines.push(format!(
        "Provider: {} / {}",
        state.runtime.provider_capabilities.provider, state.runtime.provider_capabilities.model
    ));
    lines.push(format!(
        "Model capabilities: tools={}, vision={}, reasoning={}, context={}",
        state.runtime.provider_capabilities.supports_tools,
        state.runtime.provider_capabilities.supports_vision,
        state.runtime.provider_capabilities.reasoning,
        state
            .runtime
            .provider_capabilities
            .max_context_tokens
            .map(|n| n.to_string())
            .unwrap_or_else(|| "unknown".to_string())
    ));
    lines.push(format!(
        "Safety: mode={}, checkpoint_on_mutation={}",
        safety_mode_name(state.settings.safety.mode),
        state.settings.safety.checkpoint_on_mutation
    ));
    lines.push(format!(
        "Prompt: {}",
        if state.settings.prompt.is_customized() {
            "customized for this invocation"
        } else {
            "default"
        }
    ));
    match &state.instructions {
        Some(instructions) => lines.push(format!(
            "Project instructions: {} bytes from {} source(s){}",
            instructions.byte_len,
            instructions.sources.len(),
            if instructions.truncated {
                " (truncated)"
            } else {
                ""
            }
        )),
        None => lines.push("Project instructions: none loaded (AGENTS.md, MERMAID.md)".to_string()),
    }
    lines.push(format!(
        "MCP servers: {} configured, {} ready",
        state.mcp.servers.len(),
        state
            .mcp
            .servers
            .values()
            .filter(|entry| matches!(entry.status, crate::domain::McpServerStatus::Ready))
            .count()
    ));
    lines.push(
        "Useful next commands: /help, /context, /model-info <model>, /compact [focus]".to_string(),
    );
    lines.join("\n")
}

fn safety_mode_name(mode: crate::runtime::SafetyMode) -> &'static str {
    mode.as_str()
}

/// The most recent user message, trimmed and length-capped — used as the
/// Auto-mode classifier's "what is the user trying to do" context. `None`
/// when the session has no user message yet.
fn latest_user_intent(session: &super::state::Session) -> Option<String> {
    const MAX: usize = 2000;
    session
        .messages()
        .iter()
        .rev()
        .find(|m| matches!(m.role, crate::models::MessageRole::User))
        .map(|m| {
            let c = m.content.trim();
            if c.len() > MAX {
                format!("{}…", &c[..c.floor_char_boundary(MAX)])
            } else {
                c.to_string()
            }
        })
}

fn usage_text(state: &State) -> String {
    let mut lines = Vec::new();
    lines.push("Usage".to_string());
    lines.push(format!("Model: {}", state.session.model_id));
    lines.push(String::new());

    match &state.session.context_usage {
        Some(context) => {
            let source = if context.is_estimate() {
                "estimated"
            } else {
                "provider-reported"
            };
            lines.push(format!(
                "Current context: {}{}{}",
                format_compact_count(context.used_tokens),
                context
                    .max_tokens
                    .map(|max| format!(" / {}", format_compact_count(max)))
                    .unwrap_or_else(|| " / unknown".to_string()),
                context
                    .used_percent
                    .map(|p| format!(" ({}%, {})", p, source))
                    .unwrap_or_else(|| format!(" ({})", source))
            ));
        },
        None => lines.push("Current context: n/a".to_string()),
    }

    match state.session.last_token_usage {
        Some(last) => lines.push(format!("Last API request: {}", usage_totals_line(last))),
        None => lines.push("Last API request: n/a".to_string()),
    }
    lines.push(format!(
        "Session processed: {}",
        usage_totals_line(state.session.cumulative_token_usage)
    ));

    lines.join("\n")
}

fn context_text(state: &State) -> String {
    let mut lines = Vec::new();
    lines.push("Context".to_string());
    lines.push(format!("Model: {}", state.session.model_id));
    lines.push(format!(
        "Provider: {}",
        state.runtime.provider_capabilities.provider
    ));
    lines.push(String::new());

    let request = build_chat_request(state);
    let max_context = state
        .session
        .context_usage
        .as_ref()
        .and_then(|snapshot| snapshot.max_tokens)
        .or(state.runtime.provider_capabilities.max_context_tokens);
    // The request here carries MCP tools only; the effect runner appends the
    // built-in tool schemas during dispatch. Fold their estimated cost in so
    // the verdict/hard-limit lines agree with what dispatch actually decides.
    let next_snapshot = super::state::estimate_context_usage_for_request(&request, max_context)
        .with_additional_tokens(state.runtime.builtin_tool_schema_tokens);
    let policy = CompactionPolicy::default();
    let response_reserve = policy.response_reserve(request.max_tokens);
    let usage_summary = match (next_snapshot.used_percent, next_snapshot.max_tokens) {
        (Some(percent), Some(_)) if percent >= policy.auto_threshold_percent => {
            format!("high ({percent}% used)")
        },
        (Some(percent), Some(_)) if percent >= 70 => format!("getting full ({percent}% used)"),
        (Some(percent), Some(_)) => format!("comfortable ({percent}% used)"),
        _ => "unknown because provider context limit is unknown".to_string(),
    };

    lines.push(format!("Context fullness: {usage_summary}"));
    lines.push(format!(
        "Next request: {}{} (estimated)",
        format_compact_count(next_snapshot.used_tokens),
        next_snapshot
            .max_tokens
            .map(|max| format!(" / {}", format_compact_count(max)))
            .unwrap_or_else(|| " / unknown".to_string())
    ));
    if let Some(remaining) = next_snapshot.remaining_tokens {
        lines.push(format!(
            "Remaining after request: {}",
            format_compact_count(remaining)
        ));
    }
    lines.push(format!(
        "Response reserve: {}",
        format_compact_count(response_reserve)
    ));
    lines.push(format!(
        "Auto compact threshold: {}%",
        policy.auto_threshold_percent
    ));
    let auto_status = match should_auto_compact(&next_snapshot, &request, policy) {
        Ok(()) => "would run before the next model call".to_string(),
        Err(reason) => format!("not needed ({reason})"),
    };
    lines.push(format!("Auto compact: {auto_status}"));
    if auto_status.starts_with("would run") {
        lines.push(
            "Suggested action: continue normally; Mermaid will compact before the next model call."
                .to_string(),
        );
    } else {
        lines.push("Suggested action: no manual compaction needed unless you want a handoff checkpoint now.".to_string());
    }
    lines.push(format!(
        "Hard limit risk: {}",
        if context_exceeds_hard_limit(&next_snapshot, &request, policy) {
            "yes"
        } else {
            "no"
        }
    ));

    if let Some(context) = &state.session.context_usage {
        let source = if context.is_estimate() {
            "estimated"
        } else {
            "provider-reported"
        };
        lines.push(format!(
            "Last reported context: {}{} ({})",
            format_compact_count(context.used_tokens),
            context
                .max_tokens
                .map(|max| format!(" / {}", format_compact_count(max)))
                .unwrap_or_else(|| " / unknown".to_string()),
            source
        ));
    }

    if let Some(breakdown) = &next_snapshot.breakdown {
        lines.push(String::new());
        lines.push("Prompt budget estimate:".to_string());
        lines.push(format!(
            "- system prompt: {}",
            format_compact_count(breakdown.system_tokens)
        ));
        lines.push(format!(
            "- instructions: {}",
            format_compact_count(breakdown.instructions_tokens)
        ));
        lines.push(format!(
            "- messages ({}): {}",
            breakdown.message_count,
            format_compact_count(breakdown.message_tokens)
        ));
        lines.push(format!(
            "- MCP tool schemas ({}): {}",
            breakdown.tool_count,
            format_compact_count(breakdown.tool_schema_tokens)
        ));
        if state.runtime.builtin_tool_schema_tokens > 0 {
            lines.push(format!(
                "- built-in tool schemas: {}",
                format_compact_count(state.runtime.builtin_tool_schema_tokens)
            ));
        } else {
            lines.push("- built-in tool schemas: measured on the first model call".to_string());
        }
        if breakdown.image_count > 0 {
            lines.push(format!("- images: {}", breakdown.image_count));
        }
    }

    if let Some(last) = state.session.conversation.compactions.last() {
        lines.push(String::new());
        lines.push("Last compaction:".to_string());
        lines.push(format!("- trigger: {}", last.trigger.label()));
        lines.push(format!(
            "- context: {} -> {} tokens",
            format_compact_count(last.before_tokens),
            format_compact_count(last.after_tokens)
        ));
        lines.push(format!(
            "- archived: {} messages",
            last.archived_message_count
        ));
        lines.push(format!(
            "- preserved: {} messages",
            last.preserved_message_count
        ));
        lines.push(format!(
            "- verification: {}",
            if last.verified {
                "verified".to_string()
            } else {
                last.verification_error
                    .as_ref()
                    .map(|err| format!("draft fallback ({err})"))
                    .unwrap_or_else(|| "draft fallback".to_string())
            }
        ));
        if let Some(path) = &last.archive_path {
            lines.push(format!("- archive: {}", path));
        }
        lines.push("- inspect: use the archive path above to review the raw messages Mermaid removed from context.".to_string());
    } else {
        lines.push(String::new());
        lines.push("Last compaction: none yet.".to_string());
    }

    lines.join("\n")
}

fn tasks_text(tasks: &[crate::runtime::TaskRecord]) -> String {
    let mut lines = vec!["Tasks".to_string()];
    if tasks.is_empty() {
        lines.push("No tasks recorded yet.".to_string());
        return lines.join("\n");
    }
    for task in tasks {
        lines.push(format!(
            "- {} [{}] {} - {}",
            task.id, task.status, task.priority, task.title
        ));
        lines.push(format!("  project: {}", task.project_path));
        lines.push(format!("  updated: {}", task.updated_at));
    }
    lines.join("\n")
}

fn task_detail_text(
    task: Option<&crate::runtime::TaskRecord>,
    events: &[crate::runtime::TaskTimelineEvent],
) -> String {
    let Some(task) = task else {
        return "Task not found.".to_string();
    };
    let mut lines = vec![
        format!("Task {}", task.id),
        format!("Title: {}", task.title),
        format!("Status: {}", task.status),
        format!("Priority: {}", task.priority),
        format!("Project: {}", task.project_path),
        format!("Model: {}", task.model_id),
        format!("Created: {}", task.created_at),
        format!("Updated: {}", task.updated_at),
    ];
    if let Some(report) = &task.final_report {
        lines.push(String::new());
        lines.push("Final report:".to_string());
        lines.push(report.clone());
    }
    if !events.is_empty() {
        lines.push(String::new());
        lines.push("Timeline:".to_string());
        for event in events {
            lines.push(format!(
                "- {} {}: {}",
                event.created_at, event.kind, event.message
            ));
        }
    }
    lines.join("\n")
}

fn processes_text(processes: &[crate::runtime::ProcessRecord]) -> String {
    let mut lines = vec!["Processes".to_string()];
    if processes.is_empty() {
        lines.push("No processes recorded yet.".to_string());
        return lines.join("\n");
    }
    for process in processes {
        lines.push(format!(
            "- {} pid={} [{}] {}",
            process.id,
            process.pid,
            process.status.as_str(),
            process.command
        ));
        if let Some(task_id) = &process.task_id {
            lines.push(format!("  task: {}", task_id));
        }
        if let Some(url) = &process.detected_url {
            lines.push(format!("  url: {}", url));
        }
        if let Some(log_path) = &process.log_path {
            lines.push(format!("  log: {}", log_path));
        }
    }
    lines.join("\n")
}

fn approvals_text(approvals: &[crate::runtime::ApprovalRecord]) -> String {
    let mut lines = vec!["Approvals".to_string()];
    if approvals.is_empty() {
        lines.push("No pending approvals.".to_string());
        return lines.join("\n");
    }
    for approval in approvals {
        lines.push(format!(
            "- {} [{}] {}",
            approval.id, approval.risk_classification, approval.proposed_action
        ));
        if let Some(checkpoint_id) = &approval.checkpoint_id {
            lines.push(format!("  checkpoint: {}", checkpoint_id));
        }
        if approval.pending_action_json.is_some() {
            lines.push("  pending action: recorded".to_string());
        }
    }
    lines.join("\n")
}

fn checkpoints_text(checkpoints: &[crate::runtime::CheckpointRecord]) -> String {
    let mut lines = vec!["Checkpoints".to_string()];
    if checkpoints.is_empty() {
        lines.push("No checkpoints recorded yet.".to_string());
        return lines.join("\n");
    }
    for checkpoint in checkpoints {
        lines.push(format!(
            "- {} {} {}",
            checkpoint.id, checkpoint.created_at, checkpoint.project_path
        ));
    }
    lines.join("\n")
}

fn plugins_text(plugins: &[crate::runtime::PluginInstallRecord]) -> String {
    let mut lines = vec!["Plugins".to_string()];
    if plugins.is_empty() {
        lines.push("No plugins installed.".to_string());
        return lines.join("\n");
    }
    for plugin in plugins {
        lines.push(format!(
            "- {} [{}] {}",
            plugin.id,
            if plugin.enabled {
                "enabled"
            } else {
                "disabled"
            },
            plugin.source
        ));
    }
    lines.join("\n")
}

fn usage_totals_line(usage: TokenUsageTotals) -> String {
    let mut parts = vec![
        format!("total {}", format_compact_count(usage.total_tokens)),
        format!("input {}", format_compact_count(usage.input_total_tokens())),
        format!(
            "output {}",
            format_compact_count(usage.output_total_tokens())
        ),
    ];
    if usage.cached_input_tokens > 0 {
        parts.push(format!(
            "cache read {}",
            format_compact_count(usage.cached_input_tokens)
        ));
    }
    if usage.cache_creation_input_tokens > 0 {
        parts.push(format!(
            "cache write {}",
            format_compact_count(usage.cache_creation_input_tokens)
        ));
    }
    if usage.reasoning_output_tokens > 0 {
        parts.push(format!(
            "reasoning {}",
            format_compact_count(usage.reasoning_output_tokens)
        ));
    }
    parts.join(", ")
}

fn format_compact_count(value: usize) -> String {
    if value >= 1_000_000 {
        format_scaled(value, 1_000_000, "m")
    } else if value >= 10_000 {
        format_scaled(value, 1_000, "k")
    } else {
        value.to_string()
    }
}

fn format_scaled(value: usize, divisor: usize, suffix: &str) -> String {
    let whole = value / divisor;
    let decimal = ((value % divisor) * 10) / divisor;
    if decimal == 0 {
        format!("{}{}", whole, suffix)
    } else {
        format!("{}.{}{}", whole, decimal, suffix)
    }
}

fn handle_cancel_turn(state: &mut State, cmds: &mut Vec<Cmd>) {
    let Some(id) = state.turn.id() else {
        return;
    };
    // Already cancelling: don't double-cancel.
    if matches!(state.turn, TurnState::Cancelling { .. }) {
        return;
    }
    cmds.push(Cmd::CancelScope(id));
    // The cancelled turn's tool tasks are aborted; their parked approval
    // requests can never be answered, so drop any queued prompts.
    state.pending_approval.clear();
    state.turn = TurnState::Cancelling {
        id,
        since: std::time::SystemTime::from(state.now),
    };
}

fn request_exit(state: &mut State, cmds: &mut Vec<Cmd>) {
    if state.should_exit {
        return;
    }
    if let Some(id) = state.turn.id() {
        cmds.push(Cmd::CancelScope(id));
    }
    state.should_exit = true;
    state.ui.pending_msgs.clear();
    state.pending_approval.clear();
    // Quitting mid-stream: preserve whatever the model already produced so
    // `--continue` shows what was on screen. Commit the in-flight partial
    // as an assistant message with an interrupted marker before saving.
    let now = state.now;
    if let TurnState::Generating {
        partial_text,
        partial_reasoning,
        thinking_signature,
        ..
    } = &mut state.turn
        && !partial_text.trim().is_empty()
    {
        let text = std::mem::take(partial_text);
        let reasoning = std::mem::take(partial_reasoning);
        let sig = thinking_signature.take();
        let msg = commit_assistant_message(
            format!("{text}\n\n_[interrupted]_"),
            reasoning,
            Vec::new(),
            sig,
            now,
        );
        state.session.append(msg);
    }
    cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));
    cmds.push(Cmd::Exit);
}

fn handle_confirm_accepted(state: &mut State, cmds: &mut Vec<Cmd>) {
    let Some(confirm) = state.confirm.take() else {
        return;
    };
    match confirm.accept_msg_token {
        super::state::ConfirmationTarget::ClearConversation => {
            // Clear = start a fresh conversation: new ID, new default
            // title, empty history, zero cumulative tokens. Matches
            // user mental model ("wipe everything").
            let project_path = state.session.conversation.project_path.clone();
            let model_name = state.session.conversation.model_name.clone();
            state.session.conversation =
                crate::session::ConversationHistory::new(project_path, model_name);
            state.session.cumulative_tokens = 0;
            state.session.last_token_usage = None;
            state.session.cumulative_token_usage = TokenUsageTotals::default();
            state.session.context_usage = None;
            emit_title_if_changed(state, cmds);
        },
    }
}

fn handle_compaction_finished(
    state: &mut State,
    cmds: &mut Vec<Cmd>,
    turn: TurnId,
    result: CompactionResult,
) {
    let manual = match state.turn {
        TurnState::Compacting { id, .. } if id == turn => true,
        TurnState::Generating { id, .. } if id == turn => false,
        _ => return,
    };

    let conversation_id = state.session.conversation.id.clone();
    let mut record = result.record;
    record.archive_path = Some(format!(
        ".mermaid/compactions/{}/{}.json",
        conversation_id, record.id
    ));
    let archive = CompactionArchive {
        id: record.id.clone(),
        conversation_id,
        created_at: record.created_at,
        messages: result.archived_messages,
    };

    state
        .session
        .conversation
        .replace_messages(result.replacement_messages);
    state.session.conversation.add_compaction(record.clone());
    state.session.context_usage = Some(result.after_snapshot);

    if let Some(usage) = result.usage {
        let totals = TokenUsageTotals::from_usage(&usage);
        state.session.last_token_usage = Some(totals);
        state.session.cumulative_token_usage.add_assign(totals);
        state.session.cumulative_tokens = state
            .session
            .cumulative_tokens
            .saturating_add(usage.total_tokens);
    }

    if manual {
        state.turn = TurnState::Idle;
        // Drain one queued message on the way out, same as the no-tool-calls
        // tail of `handle_stream_done` / `handle_turn_cancelled` (#73). A
        // message the user typed during `/compact` would otherwise sit in the
        // FIFO until some later turn happened to end.
        if let Some(next) = state.ui.queued_messages.pop_front() {
            state.ui.pending_msgs.push_back(Msg::SubmitPrompt {
                text: next.text,
                attachment_ids: next.attachment_ids,
            });
        }
    }

    // The compaction's replacement message already carries the receipt text, so
    // the old transient banner that repeated it is simply gone.
    // SaveCompactionArchive persists the stripped conversation.
    cmds.push(Cmd::SaveCompactionArchive {
        archive,
        record,
        conversation: state.session.conversation.clone(),
    });
}

fn handle_compaction_failed(
    state: &mut State,
    turn: TurnId,
    trigger: CompactionTrigger,
    message: String,
    kind: StatusKind,
) {
    match state.turn {
        TurnState::Compacting { id, .. } if id == turn => {
            state.turn = TurnState::Idle;
        },
        TurnState::Generating { id, .. } if id == turn => {},
        _ => return,
    }

    let prefix = match trigger {
        CompactionTrigger::Manual => "Compaction failed",
        CompactionTrigger::AutoThreshold => "Auto-compaction skipped",
        CompactionTrigger::ContextLimitRetry => "Context-limit compaction failed",
    };
    let _ = kind;
    state
        .session
        .append(ChatMessage::system(format!("{}: {}", prefix, message)));
}

fn handle_stream_tool_call(
    state: &mut State,
    turn: TurnId,
    call: crate::models::tool_call::ToolCall,
) {
    if let TurnState::Generating {
        id,
        pending_tool_calls,
        ..
    } = &mut state.turn
        && *id == turn
    {
        pending_tool_calls.push(call);
        return;
    }
    // The stale filter at update_step's top guarantees this event's turn
    // matches the active turn, so reaching here means the turn already
    // advanced past Generating (e.g. into ExecutingTools) before this tool
    // call arrived. Single-channel relay ordering should prevent it; log so
    // a provider that ever emits a ToolCall after Done is diagnosable.
    tracing::warn!(
        event_turn = %turn,
        active_turn = ?state.turn.id(),
        "reducer: dropped StreamToolCall — turn not in Generating state",
    );
}

fn handle_stream_done(
    state: &mut State,
    cmds: &mut Vec<Cmd>,
    turn: TurnId,
    usage: Option<crate::models::TokenUsage>,
    thinking_signature: Option<String>,
    stop_reason: Option<crate::models::FinishReason>,
) {
    // Unpack the Generating state, drop it into Idle temporarily;
    // the branch below decides whether to stay Idle (no tool calls)
    // or transition to ExecutingTools (calls buffered).
    let generating = match std::mem::replace(&mut state.turn, TurnState::Idle) {
        TurnState::Generating {
            id,
            partial_text,
            partial_reasoning,
            thinking_signature: accumulated_sig,
            pending_tool_calls,
            ..
        } if id == turn => (
            partial_text,
            partial_reasoning,
            accumulated_sig,
            pending_tool_calls,
        ),
        other => {
            state.turn = other;
            return;
        },
    };

    let (partial_text, partial_reasoning, accumulated_sig, tool_calls) = generating;
    let final_sig = thinking_signature.or(accumulated_sig);

    // Commit the assistant message (with any tool calls attached —
    // the adapter will serialize them into the next conversation
    // turn).
    let msg = commit_assistant_message(
        partial_text,
        partial_reasoning,
        tool_calls.clone(),
        final_sig,
        state.now,
    );
    state.session.append(msg);

    // Surface a terminal stop reason that would otherwise leave the response
    // silently incomplete. (A refusal with no content is turned into an error
    // upstream in the adapter; here we only see reasons that still produced
    // output.) Skip it when tool calls are pending: a system message inserted
    // between the assistant's `tool_calls` and their results breaks provider
    // pairing → 400 (#72). A Length/ContentFilter stop *with* tool calls is
    // contradictory anyway, so dropping the note in that case is safe.
    if tool_calls.is_empty() {
        match stop_reason {
            Some(crate::models::FinishReason::Length) => push_system(
                state,
                cmds,
                "⚠ Response truncated — reached the model's max output-token limit.",
            ),
            Some(crate::models::FinishReason::ContentFilter) => push_system(
                state,
                cmds,
                "âš  Response was flagged by the provider's content filter.",
            ),
            _ => {},
        }
    }

    // Provider token usage is per API request. Track both the last
    // reported request and the session total so the footer can label
    // the number honestly instead of presenting a giant raw counter.
    if let Some(u) = usage {
        let totals = TokenUsageTotals::from_usage(&u);
        state.session.last_token_usage = Some(totals);
        state.session.cumulative_token_usage.add_assign(totals);
        state.session.cumulative_tokens = state
            .session
            .cumulative_tokens
            .saturating_add(u.total_tokens);
        let max_context = state
            .session
            .context_usage
            .as_ref()
            .and_then(|snapshot| snapshot.max_tokens)
            .or(state.runtime.provider_capabilities.max_context_tokens);
        let mut context = super::state::ContextUsageSnapshot::from_usage(&u, max_context);
        if let Some(prev) = state.session.context_usage.as_ref()
            && context.breakdown.is_none()
        {
            context.breakdown = prev.breakdown.clone();
        }
        state.session.context_usage = Some(context);
    }
    // When a turn reports no usage (common on tool follow-ups), leave the
    // prior request's `last_token_usage` intact rather than nulling it —
    // the footer's "Last API request" should reflect the last request that
    // actually reported usage, not flip to "n/a".

    cmds.push(Cmd::SaveConversation(state.session.conversation.clone()));

    // If the model asked for any tools, transition to ExecutingTools
    // and dispatch one ExecuteTool per call. The Vec<Option<ToolOutcome>>
    // invariant now has a real producer — ToolFinished messages
    // populate the slots, and try_complete_outcomes gates the
    // transition to the follow-up Generating turn.
    if !tool_calls.is_empty() {
        let pending: Vec<super::state::PendingToolCall> = tool_calls
            .into_iter()
            .map(|source| super::state::PendingToolCall {
                call_id: state.ids.fresh_tool_call(),
                source,
            })
            .collect();
        // Captured once for the whole batch: the live safety mode + the
        // turn's intent (for the Auto-mode classifier).
        let intent = latest_user_intent(&state.session);
        for call in &pending {
            cmds.push(Cmd::ExecuteTool {
                turn,
                call_id: call.call_id,
                source: call.source.clone(),
                // F7: pass the session's current model id so subagent
                // tools can spawn children against the same provider.
                model_id: state.session.model_id.clone(),
                safety_mode: state.session.safety_mode,
                intent: intent.clone(),
            });
        }
        state.turn = super::transition::start_executing_tools(
            turn,
            pending,
            std::time::SystemTime::from(state.now),
        );
        return;
    }

    // No tool calls — turn ends here. Drain the queued-message FIFO.
    // The follow-up goes through `pending_msgs` so the outer
    // `update()` re-enters cleanly — preserves stale-filter
    // semantics instead of inline-invoking.
    if let Some(next) = state.ui.queued_messages.pop_front() {
        state.ui.pending_msgs.push_back(Msg::SubmitPrompt {
            text: next.text,
            attachment_ids: next.attachment_ids,
        });
    }
}

/// Handle `Msg::OpenImageAt { message_index, image_index }`. Resolves
/// the base64 payload from the committed message history, writes it
/// to a temp file, and dispatches `Cmd::OpenInSystem` so the user's
/// default image viewer opens it. F13.
fn handle_open_image_at(
    state: &mut State,
    cmds: &mut Vec<Cmd>,
    message_index: usize,
    image_index: usize,
) {
    let msg = match state.session.messages().get(message_index) {
        Some(m) => m,
        None => return,
    };
    let Some(images) = msg.images.as_ref() else {
        return;
    };
    let Some(b64) = images.get(image_index) else {
        return;
    };
    use base64::{Engine, engine::general_purpose};
    let Ok(bytes) = general_purpose::STANDARD.decode(b64) else {
        return;
    };
    let id = state.ids.tool_call.next();
    let temp_path = state.temp_dir.join(format!("mermaid-img-{}.png", id));
    cmds.push(Cmd::WriteImageToTemp {
        path: temp_path.clone(),
        bytes,
        format: "png".to_string(),
    });
    cmds.push(Cmd::OpenInSystem(temp_path));
}

/// Handle `Msg::TurnCancelled(turn)`. The effect runner's `drop_scope`
/// emits this after the cancelled turn's `TurnScope` drains. Transitions
/// `Cancelling(id) → Idle` when the ids match; also closes out the
/// degenerate case where the scope drained but state is already `Idle`
/// (e.g. the stream-done raced). Drains one queued message on the way
/// out, same as the no-tool-calls tail of `handle_stream_done`.
///
/// Stale filter at the top of `update_step` catches mismatched turn ids
/// before we get here, so this handler is branch-light.
fn handle_turn_cancelled(state: &mut State, turn: TurnId) {
    match state.turn {
        TurnState::Cancelling { id, .. } if id == turn => {
            state.turn = TurnState::Idle;
            if let Some(next) = state.ui.queued_messages.pop_front() {
                state.ui.pending_msgs.push_back(Msg::SubmitPrompt {
                    text: next.text,
                    attachment_ids: next.attachment_ids,
                });
            }
        },
        _ => {
            // Stream already completed / already idle / stale id —
            // silently no-op. The filter at update_step's top would
            // have caught a truly stale id; this branch handles the
            // benign race where the scope drained after a successful
            // StreamDone committed normally.
        },
    }
}

fn handle_upstream_error(state: &mut State, turn: TurnId, error: crate::models::UserFacingError) {
    // Defense in depth (F4): even though the stale-filter at the top of
    // `update_step` gates on `turn_id()`, re-check here so a future
    // refactor that weakens the filter can't silently wipe the active
    // turn with an error message that belongs to a superseded one.
    if state.turn.id() != Some(turn) {
        return;
    }

    // End the current turn. Surface the error through a single
    // channel — the ActionDisplay attached to an empty assistant
    // message. The chat widget paints ActionDisplays as colored
    // error blocks, so committing to both `content` and `actions`
    // would paint the same error twice.
    //
    // Do NOT also set `state.status`: the F9 banner would render the
    // same error a second time directly above the input, which is
    // just noise. The chat entry is persistent (scrollable);
    // duplicating as a transient banner adds nothing.
    let now = state.now;
    state.turn = TurnState::Idle;
    let msg = ChatMessage {
        role: MessageRole::Assistant,
        content: String::new(),
        timestamp: now,
        kind: crate::models::ChatMessageKind::Normal,
        metadata: None,
        actions: vec![super::action::ActionDisplay {
            action_type: "Error".to_string(),
            target: error.summary.clone(),
            result: super::action::ActionResult::Error {
                error: error.message.clone(),
            },
            details: super::action::ActionDetails::Simple,
            duration_seconds: None,
            metadata: None,
        }],
        thinking: None,
        images: None,
        tool_calls: None,
        tool_call_id: None,
        tool_name: None,
        thinking_signature: None,
    };
    state.session.append(msg);
}

/// Route a typed `ProgressEvent`.
///
/// Tool stdout / status / byte-progress and subagent chatter are intentionally
/// dropped: surfacing each line to the status banner flickered a fresh line
/// above the input every few milliseconds (build output, pids, streamed file
/// contents) which read as noise. The status *line* already names the in-flight
/// tool, and a tool's full output lands in the chat transcript when it
/// finishes. Only image artifacts are handled here — they attach to the
/// in-flight assistant message for inline display.
fn handle_tool_progress(
    state: &mut State,
    _cmds: &mut Vec<Cmd>,
    _turn: TurnId,
    event: crate::providers::ProgressEvent,
) {
    use crate::providers::ProgressEvent;
    use base64::{Engine as _, engine::general_purpose};

    if let ProgressEvent::Artifact { mime, data, .. } = event
        && mime.starts_with("image/")
        && matches!(
            state.turn,
            TurnState::ExecutingTools { .. } | TurnState::Generating { .. }
        )
        && let Some(last) = state.session.conversation.messages.last_mut()
        && last.role == MessageRole::Assistant
    {
        let encoded = general_purpose::STANDARD.encode(&data);
        last.images.get_or_insert_with(Vec::new).push(encoded);
    }
}

fn handle_tool_finished(
    state: &mut State,
    cmds: &mut Vec<Cmd>,
    turn: TurnId,
    call_id: super::ids::ToolCallId,
    outcome: ToolOutcome,
) {
    // Borrow calls + outcomes simultaneously via a helper to avoid
    // double mutable borrow on `state.turn`.
    let completed = match &mut state.turn {
        TurnState::ExecutingTools {
            id,
            calls,
            outcomes,
            ..
        } if *id == turn => {
            if !fill_outcome(calls, outcomes, call_id, outcome.clone()) {
                return;
            }
            // Attach action display to the last assistant message so
            // the renderer can show it.
            if let Some(call) = calls.iter().find(|c| c.call_id == call_id) {
                let action = action_display_for(call, &outcome);
                if let Some(process) = action
                    .metadata
                    .as_ref()
                    .and_then(|metadata| metadata.process.clone())
                {
                    cmds.push(Cmd::SaveProcess(process.clone()));
                    state.runtime.register_process(process);
                }
                if let Some(last) = state.session.conversation.messages.last_mut()
                    && last.role == MessageRole::Assistant
                {
                    last.actions.push(action);
                }
            }
            try_complete_outcomes(outcomes)
        },
        _ => None,
    };

    if let Some(completed_outcomes) = completed
        && let TurnState::ExecutingTools { id, calls, .. } =
            std::mem::replace(&mut state.turn, TurnState::Idle)
        && id == turn
    {
        // Append each tool message to the conversation, then kick off
        // the follow-up model call.
        let tool_msgs = tool_result_messages(&calls, completed_outcomes);
        for m in tool_msgs {
            state.session.append(m);
        }
        let next_turn = state.ids.fresh_turn();
        state.turn = start_generating(next_turn, std::time::SystemTime::from(state.now));
        cmds.push(Cmd::CallModel {
            turn: next_turn,
            request: build_chat_request(state),
        });
    }
}

/// Construct the request the model sees for this turn, pulling in the
/// current message log + the active `MERMAID.md` suffix + the
/// reasoning choice + the tools surface.
pub fn build_chat_request(state: &State) -> ChatRequest {
    // Project instructions + the always-loaded memory index compose into the
    // single dynamic suffix. The memory block carries its own `# Memory`
    // header, so it stays clearly separated from AGENTS.md/MERMAID.md and the
    // model adapters need no changes.
    let instructions = match (
        state.instructions.as_ref().map(|i| i.content.clone()),
        state.memory.as_ref().map(|m| m.index.clone()),
    ) {
        (Some(i), Some(m)) => Some(format!("{i}\n\n{m}")),
        (Some(i), None) => Some(i),
        (None, Some(m)) => Some(m),
        (None, None) => None,
    };

    // Pass user-configured values verbatim. `ModelSettings::default()`
    // already supplies `DEFAULT_TEMPERATURE` / `DEFAULT_MAX_TOKENS`,
    // so config never has a real "zero" — the old `.max(DEFAULT_*)`
    // was clobbering low user settings (e.g. temperature=0.1 became
    // 0.7).
    let settings = &state.settings.default_model;
    let temperature = if settings.temperature > 0.0 {
        settings.temperature
    } else {
        DEFAULT_TEMPERATURE
    };
    let max_tokens = if settings.max_tokens > 0 {
        settings.max_tokens
    } else {
        DEFAULT_MAX_TOKENS
    };

    // MCP tools the model should see — each advertised by a Ready
    // server, fully-qualified as `mcp__<server>__<tool>`. The effect
    // runner prepends built-in tools before dispatching, so this
    // vector is the MCP-only portion.
    let mcp_tools: Vec<crate::domain::ToolDefinition> = state
        .mcp
        .servers
        .iter()
        .filter(|(_, entry)| matches!(entry.status, crate::domain::McpServerStatus::Ready))
        .flat_map(|(server_name, entry)| {
            entry
                .tools
                .iter()
                .map(move |tool| crate::domain::ToolDefinition {
                    name: format!("mcp__{}__{}", server_name, tool.name),
                    description: tool.description.clone(),
                    input_schema: tool.input_schema.clone(),
                })
        })
        .collect();

    ChatRequest {
        model_id: state.session.model_id.clone(),
        messages: evict_stale_screenshots(state.session.messages().to_vec()),
        system_prompt: system_prompt_for_state(state),
        instructions,
        reasoning: state.session.reasoning,
        temperature,
        max_tokens,
        tools: mcp_tools,
    }
}

fn system_prompt_for_state(state: &State) -> String {
    let base = state
        .settings
        .prompt
        .render_system_prompt(&get_system_prompt());
    format!(
        "{}\n\n## Current Session\nCurrent working directory: {}\nSafety mode: {} (live — the user can switch it anytime with Shift+Tab or /safety; trust this over any earlier tool error, and attempt gated actions rather than assuming they will fail).\nTreat this as the project root unless the user specifies a different path.",
        base,
        state.cwd.display(),
        state.session.safety_mode.as_str()
    )
}

/// Walk the message log and retain only the `MAX_RETAINED_SCREENSHOTS`
/// most recent images across the whole conversation. Older messages
/// that had images get `images: None` AND an appended
/// `[Image elided — superseded by newer screenshot]` marker in
/// `content`, so the model still knows something visual was there.
///
/// Why: an agentic GUI loop can generate 10+ screenshots in a single
/// session. At 2MB/PNG that's 20MB uncompressed in every outgoing
/// request body — request bloat compounds across turns and slows the
/// model. The on-screen chat history still shows all images (this
/// transformation is on the CLONED Vec passed to the provider); only
/// the wire payload is slimmed.
fn evict_stale_screenshots(mut messages: Vec<ChatMessage>) -> Vec<ChatMessage> {
    use crate::constants::MAX_RETAINED_SCREENSHOTS;
    let mut seen = 0usize;
    for msg in messages.iter_mut().rev() {
        let Some(imgs) = msg.images.as_ref() else {
            continue;
        };
        if imgs.is_empty() {
            continue;
        }
        if seen < MAX_RETAINED_SCREENSHOTS {
            seen += imgs.len();
            continue;
        }
        // Beyond the cap — elide.
        let elided_count = imgs.len();
        msg.images = None;
        let marker = if elided_count == 1 {
            "\n[Image elided — superseded by newer screenshot]"
        } else {
            "\n[Images elided — superseded by newer screenshots]"
        };
        if !msg.content.ends_with(marker) {
            msg.content.push_str(marker);
        }
    }
    messages
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::Config;
    use crate::domain::msg::{Key, KeyCode, KeyMods};
    use crate::domain::state::{McpServerEntry, McpState, PendingToolCall, UiState};
    use crate::domain::transition::start_executing_tools;
    use std::path::PathBuf;

    fn fresh_state() -> State {
        State::new(
            Config::default(),
            PathBuf::from("/tmp/project"),
            "ollama/test".to_string(),
        )
    }

    #[test]
    fn evict_stale_screenshots_retains_most_recent_and_elides_rest() {
        use crate::constants::MAX_RETAINED_SCREENSHOTS;
        let mut msgs = Vec::new();
        for i in 0..(MAX_RETAINED_SCREENSHOTS + 3) {
            msgs.push(ChatMessage {
                role: MessageRole::Assistant,
                content: format!("turn {}", i),
                timestamp: chrono::Local::now(),
                kind: crate::models::ChatMessageKind::Normal,
                metadata: None,
                actions: vec![],
                thinking: None,
                images: Some(vec![format!("png-base64-{}", i)]),
                tool_calls: None,
                tool_call_id: None,
                tool_name: None,
                thinking_signature: None,
            });
        }
        let out = super::evict_stale_screenshots(msgs);
        // Last MAX_RETAINED_SCREENSHOTS entries still carry images.
        for m in out.iter().rev().take(MAX_RETAINED_SCREENSHOTS) {
            assert!(m.images.is_some(), "most-recent images must survive");
        }
        // Everything before the cap is elided.
        for m in out.iter().rev().skip(MAX_RETAINED_SCREENSHOTS) {
            assert!(m.images.is_none(), "older images must be elided");
            assert!(
                m.content.contains("elided"),
                "elision marker must land in content"
            );
        }
    }

    #[test]
    fn evict_stale_screenshots_preserves_messages_without_images() {
        use crate::constants::MAX_RETAINED_SCREENSHOTS;
        // 5 text-only + 2 with images (under the cap) — nothing should
        // be elided.
        let mut msgs = Vec::new();
        for i in 0..5 {
            msgs.push(ChatMessage {
                role: MessageRole::User,
                content: format!("text only {}", i),
                timestamp: chrono::Local::now(),
                kind: crate::models::ChatMessageKind::Normal,
                metadata: None,
                actions: vec![],
                thinking: None,
                images: None,
                tool_calls: None,
                tool_call_id: None,
                tool_name: None,
                thinking_signature: None,
            });
        }
        for i in 0..2 {
            msgs.push(ChatMessage {
                role: MessageRole::Assistant,
                content: format!("with image {}", i),
                timestamp: chrono::Local::now(),
                kind: crate::models::ChatMessageKind::Normal,
                metadata: None,
                actions: vec![],
                thinking: None,
                images: Some(vec![format!("png-{}", i)]),
                tool_calls: None,
                tool_call_id: None,
                tool_name: None,
                thinking_signature: None,
            });
        }
        const { assert!(2 < MAX_RETAINED_SCREENSHOTS, "test premise") };
        let out = super::evict_stale_screenshots(msgs);
        // All 7 messages unchanged.
        let with_images = out.iter().filter(|m| m.images.is_some()).count();
        assert_eq!(with_images, 2);
        assert!(!out.iter().any(|m| m.content.contains("elided")));
    }

    #[test]
    fn quit_sets_exit_flag_and_emits_save_and_exit() {
        let state = fresh_state();
        let (state, cmds) = update(state, Msg::Quit);
        assert!(state.should_exit);
        assert_eq!(cmds.len(), 2);
        assert!(matches!(cmds[0], Cmd::SaveConversation(_)));
        assert!(matches!(cmds[1], Cmd::Exit));
    }

    #[test]
    fn ctrl_c_on_idle_empty_input_exits() {
        let state = fresh_state();
        let msg = Msg::Key(Key {
            code: KeyCode::Char('c'),
            modifiers: KeyMods::ctrl(),
        });
        let (state, cmds) = update(state, msg);
        assert!(state.should_exit);
        assert!(cmds.iter().any(|c| matches!(c, Cmd::Exit)));
    }

    #[test]
    fn ctrl_c_on_idle_with_input_exits() {
        let mut state = fresh_state();
        state.ui.input_buffer = "partial".to_string();
        let msg = Msg::Key(Key {
            code: KeyCode::Char('c'),
            modifiers: KeyMods::ctrl(),
        });
        let (state, cmds) = update(state, msg);
        assert!(state.should_exit);
        assert!(cmds.iter().any(|c| matches!(c, Cmd::Exit)));
    }

    /// Tool stdout must NOT reach the status banner. Surfacing every
    /// progress line there flickered noise above the input (build output,
    /// pids, streamed file contents) that appeared for a fraction of a second
    /// and vanished. The status line names the running tool and the full
    /// output lands in chat; the banner is reserved for discrete messages.
    #[test]
    fn tool_progress_output_does_not_touch_status_banner() {
        use crate::providers::ProgressEvent;
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(1), std::time::SystemTime::now());
        let turn = state.current_turn_id().unwrap();

        let (state, _cmds) = update(
            state,
            Msg::ToolProgress {
                turn,
                call_id: super::super::ids::ToolCallId(1),
                event: ProgressEvent::Output(
                    "drwxrwxr-x  3 nsabaj nsabaj 4096 Mar 30 14:02 .mermaid".to_string(),
                ),
            },
        );
        assert!(
            state.status.is_none(),
            "tool stdout must not appear in the status banner"
        );
    }

    /// F14: Ctrl+V in the chat input emits `Cmd::ReadClipboard`. The
    /// reducer stays pure — the actual clipboard read runs off-thread
    /// in the effect runner.
    #[test]
    fn ctrl_v_in_editing_input_emits_read_clipboard() {
        let state = fresh_state();
        assert!(matches!(state.ui.mode, UiMode::EditingInput));
        let (_, cmds) = update(
            state,
            Msg::Key(Key {
                code: KeyCode::Char('v'),
                modifiers: KeyMods::ctrl(),
            }),
        );
        assert!(
            cmds.iter().any(|c| matches!(c, Cmd::ReadClipboard)),
            "Ctrl+V should dispatch Cmd::ReadClipboard; got tags: {:?}",
            cmds.iter().map(|c| c.tag()).collect::<Vec<_>>(),
        );
    }

    /// F14: Ctrl+V while a confirmation modal is open should NOT
    /// hijack the keystroke — the user might be mid-confirmation and
    /// accidentally paste into dismissed UI. Gated out.
    #[test]
    fn ctrl_v_with_confirm_modal_open_is_noop() {
        let mut state = fresh_state();
        state.confirm = Some(super::super::state::Confirmation {
            prompt: "Clear conversation history?".to_string(),
            accept_msg_token: super::super::state::ConfirmationTarget::ClearConversation,
        });
        let (_, cmds) = update(
            state,
            Msg::Key(Key {
                code: KeyCode::Char('v'),
                modifiers: KeyMods::ctrl(),
            }),
        );
        assert!(!cmds.iter().any(|c| matches!(c, Cmd::ReadClipboard)));
    }

    /// F14: Ctrl+V in the conversation-list picker must not trigger
    /// a clipboard read. The picker has its own key handling.
    #[test]
    fn ctrl_v_in_conversation_list_mode_is_noop() {
        let mut state = fresh_state();
        state.ui.mode = UiMode::ConversationList {
            candidates: Vec::new(),
            cursor: 0,
        };
        let (_, cmds) = update(
            state,
            Msg::Key(Key {
                code: KeyCode::Char('v'),
                modifiers: KeyMods::ctrl(),
            }),
        );
        assert!(!cmds.iter().any(|c| matches!(c, Cmd::ReadClipboard)));
    }

    /// Generic async feedback (`Msg::TransientStatus`, e.g. clipboard results)
    /// posts a system message into the chat transcript — there is no banner.
    #[test]
    fn transient_status_posts_to_chat_transcript() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::TransientStatus {
                text: "Clipboard is empty".to_string(),
                kind: StatusKind::Info,
                dismiss_ms: 2_000,
            },
        );
        assert!(state.status.is_none(), "no banner is set");
        let last = state
            .session
            .messages()
            .last()
            .expect("a transcript message was appended");
        assert!(last.content.contains("Clipboard is empty"));
        assert!(
            cmds.iter().any(|c| matches!(c, Cmd::SaveConversation(_))),
            "the transcript message is persisted"
        );
    }

    /// F14: a Paste::Image Msg (whatever its origin — bracketed paste,
    /// Ctrl+V via clipboard, or a future drag-drop) creates an
    /// Attachment entry and emits Cmd::WriteImageToTemp. This is the
    /// existing contract; the test pins it so the Ctrl+V wiring has a
    /// known-good downstream to rely on.
    #[test]
    fn paste_image_creates_attachment_and_writes_temp() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::Paste(super::super::msg::Paste::Image {
                bytes: vec![0x89, 0x50, 0x4E, 0x47], // PNG magic bytes
                format: "png".to_string(),
            }),
        );
        assert_eq!(state.ui.attachments.len(), 1);
        let att = &state.ui.attachments[0];
        assert_eq!(att.format, "png");
        assert_eq!(att.size_bytes, 4);
        assert!(cmds.iter().any(|c| {
            matches!(c, Cmd::WriteImageToTemp { path, .. } if path == &att.temp_path)
        }));
    }

    #[test]
    fn open_image_writes_and_opens_the_same_temp_path() {
        let mut state = fresh_state();
        let image =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"image bytes");
        state
            .session
            .append(ChatMessage::assistant("image").with_images(vec![image]));

        let (_, cmds) = update(
            state,
            Msg::OpenImageAt {
                message_index: 0,
                image_index: 0,
            },
        );

        let write_path = cmds.iter().find_map(|cmd| match cmd {
            Cmd::WriteImageToTemp { path, .. } => Some(path.clone()),
            _ => None,
        });
        let open_path = cmds.iter().find_map(|cmd| match cmd {
            Cmd::OpenInSystem(path) => Some(path.clone()),
            _ => None,
        });
        assert_eq!(write_path, open_path);
    }

    #[test]
    fn ctrl_c_during_turn_exits_and_cancels_scope() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let msg = Msg::Key(Key {
            code: KeyCode::Char('c'),
            modifiers: KeyMods::ctrl(),
        });
        let (state, cmds) = update(state, msg);
        assert!(state.should_exit);
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::CancelScope(TurnId(5))))
        );
        assert!(cmds.iter().any(|c| matches!(c, Cmd::Exit)));
    }

    #[test]
    fn load_conversation_mid_turn_cancels_orphaned_scope() {
        // `/load` while a turn is generating must cancel the in-flight scope,
        // not silently overwrite `state.turn` and orphan the running tasks (#2).
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let history = fresh_state().session.conversation.clone();
        let (state, cmds) = update(state, Msg::ConversationLoaded(history));
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::CancelScope(TurnId(5)))),
            "loading a conversation mid-turn must cancel the in-flight scope"
        );
        assert!(matches!(state.turn, TurnState::Idle));
    }

    #[test]
    fn load_conversation_when_idle_does_not_cancel() {
        // No in-flight turn → nothing to cancel; `/load` just swaps state.
        let state = fresh_state();
        let history = fresh_state().session.conversation.clone();
        let (state, cmds) = update(state, Msg::ConversationLoaded(history));
        assert!(!cmds.iter().any(|c| matches!(c, Cmd::CancelScope(_))));
        assert!(matches!(state.turn, TurnState::Idle));
    }

    #[test]
    fn reducer_reads_injected_now_not_wall_clock() {
        // Cause 3 determinism: the reducer stamps turn timestamps from
        // `state.now`, never `SystemTime::now()` / `Local::now()`. Folding the
        // same `(State, Msg)` with the same injected `now` must produce a
        // byte-identical `since`, and it must equal the injected value — proving
        // the reducer is a pure function of its inputs and a replay fold
        // reproduces State exactly.
        let now = chrono::Local::now();
        let cancel_since = |injected: chrono::DateTime<chrono::Local>| {
            let mut state = fresh_state();
            state.now = injected;
            state.turn = start_generating(TurnId(1), std::time::SystemTime::from(injected));
            let (state, cmds) = update(state, Msg::CancelTurn);
            assert!(
                cmds.iter()
                    .any(|c| matches!(c, Cmd::CancelScope(TurnId(1))))
            );
            match state.turn {
                TurnState::Cancelling { since, .. } => since,
                other => panic!("expected Cancelling, got {other:?}"),
            }
        };
        // Same injected clock ⇒ identical result, regardless of real wall time.
        assert_eq!(cancel_since(now), cancel_since(now));
        // And the stamp is exactly the injected value, not "roughly now".
        assert_eq!(cancel_since(now), std::time::SystemTime::from(now));
        // A different injected clock yields a correspondingly different stamp.
        let earlier = now - chrono::Duration::seconds(3600);
        assert_eq!(cancel_since(earlier), std::time::SystemTime::from(earlier));
        assert_ne!(cancel_since(earlier), cancel_since(now));
    }

    #[test]
    fn runtime_signal_exits_and_records_timeline() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::RuntimeSignal(super::super::runtime::RuntimeSignal::Terminate),
        );
        assert!(state.should_exit);
        assert!(cmds.iter().any(|c| matches!(c, Cmd::Exit)));
        assert!(
            state
                .runtime
                .timeline
                .iter()
                .any(|event| event.message.contains("terminate"))
        );
    }

    #[test]
    fn model_switch_updates_provider_capability_snapshot() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::Slash(SlashCmd::Model(Some(
                "anthropic/claude-opus-4-7".to_string(),
            ))),
        );
        assert_eq!(state.runtime.provider_capabilities.provider, "anthropic");
        assert!(state.runtime.provider_capabilities.supports_vision);
        assert!(cmds.iter().any(|c| matches!(c, Cmd::PersistLastModel(_))));
    }

    #[test]
    fn build_chat_request_injects_memory_index() {
        let mut state = fresh_state();
        // No memory loaded → no memory block in the dynamic suffix.
        assert!(
            !build_chat_request(&state)
                .instructions
                .map(|i| i.contains("# Memory"))
                .unwrap_or(false)
        );
        // With memory → the auto-derived index is composed into the suffix.
        state.memory = Some(crate::app::memory::LoadedMemory {
            entries: Vec::new(),
            index: "# Memory\n\n## Global (all projects)\n- [pnpm] use pnpm — /m/pnpm.md\n"
                .to_string(),
            truncated: false,
        });
        let instr = build_chat_request(&state)
            .instructions
            .expect("memory index should populate the instructions suffix");
        assert!(instr.contains("# Memory"));
        assert!(instr.contains("[pnpm] use pnpm"));
    }

    #[test]
    fn build_chat_request_includes_current_working_directory() {
        let state = fresh_state();
        let request = build_chat_request(&state);
        assert!(request.system_prompt.contains("Current Session"));
        assert!(
            request
                .system_prompt
                .contains("Current working directory: /tmp/project")
        );
        assert!(
            request
                .system_prompt
                .contains("Treat this as the project root")
        );
        // The live safety mode must be surfaced so the model knows the current
        // policy instead of inferring it from a stale tool error.
        assert!(
            request.system_prompt.contains("Safety mode: "),
            "system prompt must surface the live safety mode"
        );
    }

    #[test]
    fn esc_during_turn_transitions_to_cancelling() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let msg = Msg::Key(Key {
            code: KeyCode::Escape,
            modifiers: KeyMods::default(),
        });
        let (state, cmds) = update(state, msg);
        assert!(matches!(
            state.turn,
            TurnState::Cancelling { id: TurnId(5), .. }
        ));
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::CancelScope(TurnId(5))))
        );
    }

    #[test]
    fn esc_while_already_cancelling_does_not_exit() {
        // Esc must NEVER quit mermaid — a second Esc mid-cancel is a no-op,
        // not a force-exit. (Regression: it used to call request_exit, which
        // booted the user out and could leave a background process holding the
        // terminal. Only Ctrl+C / `/quit` exit.)
        let mut state = fresh_state();
        state.turn = TurnState::Cancelling {
            id: TurnId(5),
            since: std::time::SystemTime::now(),
        };
        let msg = Msg::Key(Key {
            code: KeyCode::Escape,
            modifiers: KeyMods::default(),
        });
        let (state, cmds) = update(state, msg);
        assert!(!state.should_exit, "Esc must not exit mermaid");
        assert!(
            !cmds.iter().any(|c| matches!(c, Cmd::Exit)),
            "Esc must not emit Cmd::Exit"
        );
        assert!(
            matches!(state.turn, TurnState::Cancelling { id: TurnId(5), .. }),
            "a second Esc mid-cancel leaves the turn cancelling, unchanged"
        );
    }

    #[test]
    fn double_cancel_does_not_emit_twice() {
        let mut state = fresh_state();
        state.turn = TurnState::Cancelling {
            id: TurnId(1),
            since: std::time::SystemTime::now(),
        };
        let (_state, cmds) = update(state, Msg::CancelTurn);
        assert!(cmds.is_empty());
    }

    #[test]
    fn submit_prompt_on_idle_transitions_to_generating() {
        let state = fresh_state();
        let msg = Msg::SubmitPrompt {
            text: "hi there".to_string(),
            attachment_ids: vec![],
        };
        let (state, cmds) = update(state, msg);
        assert!(matches!(state.turn, TurnState::Generating { .. }));
        // CallModel only — instructions/memory freshness comes from the config
        // watcher (#45), so submit neither refreshes inline nor emits a Cmd.
        assert!(cmds.iter().any(|c| matches!(c, Cmd::CallModel { .. })));
        assert!(
            !cmds.iter().any(|c| matches!(c, Cmd::RefreshInstructions)),
            "submit must not emit a refresh Cmd; the watcher keeps config fresh (#45)",
        );
        // user message committed
        assert_eq!(state.session.messages().len(), 1);
        assert_eq!(state.session.messages()[0].content, "hi there");
    }

    #[test]
    fn submit_prompt_when_busy_is_dropped() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(1), std::time::SystemTime::now());
        let msg = Msg::SubmitPrompt {
            text: "ignored".to_string(),
            attachment_ids: vec![],
        };
        let (state, cmds) = update(state, msg);
        assert!(matches!(
            state.turn,
            TurnState::Generating { id: TurnId(1), .. }
        ));
        assert!(cmds.is_empty());
        assert!(state.session.messages().is_empty());
    }

    #[test]
    fn cancelled_turn_submits_oldest_queued_message() {
        let mut state = fresh_state();
        state.turn = TurnState::Cancelling {
            id: TurnId(1),
            since: std::time::SystemTime::now(),
        };
        state
            .ui
            .queued_messages
            .push_back(super::super::state::QueuedMessage {
                text: "first queued".to_string(),
                attachment_ids: Vec::new(),
            });
        state
            .ui
            .queued_messages
            .push_back(super::super::state::QueuedMessage {
                text: "second queued".to_string(),
                attachment_ids: Vec::new(),
            });

        let (state, cmds) = update(state, Msg::TurnCancelled(TurnId(1)));

        assert!(matches!(state.turn, TurnState::Generating { .. }));
        assert!(cmds.iter().any(|cmd| matches!(cmd, Cmd::CallModel { .. })));
        assert_eq!(state.session.messages()[0].content, "first queued");
        assert_eq!(state.ui.queued_messages.len(), 1);
        assert_eq!(
            state.ui.queued_messages.front().map(|q| q.text.as_str()),
            Some("second queued")
        );
    }

    #[test]
    fn submit_prompt_trims_empty_input() {
        let state = fresh_state();
        let msg = Msg::SubmitPrompt {
            text: "   \n\t".to_string(),
            attachment_ids: vec![],
        };
        let (state, cmds) = update(state, msg);
        assert!(matches!(state.turn, TurnState::Idle));
        assert!(cmds.is_empty());
    }

    #[test]
    fn stale_stream_text_dropped_silently() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let msg = Msg::StreamText {
            turn: TurnId(4), // stale!
            chunk: "should be dropped".to_string(),
        };
        let (state, _cmds) = update(state, msg);
        if let TurnState::Generating { partial_text, .. } = &state.turn {
            assert!(partial_text.is_empty());
        } else {
            panic!("expected Generating");
        }
    }

    #[test]
    fn current_turn_stream_text_accumulates() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let (state, _) = update(
            state,
            Msg::StreamText {
                turn: TurnId(5),
                chunk: "hello ".to_string(),
            },
        );
        let (state, _) = update(
            state,
            Msg::StreamText {
                turn: TurnId(5),
                chunk: "world".to_string(),
            },
        );
        if let TurnState::Generating {
            partial_text,
            phase,
            ..
        } = &state.turn
        {
            assert_eq!(partial_text, "hello world");
            assert_eq!(*phase, GenPhase::Streaming);
        } else {
            panic!("expected Generating");
        }
    }

    #[test]
    fn reasoning_chunk_transitions_phase_to_thinking() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let (state, _) = update(
            state,
            Msg::StreamReasoning {
                turn: TurnId(5),
                chunk: crate::models::ReasoningChunk {
                    text: "weighing...".to_string(),
                    signature: None,
                },
            },
        );
        if let TurnState::Generating {
            phase,
            partial_reasoning,
            ..
        } = &state.turn
        {
            assert_eq!(*phase, GenPhase::Thinking);
            assert_eq!(partial_reasoning, "weighing...");
        } else {
            panic!("expected Generating");
        }
    }

    #[test]
    fn stream_done_commits_assistant_message_and_returns_to_idle() {
        let mut state = fresh_state();
        state.turn = TurnState::Generating {
            id: TurnId(5),
            started: std::time::SystemTime::now(),
            partial_text: "final answer".to_string(),
            partial_reasoning: String::new(),
            tokens: 0,
            phase: GenPhase::Streaming,
            thinking_signature: None,
            pending_tool_calls: Vec::new(),
        };
        let (state, cmds) = update(
            state,
            Msg::StreamDone {
                turn: TurnId(5),
                usage: None,
                thinking_signature: None,
                stop_reason: None,
            },
        );
        assert!(matches!(state.turn, TurnState::Idle));
        assert_eq!(state.session.messages().len(), 1);
        assert_eq!(state.session.messages()[0].content, "final answer");
        assert!(cmds.iter().any(|c| matches!(c, Cmd::SaveConversation(_))));
    }

    #[test]
    fn stream_done_tracks_last_and_cumulative_token_usage() {
        let mut state = fresh_state();
        state.turn = TurnState::Generating {
            id: TurnId(5),
            started: std::time::SystemTime::now(),
            partial_text: "final answer".to_string(),
            partial_reasoning: String::new(),
            tokens: 0,
            phase: GenPhase::Streaming,
            thinking_signature: None,
            pending_tool_calls: Vec::new(),
        };

        let (state, _) = update(
            state,
            Msg::StreamDone {
                turn: TurnId(5),
                usage: Some(crate::models::TokenUsage::provider(120, 30, 150)),
                thinking_signature: None,
                stop_reason: None,
            },
        );

        assert_eq!(state.session.last_token_usage.unwrap().prompt_tokens, 120);
        assert_eq!(state.session.cumulative_token_usage.total_tokens, 150);
        assert_eq!(state.session.cumulative_tokens, 150);
        assert_eq!(
            state.session.context_usage.as_ref().unwrap().used_tokens,
            150
        );
    }

    #[test]
    fn context_usage_estimate_is_stored_during_generation() {
        let mut state = fresh_state();
        state.turn = TurnState::Generating {
            id: TurnId(5),
            started: std::time::SystemTime::now(),
            partial_text: String::new(),
            partial_reasoning: String::new(),
            tokens: 0,
            phase: GenPhase::Thinking,
            thinking_signature: None,
            pending_tool_calls: Vec::new(),
        };
        let snapshot = crate::domain::state::ContextUsageSnapshot::from_estimate(
            crate::domain::state::PromptTokenBreakdown {
                system_tokens: 10,
                instructions_tokens: 0,
                message_tokens: 20,
                tool_schema_tokens: 30,
                image_count: 0,
                message_count: 1,
                tool_count: 2,
            },
            Some(1_000),
        );

        let (state, _) = update(
            state,
            Msg::ContextUsageEstimated {
                turn: TurnId(5),
                snapshot,
            },
        );

        let context = state.session.context_usage.expect("context usage");
        assert!(context.is_estimate());
        assert_eq!(context.used_tokens, 60);
        assert_eq!(context.used_percent, Some(6));
    }

    #[test]
    fn context_text_explains_auto_compaction_policy() {
        let mut state = fresh_state();
        state.runtime.provider_capabilities.max_context_tokens = Some(8_000);
        state.session.append(ChatMessage::user("hello"));

        let text = context_text(&state);

        assert!(text.contains("Next request:"));
        assert!(text.contains("Response reserve:"));
        assert!(text.contains("Auto compact threshold:"));
        assert!(text.contains("Auto compact:"));
        assert!(text.contains("Hard limit risk:"));
    }

    /// F4 defense-in-depth: if a later refactor weakens the stale
    /// filter at the top of `update_step`, `handle_upstream_error`
    /// still refuses to mutate state when the error's turn id doesn't
    /// match the active turn. Direct-call the helper to exercise the
    /// guard without relying on the outer filter.
    #[test]
    fn handle_upstream_error_refuses_mismatched_turn_id() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(5), std::time::SystemTime::now());
        let err = crate::models::UserFacingError {
            summary: "Stale".to_string(),
            message: "wrong turn".to_string(),
            suggestion: String::new(),
            category: crate::models::ErrorCategory::Temporary,
            recoverable: true,
        };
        super::handle_upstream_error(&mut state, TurnId(999), err);
        // Active turn must be untouched and no error message committed.
        assert!(matches!(
            state.turn,
            TurnState::Generating { id: TurnId(5), .. }
        ));
        assert!(state.session.messages().is_empty());
    }

    #[test]
    fn upstream_error_ends_turn_and_records_line() {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(1), std::time::SystemTime::now());
        let err = crate::models::UserFacingError {
            summary: "Server error".to_string(),
            message: "500 internal".to_string(),
            suggestion: "retry".to_string(),
            category: crate::models::ErrorCategory::Temporary,
            recoverable: true,
        };
        let (state, _) = update(
            state,
            Msg::UpstreamError {
                turn: TurnId(1),
                error: err,
            },
        );
        assert!(matches!(state.turn, TurnState::Idle));
        assert_eq!(state.session.messages().len(), 1);
        let m = &state.session.messages()[0];
        // Error surfaces through the ActionDisplay only — content is
        // intentionally empty so the chat widget doesn't paint the
        // error twice (once as a content line, once as an action).
        assert_eq!(m.content, "");
        assert_eq!(m.actions.len(), 1);
        assert_eq!(m.actions[0].target, "Server error");
    }

    #[test]
    fn slash_model_with_arg_persists_and_updates_session() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::Slash(SlashCmd::Model(Some("anthropic/opus".to_string()))),
        );
        assert_eq!(state.session.model_id, "anthropic/opus");
        assert!(cmds.iter().any(|c| matches!(c, Cmd::PersistLastModel(_))));
        assert!(
            !cmds
                .iter()
                .any(|c| matches!(c, Cmd::PullOllamaModel { .. }))
        );
    }

    #[test]
    fn slash_model_local_ollama_auto_pulls() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::Slash(SlashCmd::Model(Some("ollama/qwen3:8b".to_string()))),
        );
        assert_eq!(state.session.model_id, "ollama/qwen3:8b");
        assert!(
            cmds.iter()
                .any(|c| { matches!(c, Cmd::PullOllamaModel { model } if model == "qwen3:8b") }),
            "local Ollama model should dispatch pull: {:?}",
            cmds
        );
    }

    #[test]
    fn slash_model_bare_name_auto_pulls_as_ollama() {
        let state = fresh_state();
        let (_, cmds) = update(
            state,
            Msg::Slash(SlashCmd::Model(Some("qwen3-coder:30b".to_string()))),
        );
        assert!(
            cmds.iter().any(|c| {
                matches!(c, Cmd::PullOllamaModel { model } if model == "qwen3-coder:30b")
            }),
            "bare model names should dispatch an Ollama pull: {:?}",
            cmds
        );
    }

    #[test]
    fn slash_model_ollama_cloud_skips_local_pull() {
        let state = fresh_state();
        let (_, cmds) = update(
            state,
            Msg::Slash(SlashCmd::Model(Some("ollama/gpt-oss:cloud".to_string()))),
        );
        assert!(
            !cmds
                .iter()
                .any(|c| matches!(c, Cmd::PullOllamaModel { .. }))
        );
    }

    #[test]
    fn slash_help_appends_system_help_and_persists() {
        let state = fresh_state();
        let (state, cmds) = update(state, Msg::Slash(SlashCmd::Help));
        let msg = state.session.messages().last().expect("help message");
        assert_eq!(msg.role, MessageRole::System);
        assert!(msg.content.contains("Everyday:"));
        assert!(msg.content.contains("Advanced runtime:"));
        assert!(msg.content.contains("/model"));
        assert!(msg.content.contains("/help"));
        assert!(cmds.iter().any(|c| matches!(c, Cmd::SaveConversation(_))));
    }

    #[test]
    fn slash_doctor_appends_session_readiness_report() {
        let state = fresh_state();
        let (state, cmds) = update(state, Msg::Slash(SlashCmd::Doctor));
        let msg = state.session.messages().last().expect("doctor message");
        assert_eq!(msg.role, MessageRole::System);
        assert!(msg.content.contains("Mermaid Doctor"));
        assert!(msg.content.contains("Active model:"));
        assert!(msg.content.contains("Safety:"));
        assert!(cmds.iter().any(|c| matches!(c, Cmd::SaveConversation(_))));
    }

    #[test]
    fn slash_memory_commands_dispatch_effects() {
        // /memory lists; /remember <text> and /forget <id> route to effects.
        let (_s, cmds) = update(fresh_state(), Msg::Slash(SlashCmd::Memory));
        assert!(cmds.iter().any(|c| matches!(c, Cmd::ListMemory)));

        let (_s, cmds) = update(
            fresh_state(),
            Msg::Slash(SlashCmd::Remember(Some("prefer ripgrep".to_string()))),
        );
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::RememberMemory { text } if text == "prefer ripgrep"))
        );

        let (_s, cmds) = update(
            fresh_state(),
            Msg::Slash(SlashCmd::Forget(Some("prefer-rg".to_string()))),
        );
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::ForgetMemory { id } if id == "prefer-rg"))
        );

        // No-arg /remember explains usage instead of dispatching.
        let (state, cmds) = update(fresh_state(), Msg::Slash(SlashCmd::Remember(None)));
        assert!(!cmds.iter().any(|c| matches!(c, Cmd::RememberMemory { .. })));
        assert!(
            state
                .session
                .messages()
                .last()
                .is_some_and(|m| m.content.contains("Usage: /remember")),
            "no-arg /remember posts a usage hint to the transcript"
        );

        // /consolidate-memory routes to the model-assisted prune effect.
        let (_s, cmds) = update(fresh_state(), Msg::Slash(SlashCmd::ConsolidateMemory));
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::ConsolidateMemory { .. }))
        );
    }

    #[test]
    fn chat_request_uses_runtime_prompt_customization() {
        let mut state = fresh_state();
        state.settings.prompt.system_prompt = Some("replacement prompt".to_string());
        state
            .settings
            .prompt
            .append_system_prompt
            .push("extra runtime rule".to_string());

        let request = build_chat_request(&state);
        assert!(request.system_prompt.contains("replacement prompt"));
        assert!(request.system_prompt.contains("extra runtime rule"));
        assert!(!request.system_prompt.contains("Core Loop"));
        assert!(request.system_prompt.contains("Current working directory"));
    }

    #[test]
    fn slash_reasoning_persists_per_model() {
        let state = fresh_state();
        let (state, cmds) = update(
            state,
            Msg::Slash(SlashCmd::Reasoning(Some(
                crate::models::ReasoningLevel::High,
            ))),
        );
        assert_eq!(state.session.reasoning, crate::models::ReasoningLevel::High);
        let emitted = cmds
            .iter()
            .find_map(|c| match c {
                Cmd::PersistReasoningFor { model_id, level } => Some((model_id.clone(), *level)),
                _ => None,
            })
            .expect("persist cmd emitted");
        assert_eq!(emitted.0, "ollama/test");
        assert_eq!(emitted.1, crate::models::ReasoningLevel::High);
    }

    #[test]
    fn slash_visible_reasoning_toggles_runtime_ui_state() {
        let state = fresh_state();
        let (state, _) = update(state, Msg::Slash(SlashCmd::VisibleReasoning(None)));
        assert!(state.ui.show_reasoning);

        let (state, _) = update(
            state,
            Msg::Slash(SlashCmd::VisibleReasoning(Some("off".to_string()))),
        );
        assert!(!state.ui.show_reasoning);
    }

    #[test]
    fn cycle_safety_walks_by_permissiveness() {
        use crate::runtime::SafetyMode as S;
        assert_eq!(cycle_safety(S::ReadOnly), S::Ask);
        assert_eq!(cycle_safety(S::Ask), S::Auto);
        assert_eq!(cycle_safety(S::Auto), S::FullAccess);
        assert_eq!(cycle_safety(S::FullAccess), S::ReadOnly);
    }

    #[test]
    fn shift_tab_cycles_safety_mode() {
        let state = fresh_state();
        let start = state.session.safety_mode;
        let (state, _) = update(
            state,
            Msg::Key(Key {
                code: KeyCode::BackTab,
                modifiers: KeyMods::NONE,
            }),
        );
        assert_eq!(state.session.safety_mode, cycle_safety(start));
    }

    #[test]
    fn slash_safety_sets_session_mode() {
        let state = fresh_state();
        let (state, _) = update(
            state,
            Msg::Slash(SlashCmd::Safety(Some(crate::runtime::SafetyMode::Auto))),
        );
        assert_eq!(state.session.safety_mode, crate::runtime::SafetyMode::Auto);
    }

    /// State with one queued approval (turn must accept the message, so put
    /// the reducer in a live turn first).
    fn pending_approval_state() -> State {
        let mut state = fresh_state();
        state.turn = start_generating(TurnId(1), std::time::SystemTime::now());
        let (state, _) = update(
            state,
            Msg::ApprovalRequested {
                turn: TurnId(1),
                call_id: super::super::ids::ToolCallId(5),
                tool: "execute_command".to_string(),
                risk: "shell_mutation".to_string(),
                kind: crate::domain::ApprovalKind::Shell,
                prompt: "$ npm test".to_string(),
                allowlist_scope: "execute_command:npm".to_string(),
            },
        );
        state
    }

    fn key(code: KeyCode) -> Msg {
        Msg::Key(Key {
            code,
            modifiers: KeyMods::NONE,
        })
    }

    #[test]
    fn ctrl_b_backgrounds_running_tool() {
        let ctrl_b = Msg::Key(Key {
            code: KeyCode::Char('b'),
            modifiers: KeyMods {
                ctrl: true,
                ..KeyMods::NONE
            },
        });
        // While tools are executing → emit BackgroundScope(turn).
        let mut state = fresh_state();
        state.turn = start_executing_tools(TurnId(9), Vec::new(), std::time::SystemTime::now());
        let (_s, cmds) = update(state, ctrl_b.clone());
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::BackgroundScope(t) if *t == TurnId(9))),
            "Ctrl+B during tool execution should background the scope"
        );
        // Idle → swallowed, no BackgroundScope.
        let (_s, cmds) = update(fresh_state(), ctrl_b);
        assert!(!cmds.iter().any(|c| matches!(c, Cmd::BackgroundScope(_))));
    }

    #[test]
    fn paste_interleaved_with_keys_preserves_order() {
        // Reproduces the Windows paste scramble: a paste burst splits into
        // stray Char keys + coalesced Paste chunks. Both must insert at the
        // cursor and advance it, so the result stays in order regardless of
        // the split. (Before the fix, Paste appended to the end while keys
        // inserted at a never-advanced cursor, yielding "RDeview the Docs".)
        let mut state = fresh_state();
        for msg in [
            key(KeyCode::Char('R')),
            Msg::Paste(Paste::Text("eview the ".to_string())),
            key(KeyCode::Char('D')),
            Msg::Paste(Paste::Text("ocs".to_string())),
        ] {
            let (next, _) = update(state, msg);
            state = next;
        }
        assert_eq!(state.ui.input_buffer, "Review the Docs");
        assert_eq!(state.ui.input_cursor, state.ui.input_buffer.len());
    }

    #[test]
    fn paste_inserts_at_cursor_not_end() {
        // Type "ac", move left one, paste "b" → "abc" (not "acb").
        let mut state = fresh_state();
        for msg in [
            key(KeyCode::Char('a')),
            key(KeyCode::Char('c')),
            key(KeyCode::Left),
            Msg::Paste(Paste::Text("b".to_string())),
        ] {
            let (next, _) = update(state, msg);
            state = next;
        }
        assert_eq!(state.ui.input_buffer, "abc");
    }

    #[test]
    fn approval_requested_enqueues_modal() {
        let state = pending_approval_state();
        assert_eq!(state.pending_approval.len(), 1);
        assert_eq!(
            state.pending_approval.front().unwrap().tool,
            "execute_command"
        );
    }

    #[test]
    fn approval_requested_during_cancelling_is_dropped() {
        // #74: a tool task unwinding under cancellation can still emit an
        // ApprovalRequested; parking a modal for it would outlive the turn.
        let mut state = fresh_state();
        state.turn = TurnState::Cancelling {
            id: TurnId(1),
            since: std::time::SystemTime::now(),
        };
        let (state, _) = update(
            state,
            Msg::ApprovalRequested {
                turn: TurnId(1),
                call_id: super::super::ids::ToolCallId(5),
                tool: "execute_command".to_string(),
                risk: "shell_mutation".to_string(),
                kind: crate::domain::ApprovalKind::Shell,
                prompt: "$ rm -rf /".to_string(),
                allowlist_scope: "execute_command:rm".to_string(),
            },
        );
        assert!(
            state.pending_approval.is_empty(),
            "approval for a cancelling turn must not be queued (#74)"
        );
    }

    #[test]
    fn copy_selection_emits_clipboard_cmd_when_nonempty() {
        // #18: the copy side effect flows through the reducer as a Cmd.
        let (_s, cmds) = update(fresh_state(), Msg::CopySelection("hello".to_string()));
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::CopyToClipboard(t) if t == "hello")),
            "non-empty selection should emit CopyToClipboard"
        );
        // An empty selection is a no-op — no clipboard Cmd.
        let (_s, cmds) = update(fresh_state(), Msg::CopySelection(String::new()));
        assert!(!cmds.iter().any(|c| matches!(c, Cmd::CopyToClipboard(_))));
    }

    #[test]
    fn approval_keys_emit_the_right_decision() {
        use crate::domain::ApprovalChoice as A;
        for (code, expected) in [
            (KeyCode::Char('1'), A::Approve),
            (KeyCode::Char('y'), A::Approve),
            (KeyCode::Enter, A::Approve),
            (KeyCode::Char('2'), A::ApproveAlways),
            (KeyCode::Char('a'), A::ApproveAlways),
            (KeyCode::Char('3'), A::Deny),
            (KeyCode::Char('n'), A::Deny),
            (KeyCode::Escape, A::Deny),
        ] {
            let (state, cmds) = update(pending_approval_state(), key(code));
            assert!(
                state.pending_approval.is_empty(),
                "{code:?} should pop the modal"
            );
            assert!(
                cmds.iter().any(
                    |c| matches!(c, Cmd::ResolveApproval { decision, .. } if *decision == expected)
                ),
                "{code:?} should resolve {expected:?}; got {cmds:?}",
            );
            // Esc on an approval denies the tool — it must NOT cancel the turn.
            if code == KeyCode::Escape {
                assert!(
                    !cmds.iter().any(|c| matches!(c, Cmd::CancelScope(_))),
                    "Esc on an approval must deny, not cancel the turn",
                );
            }
        }
    }

    #[test]
    fn approval_modal_swallows_unrelated_keys() {
        let (state, cmds) = update(pending_approval_state(), key(KeyCode::Char('x')));
        assert_eq!(
            state.pending_approval.len(),
            1,
            "unrelated key must not pop the modal"
        );
        assert!(cmds.is_empty());
    }

    #[test]
    fn approval_arrows_move_highlight_without_resolving() {
        // ↓ moves the highlight and clamps at the last option; ↑ moves back.
        // Neither resolves the modal.
        let (state, cmds) = update(pending_approval_state(), key(KeyCode::Down));
        assert_eq!(state.pending_approval.front().unwrap().selected_option, 1);
        assert!(cmds.is_empty() && state.pending_approval.len() == 1);

        let (state, _) = update(state, key(KeyCode::Down));
        assert_eq!(state.pending_approval.front().unwrap().selected_option, 2);
        let (state, _) = update(state, key(KeyCode::Down)); // clamps at 2
        assert_eq!(state.pending_approval.front().unwrap().selected_option, 2);
        let (state, _) = update(state, key(KeyCode::Up));
        assert_eq!(state.pending_approval.front().unwrap().selected_option, 1);
    }

    #[test]
    fn approval_enter_resolves_the_highlighted_option() {
        use crate::domain::ApprovalChoice as A;
        // Highlight option 3 (No) with two ↓, then Enter → Deny.
        let (state, _) = update(pending_approval_state(), key(KeyCode::Down));
        let (state, _) = update(state, key(KeyCode::Down));
        let (state, cmds) = update(state, key(KeyCode::Enter));
        assert!(
            state.pending_approval.is_empty(),
            "Enter should pop the modal"
        );
        assert!(
            cmds.iter().any(
                |c| matches!(c, Cmd::ResolveApproval { decision, .. } if *decision == A::Deny)
            ),
            "Enter on the highlighted 'No' must deny; got {cmds:?}"
        );
    }

    #[test]
    fn approval_fifo_shows_one_at_a_time() {
        let state = pending_approval_state();
        let (state, _) = update(
            state,
            Msg::ApprovalRequested {
                turn: TurnId(1),
                call_id: super::super::ids::ToolCallId(6),
                tool: "write_file".to_string(),
                risk: "file_mutation".to_string(),
                kind: crate::domain::ApprovalKind::FileMutation,
                prompt: "src/x.rs".to_string(),
                allowlist_scope: "write_file".to_string(),
            },
        );
        assert_eq!(state.pending_approval.len(), 2);
        let (state, _) = update(state, key(KeyCode::Char('1')));
        assert_eq!(state.pending_approval.len(), 1);
        assert_eq!(state.pending_approval.front().unwrap().tool, "write_file");
    }

    #[test]
    fn clear_confirm_now_accepts_via_keypress() {
        // Regression: the /clear confirmation was inert (never rendered, never
        // key-handled). It now resolves on a keypress.
        let mut state = fresh_state();
        state.confirm = Some(super::super::state::Confirmation {
            prompt: "Clear conversation history?".to_string(),
            accept_msg_token: super::super::state::ConfirmationTarget::ClearConversation,
        });
        let (state, _) = update(state, key(KeyCode::Char('y')));
        assert!(
            state.confirm.is_none(),
            "y should accept and clear the confirm modal"
        );
    }

    #[test]
    fn slash_clear_raises_confirmation() {
        let state = fresh_state();
        let (state, _) = update(state, Msg::Slash(SlashCmd::Clear));
        assert!(state.confirm.is_some());
    }

    #[test]
    fn confirm_accepted_for_clear_wipes_messages() {
        let mut state = fresh_state();
        state.session.append(ChatMessage::user("one"));
        state.session.append(ChatMessage::assistant("two"));
        state.confirm = Some(super::super::state::Confirmation {
            prompt: "Clear conversation history?".to_string(),
            accept_msg_token: super::super::state::ConfirmationTarget::ClearConversation,
        });
        let (state, _) = update(state, Msg::ConfirmAccepted);
        assert!(state.session.messages().is_empty());
        assert!(state.confirm.is_none());
    }

    #[test]
    fn confirm_declined_clears_without_action() {
        let mut state = fresh_state();
        state.session.append(ChatMessage::user("kept"));
        state.confirm = Some(super::super::state::Confirmation {
            prompt: "Clear conversation history?".to_string(),
            accept_msg_token: super::super::state::ConfirmationTarget::ClearConversation,
        });
        let (state, _) = update(state, Msg::ConfirmDeclined);
        assert_eq!(state.session.messages().len(), 1);
        assert!(state.confirm.is_none());
    }

    #[test]
    fn mcp_server_ready_updates_entry_status() {
        let mut state = fresh_state();
        state.mcp = McpState::default();
        state.mcp.servers.insert(
            "s1".to_string(),
            McpServerEntry {
                config: crate::app::McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: std::collections::HashMap::new(),
                },
                status: McpServerStatus::Starting,
                tools: vec![],
            },
        );
        let (state, _) = update(
            state,
            Msg::McpServerReady {
                name: "s1".to_string(),
                tools: vec![],
            },
        );
        assert_eq!(state.mcp.servers["s1"].status, McpServerStatus::Ready);
    }

    #[test]
    fn mcp_server_errored_sets_status_and_emits_status_line() {
        let mut state = fresh_state();
        state.mcp.servers.insert(
            "s1".to_string(),
            McpServerEntry {
                config: crate::app::McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: std::collections::HashMap::new(),
                },
                status: McpServerStatus::Starting,
                tools: vec![],
            },
        );
        let (state, _) = update(
            state,
            Msg::McpServerErrored {
                name: "s1".to_string(),
                reason: "exit 1".to_string(),
            },
        );
        match &state.mcp.servers["s1"].status {
            McpServerStatus::Errored { reason } => assert_eq!(reason, "exit 1"),
            _ => panic!("expected Errored"),
        }
        assert!(
            state.status.is_none(),
            "no banner — errors go to the transcript"
        );
        assert!(
            state
                .session
                .messages()
                .last()
                .is_some_and(|m| m.content.contains("MCP server s1 errored: exit 1")),
            "the MCP error must be posted to the chat transcript"
        );
    }

    #[test]
    fn tool_finished_with_all_outcomes_triggers_follow_up_call_model() {
        let mut state = fresh_state();
        let call = PendingToolCall {
            call_id: super::super::ids::ToolCallId(1),
            source: crate::models::tool_call::ToolCall {
                id: Some("c1".to_string()),
                function: crate::models::tool_call::FunctionCall {
                    name: "read_file".to_string(),
                    arguments: serde_json::json!({"path": "foo"}),
                },
            },
        };
        state.turn = start_executing_tools(TurnId(3), vec![call], std::time::SystemTime::now());
        // The reducer looks up the "last assistant message" to attach
        // an ActionDisplay — plant one so the lookup doesn't silently
        // no-op in this test.
        state.session.append(ChatMessage::assistant("tools follow"));

        let (state, cmds) = update(
            state,
            Msg::ToolFinished {
                turn: TurnId(3),
                call_id: super::super::ids::ToolCallId(1),
                outcome: ToolOutcome::success("file contents", "file contents", 0.05),
            },
        );

        assert!(matches!(state.turn, TurnState::Generating { .. }));
        assert!(cmds.iter().any(|c| matches!(c, Cmd::CallModel { .. })));
        // Tool result message was appended.
        let last = state.session.messages().last().unwrap();
        assert_eq!(last.role, MessageRole::Tool);
    }

    fn test_attachment(id: u64) -> crate::domain::Attachment {
        crate::domain::Attachment {
            id,
            base64_data: "AAAA".to_string(),
            temp_path: PathBuf::from(format!("/tmp/a{id}.png")),
            size_bytes: 4,
            format: "png".to_string(),
        }
    }

    fn generating(id: u64, partial: &str) -> TurnState {
        TurnState::Generating {
            id: TurnId(id),
            started: std::time::SystemTime::now(),
            partial_text: partial.to_string(),
            partial_reasoning: String::new(),
            tokens: 0,
            phase: GenPhase::Streaming,
            thinking_signature: None,
            pending_tool_calls: Vec::new(),
        }
    }

    #[test]
    fn queued_message_keeps_attachments_from_queue_time() {
        // Axis 1 #1: a message queued while busy must re-submit with the
        // attachments present when it was queued, not whatever is live when the
        // FIFO drains.
        let mut state = fresh_state();
        state.turn = generating(5, "answer");
        state.ui.attachments.push(test_attachment(1));

        // Busy → queued, capturing attachment id 1.
        let (mut state, _) = update(
            state,
            Msg::SubmitPrompt {
                text: "queued".to_string(),
                attachment_ids: vec![1],
            },
        );
        assert_eq!(state.ui.queued_messages.len(), 1);

        // User swaps attachments while the turn is still running.
        state.ui.attachments.clear();
        state.ui.attachments.push(test_attachment(2));

        // Turn completes → queued message drains and re-submits.
        let (state, _) = update(
            state,
            Msg::StreamDone {
                turn: TurnId(5),
                usage: None,
                thinking_signature: None,
                stop_reason: None,
            },
        );

        // The re-submit targeted attachment id 1 (now gone), so live id 2 is
        // untouched — proving the queued ids were used, not the live set.
        assert_eq!(state.ui.attachments.len(), 1);
        assert_eq!(state.ui.attachments[0].id, 2);
        let queued_msg = state
            .session
            .messages()
            .iter()
            .find(|m| m.role == MessageRole::User && m.content == "queued")
            .expect("queued message submitted");
        assert!(queued_msg.images.is_none());
    }

    #[test]
    fn stream_done_without_usage_keeps_previous_last_token_usage() {
        // Axis 1 #2: a turn reporting no usage must not wipe the last request's
        // usage to "n/a".
        let mut state = fresh_state();
        state.turn = generating(1, "first");
        let (mut state, _) = update(
            state,
            Msg::StreamDone {
                turn: TurnId(1),
                usage: Some(crate::models::TokenUsage::provider(120, 30, 150)),
                thinking_signature: None,
                stop_reason: None,
            },
        );
        assert_eq!(state.session.last_token_usage.unwrap().prompt_tokens, 120);

        // A second turn reports no usage (common on tool follow-ups).
        state.turn = generating(2, "second");
        let (state, _) = update(
            state,
            Msg::StreamDone {
                turn: TurnId(2),
                usage: None,
                thinking_signature: None,
                stop_reason: None,
            },
        );
        assert_eq!(
            state
                .session
                .last_token_usage
                .expect("retained")
                .prompt_tokens,
            120
        );
    }

    #[test]
    fn stream_tool_call_outside_generating_is_dropped_without_panic() {
        // Axis 1 #5: a tool-call event arriving after the turn left Generating
        // is dropped (and logged), never panics or mutates state.
        let mut state = fresh_state();
        let call = PendingToolCall {
            call_id: super::super::ids::ToolCallId(1),
            source: crate::models::tool_call::ToolCall {
                id: Some("c1".to_string()),
                function: crate::models::tool_call::FunctionCall {
                    name: "read_file".to_string(),
                    arguments: serde_json::json!({"path": "foo"}),
                },
            },
        };
        state.turn = start_executing_tools(TurnId(3), vec![call], std::time::SystemTime::now());
        let (state, cmds) = update(
            state,
            Msg::StreamToolCall {
                turn: TurnId(3),
                call: crate::models::tool_call::ToolCall {
                    id: Some("late".to_string()),
                    function: crate::models::tool_call::FunctionCall {
                        name: "write_file".to_string(),
                        arguments: serde_json::json!({}),
                    },
                },
            },
        );
        assert!(matches!(state.turn, TurnState::ExecutingTools { .. }));
        assert!(cmds.is_empty());
    }

    #[test]
    fn exit_commits_interrupted_partial_before_saving() {
        // Axis 1 #6: quitting mid-stream preserves the partial assistant reply
        // (with an interrupted marker) so `--continue` shows what was on screen.
        let mut state = fresh_state();
        state.turn = generating(1, "half written");
        let (state, cmds) = update(state, Msg::Quit);
        assert!(state.should_exit);
        let last = state.session.messages().last().expect("a message");
        assert_eq!(last.role, MessageRole::Assistant);
        assert!(last.content.contains("half written"));
        assert!(last.content.contains("[interrupted]"));
        assert!(cmds.iter().any(|c| matches!(c, Cmd::SaveConversation(_))));
    }

    #[test]
    fn submit_clears_attachment_focus_when_consumed() {
        // Axis 1 #7: submitting while the attachment bar is focused must
        // re-clamp the selection so the render layer can't index past the
        // now-empty list.
        let mut state = fresh_state();
        state.ui.attachments.push(test_attachment(1));
        state.ui.attachment_focused = true;
        state.ui.attachment_selected = 0;
        let (state, _) = update(
            state,
            Msg::SubmitPrompt {
                text: "go".to_string(),
                attachment_ids: vec![1],
            },
        );
        assert!(state.ui.attachments.is_empty());
        assert!(!state.ui.attachment_focused);
        assert_eq!(state.ui.attachment_selected, 0);
    }

    #[test]
    fn backgrounded_tool_completes_turn_not_stranded() {
        // Axis 1 #8 (verified non-bug): Ctrl+B fires BackgroundScope but leaves
        // the reducer in ExecutingTools; the detachable tool still returns a
        // success outcome, so the turn advances normally. Locks that behavior.
        let mut state = fresh_state();
        let call = PendingToolCall {
            call_id: super::super::ids::ToolCallId(1),
            source: crate::models::tool_call::ToolCall {
                id: Some("c1".to_string()),
                function: crate::models::tool_call::FunctionCall {
                    name: "execute_command".to_string(),
                    arguments: serde_json::json!({"command": "sleep 9"}),
                },
            },
        };
        state.turn = start_executing_tools(TurnId(3), vec![call], std::time::SystemTime::now());
        state.session.append(ChatMessage::assistant("tools follow"));

        // Ctrl+B → BackgroundScope; reducer stays in ExecutingTools.
        let (state, cmds) = update(
            state,
            Msg::Key(Key {
                code: KeyCode::Char('b'),
                modifiers: KeyMods::ctrl(),
            }),
        );
        assert!(
            cmds.iter()
                .any(|c| matches!(c, Cmd::BackgroundScope(TurnId(3))))
        );
        assert!(matches!(state.turn, TurnState::ExecutingTools { .. }));

        // The detached command returns a normal success outcome → turn advances.
        let (state, cmds) = update(
            state,
            Msg::ToolFinished {
                turn: TurnId(3),
                call_id: super::super::ids::ToolCallId(1),
                outcome: ToolOutcome::success(
                    "Moved to background.\nPID: 1234",
                    "moved to background",
                    0.1,
                ),
            },
        );
        assert!(matches!(state.turn, TurnState::Generating { .. }));
        assert!(cmds.iter().any(|c| matches!(c, Cmd::CallModel { .. })));
    }

    #[test]
    fn builtin_tool_schema_tokens_msg_updates_runtime() {
        // Axis 1 #4: the runner's report lands on runtime state.
        let state = fresh_state();
        let (state, _) = update(state, Msg::BuiltinToolSchemaTokens(4321));
        assert_eq!(state.runtime.builtin_tool_schema_tokens, 4321);
    }

    #[test]
    fn context_text_folds_in_builtin_tool_tokens() {
        // Axis 1 #4: /context shows a disclaimer before the runner reports, and
        // the real figure afterward.
        let mut state = fresh_state();
        let before = context_text(&state);
        assert!(before.contains("built-in tool schemas: measured on the first model call"));

        state.runtime.builtin_tool_schema_tokens = 5000;
        let after = context_text(&state);
        assert!(after.contains("built-in tool schemas:"));
        assert!(!after.contains("measured on the first model call"));
    }

    #[test]
    fn background_command_tool_finish_registers_process() {
        let mut state = fresh_state();
        let call = PendingToolCall {
            call_id: super::super::ids::ToolCallId(1),
            source: crate::models::tool_call::ToolCall {
                id: Some("c1".to_string()),
                function: crate::models::tool_call::FunctionCall {
                    name: "execute_command".to_string(),
                    arguments: serde_json::json!({
                        "command": "npm run dev",
                        "mode": "background",
                        "working_dir": "/tmp/project",
                    }),
                },
            },
        };
        state.turn = start_executing_tools(TurnId(3), vec![call], std::time::SystemTime::now());
        state.session.append(ChatMessage::assistant("tools follow"));

        let (state, _) = update(
            state,
            Msg::ToolFinished {
                turn: TurnId(3),
                call_id: super::super::ids::ToolCallId(1),
                outcome: ToolOutcome::success(
                    "Background command started.\nPID: 123\nLog: /tmp/mermaid-bg.log\nReady: matched pattern \"Local:\"\nDetected URL: http://127.0.0.1:5173\n",
                    "background process started",
                    0.2,
                )
                .with_metadata(crate::domain::ToolRunMetadata {
                    process: Some(crate::domain::ManagedProcess {
                        id: "bg-123".to_string(),
                        pid: 123,
                        command: "npm run dev".to_string(),
                        cwd: Some("/tmp/project".to_string()),
                        log_path: "/tmp/mermaid-bg.log".to_string(),
                        detected_url: Some("http://127.0.0.1:5173".to_string()),
                        status: crate::domain::ManagedProcessStatus::Running,
                    }),
                    ..crate::domain::ToolRunMetadata::default()
                }),
            },
        );

        assert_eq!(state.runtime.processes.len(), 1);
        let process = &state.runtime.processes[0];
        assert_eq!(process.pid, 123);
        assert_eq!(process.command, "npm run dev");
        assert_eq!(process.cwd.as_deref(), Some("/tmp/project"));
        assert_eq!(
            process.detected_url.as_deref(),
            Some("http://127.0.0.1:5173")
        );
    }

    #[test]
    fn tool_finished_partial_stays_in_executing() {
        let mut state = fresh_state();
        let calls = vec![
            PendingToolCall {
                call_id: super::super::ids::ToolCallId(1),
                source: crate::models::tool_call::ToolCall {
                    id: Some("c1".to_string()),
                    function: crate::models::tool_call::FunctionCall {
                        name: "read_file".to_string(),
                        arguments: serde_json::json!({}),
                    },
                },
            },
            PendingToolCall {
                call_id: super::super::ids::ToolCallId(2),
                source: crate::models::tool_call::ToolCall {
                    id: Some("c2".to_string()),
                    function: crate::models::tool_call::FunctionCall {
                        name: "write_file".to_string(),
                        arguments: serde_json::json!({}),
                    },
                },
            },
        ];
        state.turn = start_executing_tools(TurnId(3), calls, std::time::SystemTime::now());
        state.session.append(ChatMessage::assistant("tools follow"));

        let (state, cmds) = update(
            state,
            Msg::ToolFinished {
                turn: TurnId(3),
                call_id: super::super::ids::ToolCallId(1),
                outcome: ToolOutcome::cancelled(),
            },
        );

        // Still in ExecutingTools (second tool pending).
        match &state.turn {
            TurnState::ExecutingTools { outcomes, .. } => {
                assert_eq!(outcomes.len(), 2);
                assert!(outcomes[0].is_some());
                assert!(outcomes[1].is_none());
            },
            _ => panic!("should still be ExecutingTools"),
        }
        assert!(cmds.is_empty());
    }

    #[test]
    fn stale_tool_finished_dropped_silently() {
        let mut state = fresh_state();
        state.turn = start_executing_tools(
            TurnId(3),
            vec![PendingToolCall {
                call_id: super::super::ids::ToolCallId(1),
                source: crate::models::tool_call::ToolCall {
                    id: None,
                    function: crate::models::tool_call::FunctionCall {
                        name: "x".to_string(),
                        arguments: serde_json::json!({}),
                    },
                },
            }],
            std::time::SystemTime::now(),
        );

        let (state, cmds) = update(
            state,
            Msg::ToolFinished {
                turn: TurnId(999),
                call_id: super::super::ids::ToolCallId(1),
                outcome: ToolOutcome::cancelled(),
            },
        );
        match &state.turn {
            TurnState::ExecutingTools { outcomes, .. } => {
                assert!(outcomes[0].is_none());
            },
            _ => panic!("unchanged state expected"),
        }
        assert!(cmds.is_empty());
    }

    #[test]
    fn tick_is_noop() {
        let before = fresh_state();
        let (after, cmds) = update(before.clone(), Msg::Tick);
        assert!(cmds.is_empty());
        assert!(matches!(after.turn, TurnState::Idle));
    }

    #[test]
    fn resize_is_noop() {
        let (state, cmds) = update(
            fresh_state(),
            Msg::Resize {
                width: 80,
                height: 24,
            },
        );
        assert!(cmds.is_empty());
        assert!(matches!(state.turn, TurnState::Idle));
    }

    #[test]
    fn ui_state_default_is_empty() {
        let s = UiState::default();
        assert!(s.input_buffer.is_empty());
        assert_eq!(s.chat_scroll, 0);
        assert!(matches!(s.mode, UiMode::EditingInput));
    }
}