tandem-tui 0.4.26

Terminal user interface for the Tandem engine
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
use serde_json::{json, Value};
use tandem_core::engine_api_token_file_path;
use tokio::time::sleep;

use super::plan_helpers;
use crate::app::{
    Action, AgentStatus, App, AppState, ContentBlock, EngineConnectionSource, EngineStalePolicy,
    MessageRole, ModalState, SetupStep, TandemMode, TaskStatus, UiMode,
};
use crate::command_catalog::HELP_TEXT;

pub(super) async fn try_execute_basic_command(
    app: &mut App,
    cmd_name: &str,
    args: &[&str],
) -> Option<String> {
    match cmd_name {
        "help" => Some(HELP_TEXT.to_string()),
        "diff" => Some(app.open_diff_overlay().await),
        "files" => {
            let query = if args.is_empty() {
                None
            } else {
                Some(args.join(" "))
            };
            app.open_file_search_modal(query.as_deref());
            Some(if let Some(q) = query {
                format!("Opened file search for query: {}", q)
            } else {
                "Opened file search overlay.".to_string()
            })
        }
        "edit" => Some(app.open_external_editor_for_active_input().await),
        "workspace" => Some(match args.first().copied() {
            Some("show") | None => {
                let cwd = std::env::current_dir()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|_| "<unknown>".to_string());
                format!("Current workspace directory:\n  {}", cwd)
            }
            Some("use") => {
                let raw_path = args
                    .get(1..)
                    .map(|items| items.join(" "))
                    .unwrap_or_default();
                if raw_path.trim().is_empty() {
                    return Some("Usage: /workspace use <path>".to_string());
                }
                let target = match App::resolve_workspace_path(raw_path.trim()) {
                    Ok(path) => path,
                    Err(err) => return Some(err),
                };
                let previous = std::env::current_dir()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|_| "<unknown>".to_string());
                if let Err(err) = std::env::set_current_dir(&target) {
                    return Some(format!(
                        "Failed to switch workspace to {}: {}",
                        target.display(),
                        err
                    ));
                }
                let current = std::env::current_dir()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|_| target.display().to_string());
                format!(
                    "Workspace switched.\n  From: {}\n  To:   {}",
                    previous, current
                )
            }
            _ => "Usage: /workspace [show|use <path>]".to_string(),
        }),
        "engine" => Some(match args.first().copied() {
            Some("status") => {
                if let Some(client) = &app.client {
                    match client.get_engine_status().await {
                        Ok(status) => {
                            let required = App::desired_engine_version()
                                .map(App::format_semver_triplet)
                                .unwrap_or_else(|| "unknown".to_string());
                            let stale_policy = EngineStalePolicy::from_env();
                            format!(
                                "Engine Status:\n  Healthy: {}\n  Version: {}\n  Required: {}\n  Mode: {}\n  Endpoint: {}\n  Source: {}\n  Stale policy: {}",
                                if status.healthy { "Yes" } else { "No" },
                                status.version,
                                required,
                                status.mode,
                                client.base_url(),
                                app.engine_connection_source.as_str(),
                                stale_policy.as_str()
                            )
                        }
                        Err(e) => format!("Failed to get engine status: {}", e),
                    }
                } else {
                    "Engine: Not connected".to_string()
                }
            }
            Some("restart") => {
                app.connection_status = "Restarting engine...".to_string();
                app.release_engine_lease().await;
                app.stop_engine_process().await;
                app.client = None;
                app.engine_base_url_override = None;
                app.engine_connection_source = EngineConnectionSource::Unknown;
                app.engine_spawned_at = None;
                app.provider_catalog = None;
                sleep(std::time::Duration::from_millis(300)).await;
                app.state = AppState::Connecting;
                "Engine restart requested.".to_string()
            }
            Some("token") => {
                let show_full = args.get(1).map(|s| s.eq_ignore_ascii_case("show")) == Some(true);
                let Some(token) = app.engine_api_token.as_deref().map(str::trim) else {
                    return Some("Engine token is not configured.".to_string());
                };
                if token.is_empty() {
                    return Some("Engine token is not configured.".to_string());
                }
                let value = if show_full {
                    token.to_string()
                } else {
                    App::masked_engine_api_token(token)
                };
                let path = engine_api_token_file_path().to_string_lossy().to_string();
                let backend = app
                    .engine_api_token_backend
                    .clone()
                    .unwrap_or_else(|| "unknown".to_string());
                if show_full {
                    format!(
                        "Engine API token:\n  {}\nStorage: {}\nPath:\n  {}",
                        value, backend, path
                    )
                } else {
                    format!(
                        "Engine API token (masked):\n  {}\nStorage: {}\nUse `/engine token show` to reveal.\nPath:\n  {}",
                        value, backend, path
                    )
                }
            }
            _ => "Usage: /engine status | restart | token [show]".to_string(),
        }),
        "browser" => Some(match args.first().copied() {
            Some("status") | Some("doctor") => {
                if let Some(client) = &app.client {
                    match client.get_browser_status().await {
                        Ok(status) => {
                            let mut lines = vec![
                                "Browser Status:".to_string(),
                                format!("  Enabled: {}", if status.enabled { "Yes" } else { "No" }),
                                format!(
                                    "  Runnable: {}",
                                    if status.runnable { "Yes" } else { "No" }
                                ),
                                format!(
                                    "  Sidecar: {}",
                                    status
                                        .sidecar
                                        .path
                                        .clone()
                                        .unwrap_or_else(|| "<not found>".to_string())
                                ),
                                format!(
                                    "  Browser: {}",
                                    status
                                        .browser
                                        .path
                                        .clone()
                                        .unwrap_or_else(|| "<not found>".to_string())
                                ),
                            ];
                            if let Some(version) = status.browser.version.as_deref() {
                                lines.push(format!("  Browser version: {}", version));
                            }
                            if !status.blocking_issues.is_empty() {
                                lines.push("Blocking issues:".to_string());
                                for issue in status.blocking_issues {
                                    lines.push(format!("  - {}: {}", issue.code, issue.message));
                                }
                            }
                            if !status.recommendations.is_empty() {
                                lines.push("Recommendations:".to_string());
                                for row in status.recommendations {
                                    lines.push(format!("  - {}", row));
                                }
                            }
                            if !status.install_hints.is_empty() {
                                lines.push("Install hints:".to_string());
                                for row in status.install_hints {
                                    lines.push(format!("  - {}", row));
                                }
                            }
                            lines.join("\n")
                        }
                        Err(e) => format!("Failed to get browser status: {}", e),
                    }
                } else {
                    "Engine: Not connected".to_string()
                }
            }
            _ => "Usage: /browser status | doctor".to_string(),
        }),
        "agent" => Some(match args.first().copied() {
            Some("new") => {
                app.sync_active_agent_from_chat();
                let next_agent_id = if let AppState::Chat { agents, .. } = &app.state {
                    format!("A{}", agents.len() + 1)
                } else {
                    "A1".to_string()
                };
                let mut new_session_id: Option<String> = None;
                if let Some(client) = &app.client {
                    if let Ok(session) = client
                        .create_session(Some(format!("{} session", next_agent_id)))
                        .await
                    {
                        new_session_id = Some(session.id);
                    }
                }
                if let AppState::Chat {
                    agents,
                    active_agent_index,
                    ..
                } = &mut app.state
                {
                    let fallback_session = agents
                        .get(*active_agent_index)
                        .map(|a| a.session_id.clone())
                        .unwrap_or_default();
                    let pane = App::make_agent_pane(
                        next_agent_id,
                        new_session_id.unwrap_or(fallback_session),
                    );
                    agents.push(pane);
                    *active_agent_index = agents.len().saturating_sub(1);
                }
                app.sync_chat_from_active_agent();
                "Created new agent.".to_string()
            }
            Some("list") => {
                if let AppState::Chat {
                    agents,
                    active_agent_index,
                    ..
                } = &app.state
                {
                    let mut out = Vec::new();
                    for (i, a) in agents.iter().enumerate() {
                        let marker = if i == *active_agent_index { ">" } else { " " };
                        out.push(format!(
                            "{} {} [{}] {}",
                            marker,
                            a.agent_id,
                            a.session_id,
                            format!("{:?}", a.status)
                        ));
                    }
                    format!("Agents:\n{}", out.join("\n"))
                } else {
                    "Not in chat.".to_string()
                }
            }
            Some("use") => {
                if let Some(agent_id) = args.get(1) {
                    app.sync_active_agent_from_chat();
                    if let AppState::Chat {
                        agents,
                        active_agent_index,
                        ..
                    } = &mut app.state
                    {
                        if let Some(idx) = agents.iter().position(|a| &a.agent_id == agent_id) {
                            *active_agent_index = idx;
                            app.sync_chat_from_active_agent();
                            return Some(format!("Switched to {}.", agent_id));
                        }
                    }
                    format!("Agent not found: {}", agent_id)
                } else {
                    "Usage: /agent use <A#>".to_string()
                }
            }
            Some("close") => {
                app.sync_active_agent_from_chat();
                let active_idx = if let AppState::Chat {
                    active_agent_index, ..
                } = &app.state
                {
                    *active_agent_index
                } else {
                    0
                };
                app.cancel_agent_if_running(active_idx).await;
                if let AppState::Chat {
                    agents,
                    active_agent_index,
                    grid_page,
                    ..
                } = &mut app.state
                {
                    if agents.len() <= 1 {
                        return Some("Cannot close last agent.".to_string());
                    }
                    agents.remove(active_idx);
                    if *active_agent_index >= agents.len() {
                        *active_agent_index = agents.len().saturating_sub(1);
                    }
                    let max_page = agents.len().saturating_sub(1) / 4;
                    if *grid_page > max_page {
                        *grid_page = max_page;
                    }
                }
                app.sync_chat_from_active_agent();
                "Closed active agent.".to_string()
            }
            Some("fanout") => {
                let mode_switched = if matches!(app.current_mode, TandemMode::Plan) {
                    app.current_mode = TandemMode::Orchestrate;
                    true
                } else {
                    false
                };
                let mode_note = if mode_switched {
                    " Mode auto-switched from plan -> orchestrate."
                } else {
                    ""
                };
                let (target, goal_start_idx) = match args.get(1) {
                    Some(raw) => match raw.parse::<usize>() {
                        Ok(n) => (n.clamp(2, 9), 2),
                        Err(_) => (4, 1),
                    },
                    None => (4, 1),
                };
                let goal = args
                    .iter()
                    .skip(goal_start_idx)
                    .copied()
                    .collect::<Vec<_>>()
                    .join(" ")
                    .trim()
                    .to_string();
                let created = app.ensure_agent_count(target).await;
                if let AppState::Chat {
                    ui_mode, grid_page, ..
                } = &mut app.state
                {
                    *ui_mode = UiMode::Grid;
                    *grid_page = 0;
                }
                app.sync_chat_from_active_agent();
                if !goal.is_empty() {
                    let agents = if let AppState::Chat { agents, .. } = &app.state {
                        agents.iter().take(target).cloned().collect::<Vec<_>>()
                    } else {
                        Vec::new()
                    };
                    if let Some(lead) = agents.first() {
                        let team_name = format!(
                            "fanout-{}",
                            std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map(|d| d.as_secs())
                                .unwrap_or(0)
                        );
                        let create_team_args = serde_json::json!({
                            "team_name": team_name,
                            "description": format!("Fanout run for goal: {}", goal),
                            "agent_type": "lead"
                        });
                        let mut lead_commands =
                            vec![format!("/tool TeamCreate {}", create_team_args)];
                        for agent in agents.iter().skip(1) {
                            let task_prompt = format!(
                                "You are {} in a coordinated fanout run for team `{}`.\n\
                                 Goal: {}.\n\
                                 Own one concrete workstream end-to-end, execute it, and report concise outcomes and blockers.\n\
                                 Do not ask clarification questions unless absolutely blocked.\n\
                                 Do not wait for plan approvals; make reasonable assumptions and proceed.",
                                agent.agent_id, team_name, goal
                            );
                            let task_args = serde_json::json!({
                                "description": format!("{} workstream for {}", agent.agent_id, goal),
                                "prompt": task_prompt,
                                "subagent_type": "generalist",
                                "team_name": team_name,
                                "name": agent.agent_id
                            });
                            lead_commands.push(format!("/tool task {}", task_args));
                        }
                        let lead_kickoff = format!(
                            "You are the lead coordinator for team `{}`. Goal: {}.\n\
                             Use TaskList/TaskUpdate to track delegated progress and keep execution moving until completion.",
                            team_name, goal
                        );
                        lead_commands.push(lead_kickoff);
                        if let AppState::Chat { agents, .. } = &mut app.state {
                            if let Some(lead_agent) = agents.iter_mut().find(|a| {
                                a.agent_id == lead.agent_id && a.session_id == lead.session_id
                            }) {
                                for cmd in lead_commands {
                                    lead_agent.follow_up_queue.push_back(cmd);
                                }
                            }
                        }
                        app.maybe_dispatch_queued_for_agent(&lead.session_id, &lead.agent_id);
                        return Some(format!(
                            "Started coordinated fanout: {} total agents (created {}). Team `{}` bootstrapped and assignments dispatched.{}",
                            target, created, team_name, mode_note
                        ));
                    }
                    return Some(format!(
                        "Started coordinated fanout: {} total agents (created {}). Goal dispatched.{}",
                        target, created, mode_note
                    ));
                }
                if created > 0 {
                    format!(
                        "Started fanout: {} total agents (created {}). Grid view enabled.{}",
                        target, created, mode_note
                    )
                } else {
                    format!(
                        "Fanout ready: already at {}+ agents. Grid view enabled.{}",
                        target, mode_note
                    )
                }
            }
            _ => "Usage: /agent new|list|use <A#>|close|fanout [n] [goal]".to_string(),
        }),
        "sessions" => Some(if app.sessions.is_empty() {
            "No sessions found.".to_string()
        } else {
            let lines: Vec<String> = app
                .sessions
                .iter()
                .enumerate()
                .map(|(i, s)| {
                    let marker = if i == app.selected_session_index {
                        "→ "
                    } else {
                        "  "
                    };
                    format!("{}{} (ID: {})", marker, s.title, s.id)
                })
                .collect();
            format!("Sessions:\n{}", lines.join("\n"))
        }),
        "new" => Some({
            let title = if args.is_empty() {
                None
            } else {
                Some(args.join(" ").trim().to_string())
            };
            let title_for_display = title.clone().unwrap_or_else(|| "New Session".to_string());
            if let Some(client) = &app.client {
                match client.create_session(title).await {
                    Ok(session) => {
                        app.sessions.push(session.clone());
                        app.selected_session_index = app.sessions.len() - 1;
                        format!(
                            "Created session: {} (ID: {})",
                            title_for_display, session.id
                        )
                    }
                    Err(e) => format!("Failed to create session: {}", e),
                }
            } else {
                "Not connected to engine".to_string()
            }
        }),
        "recent" => Some(match args.first().copied() {
            Some("run") => {
                let Some(raw_index) = args.get(1) else {
                    return Some("Usage: /recent run <index>".to_string());
                };
                let Ok(index) = raw_index.parse::<usize>() else {
                    return Some(format!("Invalid recent-command index: {}", raw_index));
                };
                if index == 0 {
                    return Some("Recent-command index is 1-based.".to_string());
                }
                let commands = app.recent_commands_snapshot();
                let Some(command) = commands.get(index - 1).cloned() else {
                    return Some(format!(
                        "Recent-command index {} is out of range ({} stored).",
                        index,
                        commands.len()
                    ));
                };
                let result = Box::pin(app.execute_command(&command)).await;
                format!(
                    "Replayed recent command #{}: {}\n\n{}",
                    index, command, result
                )
            }
            Some("clear") => {
                let cleared = app.clear_recent_commands();
                format!("Cleared {} recent command(s).", cleared)
            }
            Some("list") | None => {
                let commands = app.recent_commands_snapshot();
                if commands.is_empty() {
                    "No recent slash commands yet.".to_string()
                } else {
                    format!(
                        "Recent commands:\n{}\n\nNext\n  /recent run <index>\n  /recent clear",
                        commands
                            .iter()
                            .enumerate()
                            .map(|(idx, command)| format!("  {}. {}", idx + 1, command))
                            .collect::<Vec<_>>()
                            .join("\n")
                    )
                }
            }
            _ => "Usage: /recent [list|run <index>|clear]".to_string(),
        }),
        "use" => Some({
            let Some(target_id) = args.first().copied() else {
                return Some("Usage: /use <session_id>".to_string());
            };
            if let Some(idx) = app.sessions.iter().position(|s| s.id == target_id) {
                app.selected_session_index = idx;
                let loaded_messages = app.load_chat_history(target_id).await;
                let (recalled_tasks, recalled_active_task_id) =
                    plan_helpers::rebuild_tasks_from_messages(&loaded_messages);
                if let AppState::Chat {
                    session_id,
                    messages,
                    scroll_from_bottom,
                    tasks,
                    active_task_id,
                    agents,
                    active_agent_index,
                    ..
                } = &mut app.state
                {
                    *session_id = target_id.to_string();
                    *messages = loaded_messages.clone();
                    *scroll_from_bottom = 0;
                    *tasks = recalled_tasks.clone();
                    *active_task_id = recalled_active_task_id.clone();
                    if let Some(agent) = agents.get_mut(*active_agent_index) {
                        agent.session_id = target_id.to_string();
                        agent.messages = loaded_messages;
                        agent.scroll_from_bottom = 0;
                        agent.tasks = recalled_tasks;
                        agent.active_task_id = recalled_active_task_id;
                    }
                }
                format!("Switched to session: {}", target_id)
            } else {
                format!("Session not found: {}", target_id)
            }
        }),
        "keys" => Some(if let Some(keystore) = &app.keystore {
            let mut provider_ids: Vec<String> = keystore
                .list_keys()
                .into_iter()
                .map(|k| App::normalize_provider_id_from_keystore_key(&k))
                .collect();
            provider_ids.sort();
            provider_ids.dedup();
            if provider_ids.is_empty() {
                "No provider keys configured.".to_string()
            } else {
                format!(
                    "Configured providers:\n{}",
                    provider_ids
                        .iter()
                        .map(|p| format!("  {} - configured", p))
                        .collect::<Vec<_>>()
                        .join("\n")
                )
            }
        } else {
            "Keystore not unlocked. Enter PIN to access keys.".to_string()
        }),
        "key" => Some(match args.first().copied() {
            Some("set") => {
                let provider_id = args
                    .get(1)
                    .map(|s| s.to_string())
                    .or_else(|| app.current_provider.clone());
                let Some(provider_id) = provider_id else {
                    return Some(
                        "Usage: /key set <provider_id> (or set /provider first)".to_string(),
                    );
                };
                if app.open_key_wizard_for_provider(&provider_id) {
                    format!("Opening key setup wizard for {}...", provider_id)
                } else {
                    format!("Provider not found: {}", provider_id)
                }
            }
            Some("remove") => {
                let Some(provider_id) = args.get(1).copied() else {
                    return Some("Usage: /key remove <provider_id>".to_string());
                };
                format!("Key removal not implemented. Provider: {}", provider_id)
            }
            Some("test") => {
                let Some(provider_id) = args.get(1).copied() else {
                    return Some("Usage: /key test <provider_id>".to_string());
                };
                if let Some(client) = &app.client {
                    if let Ok(catalog) = client.list_providers().await {
                        let catalog = App::sanitize_provider_catalog(catalog);
                        let is_connected = catalog.connected.contains(&provider_id.to_string());
                        if catalog.all.iter().any(|p| p.id == provider_id) {
                            if is_connected {
                                return Some(format!(
                                    "Provider {}: Connected and working!",
                                    provider_id
                                ));
                            }
                            return Some(format!(
                                "Provider {}: Not connected. Use /key set to add credentials.",
                                provider_id
                            ));
                        }
                    }
                }
                format!("Provider {}: Not connected or not available.", provider_id)
            }
            _ => "Usage: /key set|remove|test <provider_id>".to_string(),
        }),
        "cancel" => Some({
            let active_idx = if let AppState::Chat {
                active_agent_index, ..
            } = &app.state
            {
                *active_agent_index
            } else {
                0
            };
            app.cancel_agent_if_running(active_idx).await;
            if let AppState::Chat { agents, .. } = &mut app.state {
                if let Some(agent) = agents.get_mut(active_idx) {
                    agent.status = AgentStatus::Idle;
                    agent.active_run_id = None;
                }
            }
            app.sync_chat_from_active_agent();
            "Cancel requested for active agent.".to_string()
        }),
        "steer" => Some({
            if args.is_empty() {
                return Some("Usage: /steer <message>".to_string());
            }
            let msg = args.join(" ");
            if let AppState::Chat { command_input, .. } = &mut app.state {
                command_input.set_text(msg);
            }
            if let Some(tx) = &app.action_tx {
                let _ = tx.send(Action::QueueSteeringFromComposer);
            }
            "Steering message queued.".to_string()
        }),
        "followup" => Some({
            if args.is_empty() {
                return Some("Usage: /followup <message>".to_string());
            }
            let msg = args.join(" ");
            let mut queued_len = 0usize;
            if let AppState::Chat {
                agents,
                active_agent_index,
                ..
            } = &mut app.state
            {
                if let Some(agent) = agents.get_mut(*active_agent_index) {
                    let merged_into_existing = !agent.follow_up_queue.is_empty();
                    if merged_into_existing {
                        if let Some(last) = agent.follow_up_queue.back_mut() {
                            if !last.is_empty() {
                                last.push('\n');
                            }
                            last.push_str(&msg);
                        }
                    } else {
                        agent.follow_up_queue.push_back(msg);
                    }
                    queued_len = agent.follow_up_queue.len();
                }
            }
            format!("Queued follow-up message (#{}).", queued_len)
        }),
        "queue" => Some({
            if matches!(args.first().map(|s| s.to_ascii_lowercase()), Some(cmd) if cmd == "clear") {
                if let AppState::Chat {
                    agents,
                    active_agent_index,
                    ..
                } = &mut app.state
                {
                    if let Some(agent) = agents.get_mut(*active_agent_index) {
                        agent.follow_up_queue.clear();
                        agent.steering_message = None;
                    }
                }
                return Some("Cleared queued steering and follow-up messages.".to_string());
            }
            if let AppState::Chat {
                agents,
                active_agent_index,
                ..
            } = &app.state
            {
                if let Some(agent) = agents.get(*active_agent_index) {
                    let steering = if agent.steering_message.is_some() {
                        "yes"
                    } else {
                        "no"
                    };
                    let next_followup = agent
                        .follow_up_queue
                        .front()
                        .map(|m| {
                            if m.chars().count() > 80 {
                                format!("{}...", m.chars().take(80).collect::<String>())
                            } else {
                                m.clone()
                            }
                        })
                        .unwrap_or_else(|| "(none)".to_string());
                    return Some(format!(
                        "Queue status:\n  steering: {}\n  follow-ups: {}\n  next: {}",
                        steering,
                        agent.follow_up_queue.len(),
                        next_followup
                    ));
                }
            }
            "Queue unavailable in current state.".to_string()
        }),
        "messages" => Some({
            let limit = args.first().and_then(|s| s.parse().ok()).unwrap_or(10);
            format!("Message history not implemented yet. (limit: {})", limit)
        }),
        "last_error" => Some(if let AppState::Chat { messages, .. } = &app.state {
            let maybe_error = messages.iter().rev().find_map(|m| {
                if m.role != MessageRole::System {
                    return None;
                }
                let text = m
                    .content
                    .iter()
                    .filter_map(|b| match b {
                        ContentBlock::Text(t) => Some(t.as_str()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                if text.to_lowercase().contains("failed") || text.to_lowercase().contains("error") {
                    Some(text)
                } else {
                    None
                }
            });
            maybe_error.unwrap_or_else(|| "No recent error found.".to_string())
        } else {
            "Not in a chat session.".to_string()
        }),
        "task" => Some(if let AppState::Chat { tasks, .. } = &mut app.state {
            match args.first().copied() {
                Some("add") => {
                    if args.len() < 2 {
                        return Some("Usage: /task add <description>".to_string());
                    }
                    let description = args[1..].join(" ");
                    let id = format!("task-{}", tasks.len() + 1);
                    tasks.push(crate::app::Task {
                        id: id.clone(),
                        description: description.clone(),
                        status: TaskStatus::Pending,
                        pinned: false,
                    });
                    format!("Task added: {} (ID: {})", description, id)
                }
                Some("done") | Some("fail") | Some("work") | Some("pending") => {
                    if args.len() < 2 {
                        return Some("Usage: /task <status> <id>".to_string());
                    }
                    let id = args[1];
                    if let Some(task) = tasks.iter_mut().find(|t| t.id == id) {
                        match args[0] {
                            "done" => task.status = TaskStatus::Done,
                            "fail" => task.status = TaskStatus::Failed,
                            "work" => task.status = TaskStatus::Working,
                            "pending" => task.status = TaskStatus::Pending,
                            _ => {}
                        }
                        format!("Task {} marked as {}", id, args[0])
                    } else {
                        format!("Task not found: {}", id)
                    }
                }
                Some("pin") => {
                    if args.len() < 2 {
                        return Some("Usage: /task pin <id>".to_string());
                    }
                    let id = args[1];
                    if let Some(task) = tasks.iter_mut().find(|t| t.id == id) {
                        task.pinned = !task.pinned;
                        format!("Task {} pinned: {}", id, task.pinned)
                    } else {
                        format!("Task not found: {}", id)
                    }
                }
                Some("list") => {
                    if tasks.is_empty() {
                        "No tasks.".to_string()
                    } else {
                        let lines: Vec<String> = tasks
                            .iter()
                            .map(|t| {
                                format!(
                                    "[{}] {} ({:?}) - Pinned: {}",
                                    t.id, t.description, t.status, t.pinned
                                )
                            })
                            .collect();
                        format!("Tasks:\n{}", lines.join("\n"))
                    }
                }
                _ => "Usage: /task add|done|fail|work|pin|list ...".to_string(),
            }
        } else {
            "Not in a chat session.".to_string()
        }),
        "prompt" => Some({
            let text = args.join(" ");
            if text.is_empty() {
                return Some("Usage: /prompt <text...>".to_string());
            }
            let (session_id, active_agent_id) = if let AppState::Chat {
                session_id,
                agents,
                active_agent_index,
                ..
            } = &mut app.state
            {
                let agent_id = agents
                    .get(*active_agent_index)
                    .map(|a| a.agent_id.clone())
                    .unwrap_or_else(|| "A1".to_string());
                (session_id.clone(), agent_id)
            } else {
                (String::new(), "A1".to_string())
            };

            if session_id.is_empty() {
                return Some("Not in a chat session. Use /use <session_id> first.".to_string());
            }
            app.dispatch_prompt_for_agent(session_id, active_agent_id, text);
            "Prompt sent.".to_string()
        }),
        "title" => Some({
            let new_title = args.join(" ");
            if new_title.is_empty() {
                return Some("Usage: /title <new title...>".to_string());
            }
            if let AppState::Chat { session_id, .. } = &mut app.state {
                if let Some(client) = &app.client {
                    let req = crate::net::client::UpdateSessionRequest {
                        title: Some(new_title.clone()),
                        ..Default::default()
                    };
                    if let Ok(_session) = client.update_session(session_id, req).await {
                        if let Some(s) = app.sessions.iter_mut().find(|s| &s.id == session_id) {
                            s.title = new_title.clone();
                        }
                        return Some(format!("Session renamed to: {}", new_title));
                    }
                }
                "Failed to rename session.".to_string()
            } else {
                "Not in a chat session.".to_string()
            }
        }),
        "missions" => Some({
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            match client.mission_list().await {
                Ok(missions) => {
                    if missions.is_empty() {
                        return Some("No missions found.".to_string());
                    }
                    let lines = missions
                        .into_iter()
                        .map(|mission| {
                            format!(
                                "- {} [{}] {} (work_items={})",
                                mission.mission_id,
                                format!("{:?}", mission.status).to_lowercase(),
                                mission.spec.title,
                                mission.work_items.len()
                            )
                        })
                        .collect::<Vec<_>>();
                    format!("Missions:\n{}", lines.join("\n"))
                }
                Err(err) => format!("Failed to list missions: {}", err),
            }
        }),
        "mission_create" => Some({
            if args.is_empty() {
                return Some(
                    "Usage: /mission_create <title> :: <goal> [:: work_item_title]".to_string(),
                );
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let raw = args.join(" ");
            let segments = raw
                .split("::")
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>();
            if segments.len() < 2 {
                return Some(
                    "Usage: /mission_create <title> :: <goal> [:: work_item_title]".to_string(),
                );
            }
            let work_items = if let Some(work_item_title) = segments.get(2) {
                vec![crate::net::client::MissionCreateWorkItem {
                    work_item_id: None,
                    title: (*work_item_title).to_string(),
                    detail: None,
                    assigned_agent: None,
                }]
            } else {
                vec![crate::net::client::MissionCreateWorkItem {
                    work_item_id: None,
                    title: "Initial implementation".to_string(),
                    detail: Some("Auto-seeded work item".to_string()),
                    assigned_agent: None,
                }]
            };
            let request = crate::net::client::MissionCreateRequest {
                title: segments[0].to_string(),
                goal: segments[1].to_string(),
                work_items,
            };
            match client.mission_create(request).await {
                Ok(mission) => format!(
                    "Created mission {}: {}",
                    mission.mission_id, mission.spec.title
                ),
                Err(err) => format!("Failed to create mission: {}", err),
            }
        }),
        "mission_get" => Some({
            if args.len() != 1 {
                return Some("Usage: /mission_get <mission_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            match client.mission_get(args[0]).await {
                Ok(mission) => {
                    let item_lines = mission
                        .work_items
                        .iter()
                        .map(|item| {
                            format!(
                                "- {} [{}]",
                                item.title,
                                format!("{:?}", item.status).to_lowercase()
                            )
                        })
                        .collect::<Vec<_>>();
                    format!(
                        "Mission {} [{}]\nTitle: {}\nGoal: {}\nWork Items:\n{}",
                        mission.mission_id,
                        format!("{:?}", mission.status).to_lowercase(),
                        mission.spec.title,
                        mission.spec.goal,
                        if item_lines.is_empty() {
                            "- (none)".to_string()
                        } else {
                            item_lines.join("\n")
                        }
                    )
                }
                Err(err) => format!("Failed to get mission: {}", err),
            }
        }),
        "mission_event" => Some({
            if args.len() < 2 {
                return Some("Usage: /mission_event <mission_id> <event_json>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let mission_id = args[0];
            let raw_json = args[1..].join(" ");
            let event = match serde_json::from_str::<Value>(&raw_json) {
                Ok(value) => value,
                Err(err) => return Some(format!("Invalid event JSON: {}", err)),
            };
            match client.mission_apply_event(mission_id, event).await {
                Ok(result) => format!(
                    "Applied event to mission {} (revision={}, commands={})",
                    result.mission.mission_id,
                    result.mission.revision,
                    result.commands.len()
                ),
                Err(err) => format!("Failed to apply mission event: {}", err),
            }
        }),
        "mission_start" => Some({
            if args.len() != 1 {
                return Some("Usage: /mission_start <mission_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let mission_id = args[0];
            let event = serde_json::json!({
                "type": "mission_started",
                "mission_id": mission_id
            });
            match client.mission_apply_event(mission_id, event).await {
                Ok(result) => format!(
                    "Mission started {} (revision={})",
                    result.mission.mission_id, result.mission.revision
                ),
                Err(err) => format!("Failed to start mission: {}", err),
            }
        }),
        "mission_review_ok" => Some({
            if args.len() < 2 {
                return Some(
                    "Usage: /mission_review_ok <mission_id> <work_item_id> [approval_id]"
                        .to_string(),
                );
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let mission_id = args[0];
            let work_item_id = args[1];
            let approval_id = args.get(2).copied().unwrap_or("review-1");
            let event = serde_json::json!({
                "type": "approval_granted",
                "mission_id": mission_id,
                "work_item_id": work_item_id,
                "approval_id": approval_id
            });
            match client.mission_apply_event(mission_id, event).await {
                Ok(result) => format!(
                    "Review approved for {}:{} (revision={})",
                    mission_id, work_item_id, result.mission.revision
                ),
                Err(err) => format!("Failed to approve review: {}", err),
            }
        }),
        "mission_test_ok" => Some({
            if args.len() < 2 {
                return Some(
                    "Usage: /mission_test_ok <mission_id> <work_item_id> [approval_id]".to_string(),
                );
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let mission_id = args[0];
            let work_item_id = args[1];
            let approval_id = args.get(2).copied().unwrap_or("test-1");
            let event = serde_json::json!({
                "type": "approval_granted",
                "mission_id": mission_id,
                "work_item_id": work_item_id,
                "approval_id": approval_id
            });
            match client.mission_apply_event(mission_id, event).await {
                Ok(result) => format!(
                    "Test approved for {}:{} (revision={})",
                    mission_id, work_item_id, result.mission.revision
                ),
                Err(err) => format!("Failed to approve test: {}", err),
            }
        }),
        "mission_review_no" => Some({
            if args.len() < 2 {
                return Some(
                    "Usage: /mission_review_no <mission_id> <work_item_id> [reason]".to_string(),
                );
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let mission_id = args[0];
            let work_item_id = args[1];
            let reason = if args.len() > 2 {
                args[2..].join(" ")
            } else {
                "needs_revision".to_string()
            };
            let event = serde_json::json!({
                "type": "approval_denied",
                "mission_id": mission_id,
                "work_item_id": work_item_id,
                "approval_id": "review-1",
                "reason": reason
            });
            match client.mission_apply_event(mission_id, event).await {
                Ok(result) => format!(
                    "Review denied for {}:{} (revision={})",
                    mission_id, work_item_id, result.mission.revision
                ),
                Err(err) => format!("Failed to deny review: {}", err),
            }
        }),
        "agent-team" | "agent_team" => Some({
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let sub = args.first().copied().unwrap_or("summary");
            match sub {
                "summary" => {
                    let missions = client.agent_team_missions().await;
                    let instances = client.agent_team_instances(None).await;
                    let approvals = client.agent_team_approvals().await;
                    match (missions, instances, approvals) {
                        (Ok(missions), Ok(instances), Ok(approvals)) => format!(
                            "Agent-Team Summary:\n  Missions: {}\n  Instances: {}\n  Spawn approvals: {}\n  Tool approvals: {}",
                            missions.len(),
                            instances.len(),
                            approvals.spawn_approvals.len(),
                            approvals.tool_approvals.len()
                        ),
                        _ => "Failed to load agent-team summary.".to_string(),
                    }
                }
                "missions" => match client.agent_team_missions().await {
                    Ok(missions) => {
                        if missions.is_empty() {
                            return Some("No agent-team missions found.".to_string());
                        }
                        let lines = missions
                            .into_iter()
                            .map(|mission| {
                                format!(
                                    "- {} total={} running={} done={} failed={} cancelled={}",
                                    mission.mission_id,
                                    mission.instance_count,
                                    mission.running_count,
                                    mission.completed_count,
                                    mission.failed_count,
                                    mission.cancelled_count
                                )
                            })
                            .collect::<Vec<_>>();
                        format!("Agent-Team Missions:\n{}", lines.join("\n"))
                    }
                    Err(err) => format!("Failed to list agent-team missions: {}", err),
                },
                "instances" => {
                    let mission_id = args.get(1).copied();
                    match client.agent_team_instances(mission_id).await {
                        Ok(instances) => {
                            if instances.is_empty() {
                                return Some("No agent-team instances found.".to_string());
                            }
                            let lines = instances
                                .into_iter()
                                .map(|instance| {
                                    format!(
                                        "- {} role={} mission={} status={} parent={}",
                                        instance.instance_id,
                                        instance.role,
                                        instance.mission_id,
                                        instance.status,
                                        instance
                                            .parent_instance_id
                                            .unwrap_or_else(|| "-".to_string())
                                    )
                                })
                                .collect::<Vec<_>>();
                            format!("Agent-Team Instances:\n{}", lines.join("\n"))
                        }
                        Err(err) => format!("Failed to list agent-team instances: {}", err),
                    }
                }
                "approvals" => match client.agent_team_approvals().await {
                    Ok(approvals) => {
                        let mut lines = Vec::new();
                        for spawn in approvals.spawn_approvals {
                            lines.push(format!("- spawn approval {}", spawn.approval_id));
                        }
                        for tool in approvals.tool_approvals {
                            lines.push(format!(
                                "- tool approval {} ({})",
                                tool.approval_id,
                                tool.tool.unwrap_or_else(|| "tool".to_string())
                            ));
                        }
                        if lines.is_empty() {
                            "No agent-team approvals pending.".to_string()
                        } else {
                            format!("Agent-Team Approvals:\n{}", lines.join("\n"))
                        }
                    }
                    Err(err) => format!("Failed to list agent-team approvals: {}", err),
                },
                "bindings" => {
                    let team_filter = args.get(1).copied();
                    App::format_local_agent_team_bindings(team_filter)
                }
                "approve" => {
                    if args.len() < 3 {
                        return Some(
                            "Usage: /agent-team approve <spawn|tool> <id> [reason]".to_string(),
                        );
                    }
                    let target = args[1];
                    let id = args[2];
                    let reason = if args.len() > 3 {
                        args[3..].join(" ")
                    } else {
                        "approved in TUI".to_string()
                    };
                    match target {
                        "spawn" => match client.agent_team_approve_spawn(id, &reason).await {
                            Ok(true) => format!("Approved spawn approval {}.", id),
                            Ok(false) => format!("Spawn approval not found or denied: {}", id),
                            Err(err) => format!("Failed to approve spawn approval: {}", err),
                        },
                        "tool" => match client.reply_permission(id, "allow").await {
                            Ok(true) => format!("Approved tool request {}.", id),
                            Ok(false) => format!("Tool request not found: {}", id),
                            Err(err) => format!("Failed to approve tool request: {}", err),
                        },
                        _ => "Usage: /agent-team approve <spawn|tool> <id> [reason]".to_string(),
                    }
                }
                "deny" => {
                    if args.len() < 3 {
                        return Some(
                            "Usage: /agent-team deny <spawn|tool> <id> [reason]".to_string(),
                        );
                    }
                    let target = args[1];
                    let id = args[2];
                    let reason = if args.len() > 3 {
                        args[3..].join(" ")
                    } else {
                        "denied in TUI".to_string()
                    };
                    match target {
                        "spawn" => match client.agent_team_deny_spawn(id, &reason).await {
                            Ok(true) => format!("Denied spawn approval {}.", id),
                            Ok(false) => {
                                format!("Spawn approval not found or already resolved: {}", id)
                            }
                            Err(err) => format!("Failed to deny spawn approval: {}", err),
                        },
                        "tool" => match client.reply_permission(id, "deny").await {
                            Ok(true) => format!("Denied tool request {}.", id),
                            Ok(false) => format!("Tool request not found: {}", id),
                            Err(err) => format!("Failed to deny tool request: {}", err),
                        },
                        _ => "Usage: /agent-team deny <spawn|tool> <id> [reason]".to_string(),
                    }
                }
                _ => {
                    "Usage: /agent-team [summary|missions|instances [mission_id]|approvals|bindings [team]|approve <spawn|tool> <id> [reason]|deny <spawn|tool> <id> [reason]]".to_string()
                }
            }
        }),
        "preset" | "presets" => Some({
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let sub = args.first().copied().unwrap_or("help").to_ascii_lowercase();
            match sub.as_str() {
                "index" => match client.presets_index().await {
                    Ok(index) => format!(
                        "Preset index:\n  skill_modules: {}\n  agent_presets: {}\n  automation_presets: {}\n  pack_presets: {}\n  generated_at_ms: {}",
                        index.skill_modules.len(),
                        index.agent_presets.len(),
                        index.automation_presets.len(),
                        index.pack_presets.len(),
                        index.generated_at_ms
                    ),
                    Err(err) => format!("Failed to load preset index: {}", err),
                },
                "agent" => {
                    let action = args.get(1).copied().unwrap_or("help").to_ascii_lowercase();
                    match action.as_str() {
                        "compose" => {
                            let tail = args.get(2..).unwrap_or(&[]).join(" ");
                            let mut pieces = tail.splitn(2, "::");
                            let base_prompt = pieces.next().unwrap_or("").trim();
                            let fragments_raw = pieces.next().unwrap_or("").trim();
                            if base_prompt.is_empty() || fragments_raw.is_empty() {
                                return Some(
                                    "Usage: /preset agent compose <base_prompt> :: <fragments_json>"
                                        .to_string(),
                                );
                            }
                            let fragments_json =
                                match serde_json::from_str::<Value>(fragments_raw) {
                                    Ok(value) if value.is_array() => value,
                                    Ok(_) => {
                                        return Some(
                                            "fragments_json must be a JSON array of {id,phase,content}"
                                                .to_string(),
                                        );
                                    }
                                    Err(err) => return Some(format!("Invalid fragments_json: {}", err)),
                                };
                            let request = json!({
                                "base_prompt": base_prompt,
                                "fragments": fragments_json,
                            });
                            match client.presets_compose_preview(request).await {
                                Ok(payload) => {
                                    let composition =
                                        payload.get("composition").cloned().unwrap_or(payload);
                                    format!(
                                        "Agent compose preview:\n{}",
                                        serde_json::to_string_pretty(&composition)
                                            .unwrap_or_else(|_| "{}".to_string())
                                    )
                                }
                                Err(err) => format!("Compose preview failed: {}", err),
                            }
                        }
                        "summary" => {
                            let tail = args.get(2..).unwrap_or(&[]).join(" ");
                            let (required, optional) =
                                App::parse_required_optional_segments(&tail);
                            let request = json!({
                                "agent": {
                                    "required": required,
                                    "optional": optional,
                                },
                                "tasks": [],
                            });
                            match client.presets_capability_summary(request).await {
                                Ok(payload) => {
                                    let summary = payload.get("summary").cloned().unwrap_or(payload);
                                    format!(
                                        "Agent capability summary:\n{}",
                                        serde_json::to_string_pretty(&summary)
                                            .unwrap_or_else(|_| "{}".to_string())
                                    )
                                }
                                Err(err) => format!("Capability summary failed: {}", err),
                            }
                        }
                        "fork" => {
                            if args.len() < 3 {
                                return Some(
                                    "Usage: /preset agent fork <source_path> [target_id]".to_string(),
                                );
                            }
                            let source_path = args[2];
                            let target_id = args.get(3).copied();
                            let request = json!({
                                "kind": "agent_preset",
                                "source_path": source_path,
                                "target_id": target_id,
                            });
                            match client.presets_fork(request).await {
                                Ok(payload) => format!(
                                    "Forked agent preset override:\n{}",
                                    serde_json::to_string_pretty(&payload)
                                        .unwrap_or_else(|_| "{}".to_string())
                                ),
                                Err(err) => format!("Agent preset fork failed: {}", err),
                            }
                        }
                        _ => "Usage: /preset agent <compose|summary|fork> ...".to_string(),
                    }
                }
                "automation" => {
                    let action = args.get(1).copied().unwrap_or("help").to_ascii_lowercase();
                    match action.as_str() {
                        "summary" => {
                            let tail = args.get(2..).unwrap_or(&[]).join(" ");
                            let segments = tail
                                .split("::")
                                .map(str::trim)
                                .filter(|part| !part.is_empty())
                                .collect::<Vec<_>>();
                            if segments.is_empty() {
                                return Some("Usage: /preset automation summary <tasks_json> [:: required=<csv> :: optional=<csv>]".to_string());
                            }
                            let tasks_json = match serde_json::from_str::<Value>(segments[0]) {
                                Ok(value) => value,
                                Err(err) => return Some(format!("Invalid tasks_json: {}", err)),
                            };
                            let tasks = match App::normalize_automation_tasks(&tasks_json) {
                                Ok(items) => items,
                                Err(err) => return Some(err),
                            };
                            let (required, optional) = if segments.len() > 1 {
                                App::parse_required_optional_segments(&segments[1..].join(" :: "))
                            } else {
                                (Vec::new(), Vec::new())
                            };
                            let capability_tasks = tasks
                                .iter()
                                .map(|task| {
                                    json!({
                                        "required": task.get("required").cloned().unwrap_or_else(|| json!([])),
                                        "optional": task.get("optional").cloned().unwrap_or_else(|| json!([])),
                                    })
                                })
                                .collect::<Vec<_>>();
                            let request = json!({
                                "agent": {
                                    "required": required,
                                    "optional": optional,
                                },
                                "tasks": capability_tasks,
                            });
                            match client.presets_capability_summary(request).await {
                                Ok(payload) => {
                                    let summary = payload.get("summary").cloned().unwrap_or(payload);
                                    format!(
                                        "Automation capability summary ({} tasks):\n{}",
                                        tasks.len(),
                                        serde_json::to_string_pretty(&summary)
                                            .unwrap_or_else(|_| "{}".to_string())
                                    )
                                }
                                Err(err) => format!("Automation summary failed: {}", err),
                            }
                        }
                        "save" => {
                            let tail = args.get(2..).unwrap_or(&[]).join(" ");
                            let segments = tail
                                .split("::")
                                .map(str::trim)
                                .filter(|part| !part.is_empty())
                                .collect::<Vec<_>>();
                            if segments.len() < 2 {
                                return Some("Usage: /preset automation save <id> :: <tasks_json> [:: required=<csv> :: optional=<csv>]".to_string());
                            }
                            let id = segments[0];
                            if id.is_empty() {
                                return Some("Automation preset id is required.".to_string());
                            }
                            let tasks_json = match serde_json::from_str::<Value>(segments[1]) {
                                Ok(value) => value,
                                Err(err) => return Some(format!("Invalid tasks_json: {}", err)),
                            };
                            let tasks = match App::normalize_automation_tasks(&tasks_json) {
                                Ok(items) => items,
                                Err(err) => return Some(err),
                            };
                            let (required, optional) = if segments.len() > 2 {
                                App::parse_required_optional_segments(&segments[2..].join(" :: "))
                            } else {
                                (Vec::new(), Vec::new())
                            };
                            let capability_tasks = tasks
                                .iter()
                                .map(|task| {
                                    json!({
                                        "required": task.get("required").cloned().unwrap_or_else(|| json!([])),
                                        "optional": task.get("optional").cloned().unwrap_or_else(|| json!([])),
                                    })
                                })
                                .collect::<Vec<_>>();
                            let summary_request = json!({
                                "agent": {
                                    "required": required,
                                    "optional": optional,
                                },
                                "tasks": capability_tasks,
                            });
                            let summary_payload =
                                match client.presets_capability_summary(summary_request).await {
                                    Ok(payload) => payload,
                                    Err(err) => {
                                        return Some(format!("Automation summary failed: {}", err));
                                    }
                                };
                            let summary = summary_payload
                                .get("summary")
                                .cloned()
                                .unwrap_or_else(|| json!({}));
                            let yaml = App::automation_override_yaml(id, &tasks, &summary);
                            match client
                                .presets_override_put("automation_preset", id, &yaml)
                                .await
                            {
                                Ok(payload) => format!(
                                    "Saved automation preset override `{}` with {} task(s).\n{}",
                                    id,
                                    tasks.len(),
                                    serde_json::to_string_pretty(&payload)
                                        .unwrap_or_else(|_| "{}".to_string())
                                ),
                                Err(err) => format!("Automation override save failed: {}", err),
                            }
                        }
                        _ => "Usage: /preset automation <summary|save> ...".to_string(),
                    }
                }
                _ => "Usage: /preset <index|agent|automation> ...".to_string(),
            }
        }),
        "context_runs" => Some({
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let limit = args
                .first()
                .and_then(|value| value.parse::<usize>().ok())
                .unwrap_or(20);
            match client.context_runs_list().await {
                Ok(mut runs) => {
                    if runs.is_empty() {
                        return Some("No context runs found.".to_string());
                    }
                    runs.sort_by(|a, b| b.updated_at_ms.cmp(&a.updated_at_ms));
                    let lines = runs
                        .into_iter()
                        .take(limit)
                        .map(|run| {
                            format!(
                                "- {} [{}] type={} steps={} updated_at={}\n  objective: {}",
                                run.run_id,
                                format!("{:?}", run.status).to_lowercase(),
                                run.run_type,
                                run.steps.len(),
                                run.updated_at_ms,
                                run.objective
                            )
                        })
                        .collect::<Vec<_>>();
                    format!("Context runs:\n{}", lines.join("\n"))
                }
                Err(err) => format!("Failed to list context runs: {}", err),
            }
        }),
        "context_run_create" => Some({
            if args.is_empty() {
                return Some("Usage: /context_run_create <objective...>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let objective = args.join(" ");
            match client
                .context_run_create(None, objective, Some("interactive".to_string()), None)
                .await
            {
                Ok(run) => format!("Created context run {} [{}].", run.run_id, run.run_type),
                Err(err) => format!("Failed to create context run: {}", err),
            }
        }),
        "context_run_get" => Some({
            if args.len() != 1 {
                return Some("Usage: /context_run_get <run_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            match client.context_run_get(run_id).await {
                Ok(detail) => {
                    let run = detail.run;
                    let rollback_preview_steps = detail
                        .rollback_preview_summary
                        .get("step_count")
                        .and_then(|value| value.as_u64())
                        .unwrap_or(0);
                    let rollback_history_entries = detail
                        .rollback_history_summary
                        .get("entry_count")
                        .and_then(|value| value.as_u64())
                        .unwrap_or(0);
                    let rollback_policy_eligible = detail
                        .rollback_policy
                        .get("eligible")
                        .and_then(|value| value.as_bool())
                        .unwrap_or(false);
                    let rollback_required_ack = detail
                        .rollback_policy
                        .get("required_policy_ack")
                        .and_then(|value| value.as_str())
                        .unwrap_or("<none>");
                    let last_rollback_outcome = detail
                        .last_rollback_outcome
                        .get("outcome")
                        .and_then(|value| value.as_str())
                        .unwrap_or("<none>");
                    let last_rollback_reason = detail
                        .last_rollback_outcome
                        .get("reason")
                        .and_then(|value| value.as_str())
                        .unwrap_or("<none>");
                    format!(
                        "Context run {}\n  status: {}\n  type: {}\n  revision: {}\n  workspace: {}\n  steps: {}\n  why_next_step: {}\n  objective: {}\n\nRollback\n  preview_steps: {}\n  history_entries: {}\n  policy: {}\n  required_ack: {}\n  last_outcome: {}\n  last_reason: {}\n\nNext\n  /context_run_rollback_preview {}\n  /context_run_rollback_history {}",
                        run.run_id,
                        format!("{:?}", run.status).to_lowercase(),
                        run.run_type,
                        run.revision,
                        run.workspace.canonical_path,
                        run.steps.len(),
                        run.why_next_step.unwrap_or_else(|| "<none>".to_string()),
                        run.objective,
                        rollback_preview_steps,
                        rollback_history_entries,
                        if rollback_policy_eligible {
                            "eligible"
                        } else {
                            "blocked"
                        },
                        rollback_required_ack,
                        last_rollback_outcome,
                        last_rollback_reason,
                        run.run_id,
                        run.run_id
                    )
                }
                Err(err) => format!("Failed to load context run: {}", err),
            }
        }),
        "context_run_rollback_preview" => Some({
            if args.len() != 1 {
                return Some("Usage: /context_run_rollback_preview <run_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            match client.context_run_rollback_preview(run_id).await {
                Ok(preview) => {
                    if preview.steps.is_empty() {
                        return Some(format!(
                            "No rollback preview steps for context run {}.",
                            run_id
                        ));
                    }
                    let lines = preview
                        .steps
                        .iter()
                        .take(12)
                        .map(|step| {
                            format!(
                                "  - [{}] seq={} ops={} tool={} event={}",
                                if step.executable { "exec" } else { "info" },
                                step.seq,
                                step.operation_count,
                                step.tool.as_deref().unwrap_or("<unknown>"),
                                step.event_id
                            )
                        })
                        .collect::<Vec<_>>();
                    let executable_ids = preview
                        .steps
                        .iter()
                        .filter(|step| step.executable)
                        .map(|step| step.event_id.clone())
                        .collect::<Vec<_>>();
                    let executable_id_lines = if executable_ids.is_empty() {
                        "  <none>".to_string()
                    } else {
                        executable_ids
                            .iter()
                            .map(|event_id| format!("  {}", event_id))
                            .collect::<Vec<_>>()
                            .join("\n")
                    };
                    let next = if executable_ids.is_empty() {
                        "  No executable rollback steps are available yet.".to_string()
                    } else {
                        format!(
                            "  /context_run_rollback_execute {} --ack {}\n  /context_run_rollback_execute_all {} --ack",
                            run_id,
                            executable_ids.join(" "),
                            run_id
                        )
                    };
                    format!(
                        "Rollback preview ({})\n  step_count: {}\n  executable_steps: {}\n  advisory_steps: {}\n  fully_executable: {}\n\nExecutable ids\n{}\n\nSteps\n{}\n\nNext\n{}",
                        run_id,
                        preview.step_count,
                        preview.executable_step_count,
                        preview.advisory_step_count,
                        preview.executable,
                        executable_id_lines,
                        lines.join("\n"),
                        next
                    )
                }
                Err(err) => format!("Failed to load rollback preview: {}", err),
            }
        }),
        "context_run_rollback_execute" => Some({
            if args.len() < 3 || args[1] != "--ack" {
                return Some(
                    "Usage: /context_run_rollback_execute <run_id> --ack <event_id...>".to_string(),
                );
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let event_ids = args[2..]
                .iter()
                .map(|value| value.trim().to_string())
                .filter(|value| !value.is_empty())
                .collect::<Vec<_>>();
            if event_ids.is_empty() {
                return Some("Provide at least one rollback preview event id.".to_string());
            }
            match client
                .context_run_rollback_execute(
                    run_id,
                    event_ids.clone(),
                    Some("allow_rollback_execution".to_string()),
                )
                .await
            {
                Ok(result) => {
                    let missing = result
                        .missing_event_ids
                        .as_ref()
                        .filter(|rows| !rows.is_empty())
                        .map(|rows| rows.join(", "))
                        .unwrap_or_else(|| "<none>".to_string());
                    format!(
                        "Rollback execute ({})\n  applied: {}\n  selected: {}\n  applied_steps: {}\n  applied_operations: {}\n  missing: {}\n  reason: {}\n\nNext\n  /context_run_rollback_history {}\n  /context_run_rollback_preview {}",
                        run_id,
                        result.applied,
                        if result.selected_event_ids.is_empty() {
                            event_ids.join(", ")
                        } else {
                            result.selected_event_ids.join(", ")
                        },
                        result.applied_step_count.unwrap_or(0),
                        result.applied_operation_count.unwrap_or(0),
                        missing,
                        result.reason.unwrap_or_else(|| "<none>".to_string()),
                        run_id,
                        run_id
                    )
                }
                Err(err) => format!("Failed to execute rollback: {}", err),
            }
        }),
        "context_run_rollback_execute_all" => Some({
            if args.len() != 2 || args[1] != "--ack" {
                return Some("Usage: /context_run_rollback_execute_all <run_id> --ack".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let preview = match client.context_run_rollback_preview(run_id).await {
                Ok(preview) => preview,
                Err(err) => return Some(format!("Failed to load rollback preview: {}", err)),
            };
            let event_ids = preview
                .steps
                .iter()
                .filter(|step| step.executable)
                .map(|step| step.event_id.clone())
                .collect::<Vec<_>>();
            if event_ids.is_empty() {
                return Some(format!(
                    "No executable rollback preview steps for context run {}.",
                    run_id
                ));
            }
            match client
                .context_run_rollback_execute(
                    run_id,
                    event_ids.clone(),
                    Some("allow_rollback_execution".to_string()),
                )
                .await
            {
                Ok(result) => {
                    let missing = result
                        .missing_event_ids
                        .as_ref()
                        .filter(|rows| !rows.is_empty())
                        .map(|rows| rows.join(", "))
                        .unwrap_or_else(|| "<none>".to_string());
                    let selected = if result.selected_event_ids.is_empty() {
                        event_ids.join(", ")
                    } else {
                        result.selected_event_ids.join(", ")
                    };
                    format!(
                        "Rollback execute all ({})\n  applied: {}\n  selected: {}\n  applied_steps: {}\n  applied_operations: {}\n  missing: {}\n  reason: {}\n\nNext\n  /context_run_rollback_history {}\n  /context_run_rollback_preview {}",
                        run_id,
                        result.applied,
                        selected,
                        result.applied_step_count.unwrap_or(0),
                        result.applied_operation_count.unwrap_or(0),
                        missing,
                        result.reason.unwrap_or_else(|| "<none>".to_string()),
                        run_id,
                        run_id
                    )
                }
                Err(err) => format!("Failed to execute rollback: {}", err),
            }
        }),
        "context_run_rollback_history" => Some({
            if args.len() != 1 {
                return Some("Usage: /context_run_rollback_history <run_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            match client.context_run_rollback_history(run_id).await {
                Ok(history) => {
                    if history.entries.is_empty() {
                        return Some(format!("No rollback receipts for context run {}.", run_id));
                    }
                    let entry_count = history.entries.len();
                    let applied_count = history
                        .entries
                        .iter()
                        .filter(|entry| entry.outcome == "applied")
                        .count();
                    let blocked_count = history
                        .entries
                        .iter()
                        .filter(|entry| entry.outcome != "applied")
                        .count();
                    let lines = history
                        .entries
                        .iter()
                        .rev()
                        .take(6)
                        .map(|entry| {
                            let selected = if entry.selected_event_ids.is_empty() {
                                "<none>".to_string()
                            } else {
                                entry.selected_event_ids.join(", ")
                            };
                            let missing = entry
                                .missing_event_ids
                                .as_ref()
                                .filter(|rows| !rows.is_empty())
                                .map(|rows| rows.join(", "))
                                .unwrap_or_else(|| "<none>".to_string());
                            let actions = entry
                                .applied_by_action
                                .as_ref()
                                .filter(|counts| !counts.is_empty())
                                .map(|counts| {
                                    let mut rows = counts
                                        .iter()
                                        .map(|(action, count)| format!("{}={}", action, count))
                                        .collect::<Vec<_>>();
                                    rows.sort();
                                    rows.join(", ")
                                })
                                .unwrap_or_else(|| "<none>".to_string());
                            format!(
                                "  - seq={} outcome={} ts={}\n    selected: {}\n    missing: {}\n    steps: {}\n    operations: {}\n    actions: {}\n    reason: {}",
                                entry.seq,
                                entry.outcome,
                                entry.ts_ms,
                                selected,
                                missing,
                                entry.applied_step_count.unwrap_or(0),
                                entry.applied_operation_count.unwrap_or(0),
                                actions,
                                entry.reason.as_deref().unwrap_or("<none>")
                            )
                        })
                        .collect::<Vec<_>>();
                    format!(
                        "Rollback receipts ({})\n  entries: {}\n  applied: {}\n  blocked: {}\n\nRecent receipts\n{}",
                        run_id,
                        entry_count,
                        applied_count,
                        blocked_count,
                        lines.join("\n")
                    )
                }
                Err(err) => format!("Failed to load rollback receipts: {}", err),
            }
        }),
        "context_run_events" => Some({
            if args.is_empty() {
                return Some("Usage: /context_run_events <run_id> [tail]".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let tail = if args.len() > 1 {
                match args[1].parse::<usize>() {
                    Ok(value) if value > 0 => Some(value),
                    _ => return Some("tail must be a positive integer.".to_string()),
                }
            } else {
                Some(20)
            };
            match client.context_run_events(run_id, None, tail).await {
                Ok(events) => {
                    if events.is_empty() {
                        return Some(format!("No events for context run {}.", run_id));
                    }
                    let lines = events
                        .iter()
                        .map(|event| {
                            format!(
                                "- #{} {} status={} step={} ts={}",
                                event.seq,
                                event.event_type,
                                format!("{:?}", event.status).to_lowercase(),
                                event.step_id.as_deref().unwrap_or("-"),
                                event.ts_ms
                            )
                        })
                        .collect::<Vec<_>>();
                    format!("Context run events ({}):\n{}", run_id, lines.join("\n"))
                }
                Err(err) => format!("Failed to load context run events: {}", err),
            }
        }),
        "context_run_pause" | "context_run_resume" | "context_run_cancel" => Some({
            if args.len() != 1 {
                return Some(format!("Usage: /{} <run_id>", cmd_name));
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let (event_type, status, label) = match cmd_name {
                "context_run_pause" => (
                    "run_paused",
                    crate::net::client::ContextRunStatus::Paused,
                    "paused",
                ),
                "context_run_resume" => (
                    "run_resumed",
                    crate::net::client::ContextRunStatus::Running,
                    "running",
                ),
                _ => (
                    "run_cancelled",
                    crate::net::client::ContextRunStatus::Cancelled,
                    "cancelled",
                ),
            };
            match client
                .context_run_append_event(
                    run_id,
                    event_type,
                    status,
                    None,
                    json!({ "source": "tui" }),
                )
                .await
            {
                Ok(event) => format!(
                    "Context run {} {} (seq={} event={}).",
                    run_id, label, event.seq, event.event_id
                ),
                Err(err) => format!("Failed to update context run status: {}", err),
            }
        }),
        "context_run_blackboard" => Some({
            if args.len() != 1 {
                return Some("Usage: /context_run_blackboard <run_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            match client.context_run_blackboard(run_id).await {
                Ok(blackboard) => format!(
                    "Context blackboard {}\n  revision: {}\n  facts: {}\n  decisions: {}\n  open_questions: {}\n  artifacts: {}\n  rolling_summary: {}\n  latest_context_pack: {}",
                    run_id,
                    blackboard.revision,
                    blackboard.facts.len(),
                    blackboard.decisions.len(),
                    blackboard.open_questions.len(),
                    blackboard.artifacts.len(),
                    if blackboard.summaries.rolling.is_empty() { "<empty>" } else { "<present>" },
                    if blackboard.summaries.latest_context_pack.is_empty() { "<empty>" } else { "<present>" }
                ),
                Err(err) => format!("Failed to load context run blackboard: {}", err),
            }
        }),
        "context_run_next" => Some({
            if args.is_empty() {
                return Some("Usage: /context_run_next <run_id> [dry_run]".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let dry_run = args
                .get(1)
                .map(|value| {
                    matches!(
                        value.to_ascii_lowercase().as_str(),
                        "1" | "true" | "yes" | "dry"
                    )
                })
                .unwrap_or(false);
            match client.context_run_driver_next(run_id, dry_run).await {
                Ok(next) => format!(
                    "ContextDriver next ({})\n  run: {}\n  dry_run: {}\n  target_status: {}\n  selected_step: {}\n  why_next_step: {}",
                    if dry_run { "preview" } else { "applied" },
                    next.run_id,
                    next.dry_run,
                    format!("{:?}", next.target_status).to_lowercase(),
                    next.selected_step_id.unwrap_or_else(|| "<none>".to_string()),
                    next.why_next_step
                ),
                Err(err) => format!("Failed to run ContextDriver next-step selection: {}", err),
            }
        }),
        "context_run_replay" => Some({
            if args.is_empty() {
                return Some("Usage: /context_run_replay <run_id> [upto_seq]".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let upto_seq = if args.len() > 1 {
                match args[1].parse::<u64>() {
                    Ok(value) if value > 0 => Some(value),
                    _ => return Some("upto_seq must be a positive integer.".to_string()),
                }
            } else {
                None
            };
            match client.context_run_replay(run_id, upto_seq, Some(true)).await {
                Ok(replay) => format!(
                    "Context replay {}\n  from_checkpoint: {} (seq={})\n  events_applied: {}\n  replay_status: {}\n  persisted_status: {}\n  drift: {} (status={}, why={}, steps={})",
                    replay.run_id,
                    replay.from_checkpoint,
                    replay
                        .checkpoint_seq
                        .map(|value| value.to_string())
                        .unwrap_or_else(|| "-".to_string()),
                    replay.events_applied,
                    format!("{:?}", replay.replay.status).to_lowercase(),
                    format!("{:?}", replay.persisted.status).to_lowercase(),
                    replay.drift.mismatch,
                    replay.drift.status_mismatch,
                    replay.drift.why_next_step_mismatch,
                    replay.drift.step_count_mismatch
                ),
                Err(err) => format!("Failed to replay context run: {}", err),
            }
        }),
        "context_run_lineage" => Some({
            if args.is_empty() {
                return Some("Usage: /context_run_lineage <run_id> [tail]".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let tail = if args.len() > 1 {
                match args[1].parse::<usize>() {
                    Ok(value) if value > 0 => Some(value),
                    _ => return Some("tail must be a positive integer.".to_string()),
                }
            } else {
                Some(100)
            };
            match client.context_run_events(run_id, None, tail).await {
                Ok(events) => {
                    let decisions = events
                        .iter()
                        .filter(|event| event.event_type == "meta_next_step_selected")
                        .collect::<Vec<_>>();
                    if decisions.is_empty() {
                        return Some(format!(
                            "No decision lineage events for context run {}.",
                            run_id
                        ));
                    }
                    let lines = decisions
                        .iter()
                        .map(|event| {
                            let why = event
                                .payload
                                .get("why_next_step")
                                .and_then(Value::as_str)
                                .unwrap_or("<missing>");
                            let selected = event
                                .payload
                                .get("selected_step_id")
                                .and_then(Value::as_str)
                                .or_else(|| event.step_id.as_deref())
                                .unwrap_or("-");
                            format!(
                                "- #{} ts={} status={} step={} why={}",
                                event.seq,
                                event.ts_ms,
                                format!("{:?}", event.status).to_lowercase(),
                                selected,
                                why
                            )
                        })
                        .collect::<Vec<_>>();
                    format!(
                        "Context decision lineage ({}):\n{}",
                        run_id,
                        lines.join("\n")
                    )
                }
                Err(err) => format!("Failed to load context run lineage: {}", err),
            }
        }),
        "context_run_sync_tasks" => Some({
            if args.len() != 1 {
                return Some("Usage: /context_run_sync_tasks <run_id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let run_id = args[0];
            let (source_session_id, source_run_id, todos) = match &app.state {
                AppState::Chat {
                    session_id,
                    agents,
                    active_agent_index,
                    tasks,
                    ..
                } => {
                    let mapped = plan_helpers::context_todo_items_from_tasks(tasks);
                    let run_ref = agents
                        .get(*active_agent_index)
                        .and_then(|agent| agent.active_run_id.clone());
                    (Some(session_id.clone()), run_ref, mapped)
                }
                _ => (None, None, Vec::new()),
            };
            if todos.is_empty() {
                return Some("No tasks available to sync.".to_string());
            }
            match client
                .context_run_sync_todos(run_id, todos, true, source_session_id, source_run_id)
                .await
            {
                Ok(run) => format!(
                    "Synced tasks into context run {}.\n  steps: {}\n  status: {}\n  why_next_step: {}",
                    run.run_id,
                    run.steps.len(),
                    format!("{:?}", run.status).to_lowercase(),
                    run.why_next_step.unwrap_or_else(|| "<none>".to_string())
                ),
                Err(err) => format!("Failed to sync tasks into context run: {}", err),
            }
        }),
        "context_run_bind" => Some({
            if args.len() != 1 {
                return Some("Usage: /context_run_bind <run_id|off>".to_string());
            }
            let target = args[0];
            if let AppState::Chat {
                agents,
                active_agent_index,
                ..
            } = &mut app.state
            {
                let Some(agent) = agents.get_mut(*active_agent_index) else {
                    return Some("No active agent.".to_string());
                };
                if target.eq_ignore_ascii_case("off") || target == "-" {
                    agent.bound_context_run_id = None;
                    return Some(format!(
                        "Cleared context-run binding for {}.",
                        agent.agent_id
                    ));
                }
                agent.bound_context_run_id = Some(target.to_string());
                format!(
                    "Bound {} todowrite updates to context run {}.",
                    agent.agent_id, target
                )
            } else {
                "Context-run binding is available in chat mode only.".to_string()
            }
        }),
        "routines" => Some({
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            match client.routines_list().await {
                Ok(routines) => {
                    if routines.is_empty() {
                        return Some("No routines configured.".to_string());
                    }
                    let lines = routines
                        .into_iter()
                        .map(|routine| {
                            let schedule = match routine.schedule {
                                crate::net::client::RoutineSchedule::IntervalSeconds {
                                    seconds,
                                } => format!("interval:{}s", seconds),
                                crate::net::client::RoutineSchedule::Cron { expression } => {
                                    format!("cron:{expression}")
                                }
                            };
                            format!(
                                "- {} [{}] {} ({})",
                                routine.routine_id, routine.name, schedule, routine.entrypoint
                            )
                        })
                        .collect::<Vec<_>>();
                    format!("Routines:\n{}", lines.join("\n"))
                }
                Err(err) => format!("Failed to list routines: {}", err),
            }
        }),
        "routine_create" => Some({
            if args.len() < 3 {
                return Some(
                    "Usage: /routine_create <id> <interval_seconds> <entrypoint>".to_string(),
                );
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0].to_string();
            let interval_seconds = match args[1].parse::<u64>() {
                Ok(seconds) if seconds > 0 => seconds,
                _ => return Some("interval_seconds must be a positive integer.".to_string()),
            };
            let entrypoint = args[2..].join(" ");
            let request = crate::net::client::RoutineCreateRequest {
                routine_id: Some(routine_id.clone()),
                name: routine_id.clone(),
                schedule: crate::net::client::RoutineSchedule::IntervalSeconds {
                    seconds: interval_seconds,
                },
                timezone: None,
                misfire_policy: Some(crate::net::client::RoutineMisfirePolicy::RunOnce),
                entrypoint: entrypoint.clone(),
                args: Some(serde_json::json!({})),
                allowed_tools: None,
                output_targets: None,
                creator_type: Some("user".to_string()),
                creator_id: Some("tui".to_string()),
                requires_approval: Some(true),
                external_integrations_allowed: Some(false),
                next_fire_at_ms: None,
            };
            match client.routines_create(request).await {
                Ok(routine) => format!(
                    "Created routine {} ({}s -> {}).",
                    routine.routine_id, interval_seconds, routine.entrypoint
                ),
                Err(err) => format!("Failed to create routine: {}", err),
            }
        }),
        "routine_edit" => Some({
            if args.len() != 2 {
                return Some("Usage: /routine_edit <id> <interval_seconds>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0];
            let interval_seconds = match args[1].parse::<u64>() {
                Ok(seconds) if seconds > 0 => seconds,
                _ => return Some("interval_seconds must be a positive integer.".to_string()),
            };
            let request = crate::net::client::RoutinePatchRequest {
                schedule: Some(crate::net::client::RoutineSchedule::IntervalSeconds {
                    seconds: interval_seconds,
                }),
                ..Default::default()
            };
            match client.routines_patch(routine_id, request).await {
                Ok(_) => format!(
                    "Updated routine {} schedule to every {}s.",
                    routine_id, interval_seconds
                ),
                Err(err) => format!("Failed to edit routine: {}", err),
            }
        }),
        "routine_pause" => Some({
            if args.len() != 1 {
                return Some("Usage: /routine_pause <id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0];
            let request = crate::net::client::RoutinePatchRequest {
                status: Some(crate::net::client::RoutineStatus::Paused),
                ..Default::default()
            };
            match client.routines_patch(routine_id, request).await {
                Ok(_) => format!("Paused routine {}.", routine_id),
                Err(err) => format!("Failed to pause routine: {}", err),
            }
        }),
        "routine_resume" => Some({
            if args.len() != 1 {
                return Some("Usage: /routine_resume <id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0];
            let request = crate::net::client::RoutinePatchRequest {
                status: Some(crate::net::client::RoutineStatus::Active),
                ..Default::default()
            };
            match client.routines_patch(routine_id, request).await {
                Ok(_) => format!("Resumed routine {}.", routine_id),
                Err(err) => format!("Failed to resume routine: {}", err),
            }
        }),
        "routine_run_now" => Some({
            if args.is_empty() {
                return Some("Usage: /routine_run_now <id> [run_count]".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0];
            let run_count = if args.len() > 1 {
                match args[1].parse::<u32>() {
                    Ok(count) if count > 0 => Some(count),
                    _ => return Some("run_count must be a positive integer.".to_string()),
                }
            } else {
                None
            };
            let request = crate::net::client::RoutineRunNowRequest {
                run_count,
                reason: Some("manual_tui".to_string()),
            };
            match client.routines_run_now(routine_id, request).await {
                Ok(resp) => format!(
                    "Triggered routine {} (run_count={}).",
                    resp.routine_id, resp.run_count
                ),
                Err(err) => format!("Failed to trigger routine: {}", err),
            }
        }),
        "routine_delete" => Some({
            if args.len() != 1 {
                return Some("Usage: /routine_delete <id>".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0];
            match client.routines_delete(routine_id).await {
                Ok(true) => format!("Deleted routine {}.", routine_id),
                Ok(false) => format!("Routine not found: {}", routine_id),
                Err(err) => format!("Failed to delete routine: {}", err),
            }
        }),
        "routine_history" => Some({
            if args.is_empty() {
                return Some("Usage: /routine_history <id> [limit]".to_string());
            }
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let routine_id = args[0];
            let limit = if args.len() > 1 {
                match args[1].parse::<usize>() {
                    Ok(value) => Some(value),
                    Err(_) => return Some("limit must be a positive integer.".to_string()),
                }
            } else {
                Some(10)
            };
            match client.routines_history(routine_id, limit).await {
                Ok(events) => {
                    if events.is_empty() {
                        return Some(format!("No history for routine {}.", routine_id));
                    }
                    let lines = events
                        .iter()
                        .map(|event| {
                            format!(
                                "- {} run_count={} status={} at={}",
                                event.trigger_type,
                                event.run_count,
                                event.status,
                                event.fired_at_ms
                            )
                        })
                        .collect::<Vec<_>>();
                    format!("Routine history ({}):\n{}", routine_id, lines.join("\n"))
                }
                Err(err) => format!("Failed to load routine history: {}", err),
            }
        }),
        "config" => Some({
            let lines = vec![
                format!(
                    "Engine URL: {}",
                    app.client
                        .as_ref()
                        .map(|c| c.base_url())
                        .unwrap_or(&"not connected")
                ),
                format!("Sessions: {}", app.sessions.len()),
                format!("Current Mode: {:?}", app.current_mode),
                format!(
                    "Current Provider: {}",
                    app.current_provider.as_deref().unwrap_or("none")
                ),
                format!(
                    "Current Model: {}",
                    app.current_model.as_deref().unwrap_or("none")
                ),
            ];
            format!("Configuration:\n{}", lines.join("\n"))
        }),
        "requests" => Some({
            if let AppState::Chat {
                pending_requests,
                modal,
                request_cursor,
                ..
            } = &mut app.state
            {
                if pending_requests.is_empty() {
                    "No pending requests.".to_string()
                } else {
                    if *request_cursor >= pending_requests.len() {
                        *request_cursor = pending_requests.len().saturating_sub(1);
                    }
                    *modal = Some(ModalState::RequestCenter);
                    format!(
                        "Opened request center ({} pending).",
                        pending_requests.len()
                    )
                }
            } else {
                "Requests are only available in chat mode.".to_string()
            }
        }),
        "copy" => Some({
            if let AppState::Chat { messages, .. } = &app.state {
                match app.copy_latest_assistant_to_clipboard(messages) {
                    Ok(len) => format!("Copied {} characters to clipboard.", len),
                    Err(err) => format!("Clipboard copy failed: {}", err),
                }
            } else {
                "Clipboard copy works in chat screens only.".to_string()
            }
        }),
        "approve" | "deny" | "answer" => Some({
            let Some(client) = &app.client else {
                return Some("Engine client not connected.".to_string());
            };
            let session_id = if let AppState::Chat { session_id, .. } = &app.state {
                Some(session_id.clone())
            } else {
                None
            };

            match cmd_name {
                "approve" => {
                    if args
                        .first()
                        .map(|s| s.eq_ignore_ascii_case("all"))
                        .unwrap_or(false)
                        || args.is_empty()
                    {
                        let Ok(snapshot) = client.list_permissions().await else {
                            return Some("Failed to load pending permissions.".to_string());
                        };
                        let pending: Vec<String> = snapshot
                            .requests
                            .iter()
                            .filter(|r| r.status.as_deref() == Some("pending"))
                            .filter(|r| {
                                if let Some(sid) = &session_id {
                                    r.session_id.as_deref() == Some(sid.as_str())
                                } else {
                                    true
                                }
                            })
                            .map(|r| r.id.clone())
                            .collect();
                        if pending.is_empty() {
                            return Some("No pending permissions.".to_string());
                        }
                        let mut approved = 0usize;
                        for id in pending {
                            if client.reply_permission(&id, "allow").await.unwrap_or(false) {
                                approved += 1;
                            }
                        }
                        format!("Approved {} pending permission request(s).", approved)
                    } else {
                        let id = args[0];
                        let reply = if args
                            .get(1)
                            .map(|s| s.eq_ignore_ascii_case("always"))
                            .unwrap_or(false)
                        {
                            "always"
                        } else {
                            "allow"
                        };
                        if client.reply_permission(id, reply).await.unwrap_or(false) {
                            format!("Approved permission request {}.", id)
                        } else {
                            format!("Permission request not found: {}", id)
                        }
                    }
                }
                "deny" => {
                    if args.is_empty() {
                        return Some("Usage: /deny <id>".to_string());
                    }
                    let id = args[0];
                    if client.reply_permission(id, "deny").await.unwrap_or(false) {
                        format!("Denied permission request {}.", id)
                    } else {
                        format!("Permission request not found: {}", id)
                    }
                }
                "answer" => {
                    if args.is_empty() {
                        return Some("Usage: /answer <id> <text>".to_string());
                    }
                    let id = args[0];
                    let reply = if args.len() > 1 {
                        args[1..].join(" ")
                    } else {
                        "allow".to_string()
                    };
                    if client
                        .reply_permission(id, reply.as_str())
                        .await
                        .unwrap_or(false)
                    {
                        format!("Replied to permission request {}.", id)
                    } else {
                        format!("Permission request not found: {}", id)
                    }
                }
                _ => "Unsupported permission command.".to_string(),
            }
        }),
        "mode" => Some(if args.is_empty() {
            let agent = app.current_mode.as_agent();
            format!("Current mode: {:?} (agent: {})", app.current_mode, agent)
        } else {
            let mode_name = args[0];
            if let Some(mode) = TandemMode::from_str(mode_name) {
                app.current_mode = mode;
                format!("Mode set to: {:?}", mode)
            } else {
                format!(
                    "Unknown mode: {}. Use /modes to see available modes.",
                    mode_name
                )
            }
        }),
        "modes" => Some({
            let lines: Vec<String> = TandemMode::all_modes()
                .iter()
                .map(|(name, desc)| format!("  {} - {}", name, desc))
                .collect();
            format!("Available modes:\n{}", lines.join("\n"))
        }),
        "providers" => Some(if let Some(catalog) = &app.provider_catalog {
            let lines: Vec<String> = catalog
                .all
                .iter()
                .map(|p| {
                    let status = if catalog.connected.contains(&p.id) {
                        "connected"
                    } else {
                        "not configured"
                    };
                    format!("  {} - {}", p.id, status)
                })
                .collect();
            if lines.is_empty() {
                "No providers available.".to_string()
            } else {
                format!("Available providers:\n{}", lines.join("\n"))
            }
        } else {
            "Loading providers... (use /providers to refresh)".to_string()
        }),
        "provider" => Some({
            let mut step = SetupStep::SelectProvider;
            let mut selected_provider_index = 0;
            let filter_model = String::new();

            if !args.is_empty() {
                let provider_id = args[0];
                if let Some(catalog) = &app.provider_catalog {
                    if let Some(idx) = catalog.all.iter().position(|p| p.id == provider_id) {
                        selected_provider_index = idx;
                        step = if catalog.connected.contains(&provider_id.to_string()) {
                            SetupStep::SelectModel
                        } else {
                            SetupStep::EnterApiKey
                        };
                    }
                }
            } else if let Some(current) = &app.current_provider {
                if let Some(catalog) = &app.provider_catalog {
                    if let Some(idx) = catalog.all.iter().position(|p| &p.id == current) {
                        selected_provider_index = idx;
                        step = if catalog.connected.contains(current) {
                            SetupStep::SelectModel
                        } else {
                            SetupStep::EnterApiKey
                        };
                    }
                }
            }

            app.state = AppState::SetupWizard {
                step,
                provider_catalog: app.provider_catalog.clone(),
                selected_provider_index,
                selected_model_index: 0,
                api_key_input: String::new(),
                model_input: filter_model,
            };
            "Opening provider selection...".to_string()
        }),
        "models" => Some({
            let provider_id = args
                .first()
                .map(|s| s.to_string())
                .or_else(|| app.current_provider.clone());
            if let Some(catalog) = &app.provider_catalog {
                if let Some(pid) = &provider_id {
                    if let Some(provider) = catalog.all.iter().find(|p| p.id == *pid) {
                        let model_ids: Vec<String> = provider.models.keys().cloned().collect();
                        if model_ids.is_empty() {
                            format!("No models available for provider: {}", pid)
                        } else {
                            format!(
                                "Models for {}:\n{}",
                                pid,
                                model_ids
                                    .iter()
                                    .map(|m| format!("  {}", m))
                                    .collect::<Vec<_>>()
                                    .join("\n")
                            )
                        }
                    } else {
                        format!("Provider not found: {}", pid)
                    }
                } else {
                    "No provider selected. Use /provider <id> first.".to_string()
                }
            } else {
                "Loading providers... (use /providers to refresh)".to_string()
            }
        }),
        "model" => Some(if args.is_empty() {
            let mut selected_provider_index = 0;
            if let Some(current) = &app.current_provider {
                if let Some(catalog) = &app.provider_catalog {
                    if let Some(idx) = catalog.all.iter().position(|p| &p.id == current) {
                        selected_provider_index = idx;
                    }
                }
            }
            app.state = AppState::SetupWizard {
                step: SetupStep::SelectModel,
                provider_catalog: app.provider_catalog.clone(),
                selected_provider_index,
                selected_model_index: 0,
                api_key_input: String::new(),
                model_input: String::new(),
            };
            "Opening model selection...".to_string()
        } else {
            let model_id = args.join(" ");
            app.current_model = Some(model_id.clone());
            app.pending_model_provider = None;
            if let Some(provider_id) = app.current_provider.clone() {
                app.persist_provider_defaults(&provider_id, Some(&model_id), None)
                    .await;
            }
            format!("Model set to: {}", model_id)
        }),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::{
        ChatMessage, ComposerInputState, ModalState, PendingPermissionRequest, PendingRequest,
        PendingRequestKind, PlanFeedbackWizardState, Task, UiMode,
    };
    use crate::crypto::keystore::SecureKeyStore;
    use crate::net::client::EngineClient;
    use crate::net::client::{ProviderCatalog, Session, SessionTime};
    use std::collections::HashMap;
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use std::thread::JoinHandle;
    use std::time::Duration;
    use tandem_wire::{WireProviderEntry, WireProviderModel};

    #[tokio::test]
    async fn rollback_commands_render_engine_responses() {
        let server = MockServer::start(HashMap::from([
            (
                "/context/runs/run-1/checkpoints/mutations/rollback-preview".to_string(),
                json_response(
                    r#"{"steps":[{"seq":3,"event_id":"evt-1","tool":"edit_file","executable":true,"operation_count":2},{"seq":4,"event_id":"evt-2","tool":"read_file","executable":false,"operation_count":1}],"step_count":2,"executable_step_count":1,"advisory_step_count":1,"executable":false}"#,
                ),
            ),
            (
                "/context/runs/run-1/checkpoints/mutations/rollback-history".to_string(),
                json_response(
                    r#"{"entries":[{"seq":7,"ts_ms":200,"event_id":"evt-rollback-2","outcome":"blocked","selected_event_ids":["evt-1"],"applied_step_count":0,"applied_operation_count":0,"reason":"approval required"},{"seq":6,"ts_ms":100,"event_id":"evt-rollback-1","outcome":"applied","selected_event_ids":["evt-1"],"applied_step_count":1,"applied_operation_count":2,"applied_by_action":{"rewrite_file":2}}],"summary":{"entry_count":2,"by_outcome":{"applied":1,"blocked":1}}}"#,
                ),
            ),
            (
                "/context/runs/run-1/checkpoints/mutations/rollback-execute".to_string(),
                json_response(
                    r#"{"applied":true,"selected_event_ids":["evt-1"],"applied_step_count":1,"applied_operation_count":2,"missing_event_ids":[],"reason":null}"#,
                ),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let preview = app
            .execute_command("/context_run_rollback_preview run-1")
            .await;
        assert!(preview.contains("Rollback preview (run-1)"));
        assert!(preview.contains("evt-1"));

        let history = app
            .execute_command("/context_run_rollback_history run-1")
            .await;
        assert!(history.contains("Rollback receipts (run-1)"));
        assert!(history.contains("outcome=applied"));
        assert!(history.contains("outcome=blocked"));

        let execute = app
            .execute_command("/context_run_rollback_execute run-1 --ack evt-1")
            .await;
        assert!(execute.contains("Rollback execute (run-1)"));
        assert!(execute.contains("selected: evt-1"));
    }

    #[tokio::test]
    async fn recent_command_helper_lists_replays_and_clears() {
        let mut app = App::new();

        let mode = app.execute_command("/mode coder").await;
        assert!(mode.contains("Mode set to: Coder"));

        let workspace = app.execute_command("/workspace show").await;
        assert!(workspace.contains("Current workspace directory:"));

        let recent = app.execute_command("/recent").await;
        assert!(recent.contains("1. /workspace show"));
        assert!(recent.contains("2. /mode coder"));

        let replay = app.execute_command("/recent run 2").await;
        assert!(replay.contains("Replayed recent command #2: /mode coder"));
        assert!(replay.contains("Mode set to: Coder"));

        let cleared = app.execute_command("/recent clear").await;
        assert_eq!(cleared, "Cleared 2 recent command(s).");
        assert_eq!(
            app.execute_command("/recent").await,
            "No recent slash commands yet."
        );
    }

    #[tokio::test]
    async fn session_commands_list_and_switch_sessions() {
        let mut app = App::new();
        app.sessions = vec![
            Session {
                id: "s-1".to_string(),
                title: "First".to_string(),
                directory: None,
                workspace_root: None,
                time: Some(SessionTime {
                    created: Some(1),
                    updated: Some(2),
                }),
            },
            Session {
                id: "s-2".to_string(),
                title: "Second".to_string(),
                directory: None,
                workspace_root: None,
                time: Some(SessionTime {
                    created: Some(3),
                    updated: Some(4),
                }),
            },
        ];
        app.selected_session_index = 1;
        app.state = chat_state("s-1");

        let sessions = app.execute_command("/sessions").await;
        assert!(sessions.contains("→ Second (ID: s-2)"));
        assert!(sessions.contains("  First (ID: s-1)"));

        let switched = app.execute_command("/use s-2").await;
        assert_eq!(switched, "Switched to session: s-2");
        assert_eq!(app.selected_session_index, 1);
        match &app.state {
            AppState::Chat {
                session_id,
                active_agent_index,
                agents,
                ..
            } => {
                assert_eq!(session_id, "s-2");
                assert_eq!(agents[*active_agent_index].session_id, "s-2");
            }
            _ => panic!("expected chat state"),
        }
    }

    #[tokio::test]
    async fn key_commands_list_keys_and_open_wizard() {
        let mut app = App::new();
        let path =
            std::env::temp_dir().join(format!("tandem-tui-keystore-{}.json", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let mut keystore = SecureKeyStore::load(&path, vec![7; 32]).expect("keystore");
        keystore
            .set("openai_api_key", "secret".to_string())
            .expect("set key");
        app.keystore = Some(keystore);
        app.current_provider = Some("openai".to_string());
        app.provider_catalog = Some(ProviderCatalog {
            all: vec![WireProviderEntry {
                id: "openai".to_string(),
                name: Some("OpenAI".to_string()),
                models: HashMap::<String, WireProviderModel>::new(),
                catalog_source: None,
                catalog_status: None,
                catalog_message: None,
            }],
            connected: vec!["openai".to_string()],
            default: Some("openai".to_string()),
        });

        let keys = app.execute_command("/keys").await;
        assert!(keys.contains("Configured providers:"));
        assert!(keys.contains("openai - configured"));

        let wizard = app.execute_command("/key set").await;
        assert_eq!(wizard, "Opening key setup wizard for openai...");
        match &app.state {
            AppState::SetupWizard { step, .. } => assert_eq!(*step, SetupStep::EnterApiKey),
            _ => panic!("expected setup wizard"),
        }

        let _ = std::fs::remove_file(PathBuf::from(path));
    }

    #[tokio::test]
    async fn queue_commands_manage_followups_and_errors() {
        let mut app = App::new();
        app.state = chat_state("s-1");
        if let AppState::Chat {
            agents, messages, ..
        } = &mut app.state
        {
            agents[0]
                .follow_up_queue
                .push_back("first follow-up".to_string());
            agents[0].steering_message = Some("steer".to_string());
            messages.push(ChatMessage {
                role: MessageRole::System,
                content: vec![ContentBlock::Text("Something failed badly".to_string())],
            });
        }

        let queue = app.execute_command("/queue").await;
        assert!(queue.contains("steering: yes"));
        assert!(queue.contains("follow-ups: 1"));
        assert!(queue.contains("first follow-up"));

        let error = app.execute_command("/last_error").await;
        assert_eq!(error, "Something failed badly");

        let cleared = app.execute_command("/queue clear").await;
        assert_eq!(cleared, "Cleared queued steering and follow-up messages.");

        let messages = app.execute_command("/messages 25").await;
        assert_eq!(messages, "Message history not implemented yet. (limit: 25)");
    }

    #[tokio::test]
    async fn steer_followup_and_cancel_commands_update_active_agent_state() {
        let mut app = App::new();
        app.state = chat_state("s-1");
        if let AppState::Chat { agents, .. } = &mut app.state {
            agents[0].status = AgentStatus::Running;
            agents[0].active_run_id = Some("run-1".to_string());
        }

        let steer = app.execute_command("/steer check logs").await;
        assert_eq!(steer, "Steering message queued.");
        match &app.state {
            AppState::Chat { command_input, .. } => assert_eq!(command_input.text(), "check logs"),
            _ => panic!("expected chat state"),
        }

        let followup = app.execute_command("/followup inspect rollback").await;
        assert_eq!(followup, "Queued follow-up message (#1).");
        match &app.state {
            AppState::Chat { agents, .. } => {
                assert_eq!(
                    agents[0].follow_up_queue.front().map(String::as_str),
                    Some("inspect rollback")
                );
            }
            _ => panic!("expected chat state"),
        }

        let cancel = app.execute_command("/cancel").await;
        assert_eq!(cancel, "Cancel requested for active agent.");
        match &app.state {
            AppState::Chat { agents, .. } => {
                assert_eq!(agents[0].status, AgentStatus::Idle);
                assert_eq!(agents[0].active_run_id, None);
            }
            _ => panic!("expected chat state"),
        }
    }

    #[tokio::test]
    async fn task_and_prompt_commands_update_chat_state() {
        let mut app = App::new();
        app.state = chat_state("s-1");

        let added = app.execute_command("/task add investigate rollback").await;
        assert_eq!(added, "Task added: investigate rollback (ID: task-1)");

        let pinned = app.execute_command("/task pin task-1").await;
        assert_eq!(pinned, "Task task-1 pinned: true");

        let worked = app.execute_command("/task work task-1").await;
        assert_eq!(worked, "Task task-1 marked as work");

        let listed = app.execute_command("/task list").await;
        assert!(listed.contains("[task-1] investigate rollback (Working) - Pinned: true"));

        let prompt = app.execute_command("/prompt review status").await;
        assert_eq!(prompt, "Prompt sent.");
        match &app.state {
            AppState::Chat {
                messages, agents, ..
            } => {
                assert!(messages
                    .iter()
                    .any(|m| m.content.iter().any(|block| match block {
                        ContentBlock::Text(text) => text == "review status",
                        _ => false,
                    })));
                assert!(agents[0].messages.iter().any(|m| m.content.iter().any(
                    |block| match block {
                        ContentBlock::Text(text) => text == "review status",
                        _ => false,
                    }
                )));
            }
            _ => panic!("expected chat state"),
        }
    }

    #[tokio::test]
    async fn title_command_renames_current_session() {
        let server = MockServer::start(HashMap::from([(
            "/session/s-1".to_string(),
            json_response(
                r#"{"id":"s-1","title":"Renamed Session","directory":null,"workspaceRoot":null,"time":{"created":1,"updated":2}}"#,
            ),
        )]))
        .expect("mock server");
        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));
        app.sessions = vec![Session {
            id: "s-1".to_string(),
            title: "Original Session".to_string(),
            directory: None,
            workspace_root: None,
            time: Some(SessionTime {
                created: Some(1),
                updated: Some(2),
            }),
        }];
        app.state = chat_state("s-1");

        let renamed = app.execute_command("/title Renamed Session").await;
        assert_eq!(renamed, "Session renamed to: Renamed Session");
        assert_eq!(app.sessions[0].title, "Renamed Session");
    }

    #[tokio::test]
    async fn mission_commands_render_list_detail_and_create_views() {
        let mission =
            mission_state_json("m-1", "running", "Stabilize rollback", "Ship safer undo", 3);
        let created = mission_state_json("m-2", "draft", "Fresh mission", "Start clean", 1);
        let server = MockServer::start(HashMap::from([
            (
                "/mission".to_string(),
                json_response(
                    &serde_json::json!({
                        "missions": [serde_json::from_str::<serde_json::Value>(&mission).expect("mission")]
                    })
                    .to_string(),
                ),
            ),
            (
                "/mission/m-1".to_string(),
                json_response(
                    &serde_json::json!({
                        "mission": serde_json::from_str::<serde_json::Value>(&mission).expect("mission detail")
                    })
                    .to_string(),
                ),
            ),
        ]))
        .expect("mock server");
        let create_server = MockServer::start(HashMap::from([(
            "/mission".to_string(),
            json_response(
                &serde_json::json!({
                    "mission": serde_json::from_str::<serde_json::Value>(&created).expect("created mission")
                })
                .to_string(),
            ),
        )]))
        .expect("create mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let list = app.execute_command("/missions").await;
        assert!(list.contains("Missions:"));
        assert!(list.contains("m-1 [running] Stabilize rollback (work_items=1)"));

        let detail = app.execute_command("/mission_get m-1").await;
        assert!(detail.contains("Mission m-1 [running]"));
        assert!(detail.contains("Title: Stabilize rollback"));
        assert!(detail.contains("Goal: Ship safer undo"));
        assert!(detail.contains("- Verify rollback [review]"));

        app.client = Some(EngineClient::new(create_server.base_url()));
        let created = app
            .execute_command("/mission_create Fresh mission :: Start clean :: Draft task")
            .await;
        assert_eq!(created, "Created mission m-2: Fresh mission");
    }

    #[tokio::test]
    async fn mission_event_commands_apply_expected_engine_events() {
        let mission =
            mission_state_json("m-1", "running", "Stabilize rollback", "Ship safer undo", 5);
        let server = MockServer::start(HashMap::from([(
            "/mission/m-1/event".to_string(),
            json_response(
                &serde_json::json!({
                    "mission": serde_json::from_str::<serde_json::Value>(&mission).expect("mission event result"),
                    "commands": [{ "type": "notify" }]
                })
                .to_string(),
            ),
        )]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let invalid = app.execute_command("/mission_event m-1 nope").await;
        assert!(invalid.starts_with("Invalid event JSON:"));

        let applied = app
            .execute_command(r#"/mission_event m-1 {"type":"custom","state":"ok"}"#)
            .await;
        assert_eq!(
            applied,
            "Applied event to mission m-1 (revision=5, commands=1)"
        );

        let started = app.execute_command("/mission_start m-1").await;
        assert_eq!(started, "Mission started m-1 (revision=5)");

        let review_ok = app
            .execute_command("/mission_review_ok m-1 w-1 gate-7")
            .await;
        assert_eq!(review_ok, "Review approved for m-1:w-1 (revision=5)");

        let test_ok = app.execute_command("/mission_test_ok m-1 w-1").await;
        assert_eq!(test_ok, "Test approved for m-1:w-1 (revision=5)");

        let review_no = app
            .execute_command("/mission_review_no m-1 w-1 needs more logs")
            .await;
        assert_eq!(review_no, "Review denied for m-1:w-1 (revision=5)");
    }

    #[tokio::test]
    async fn agent_team_commands_render_summary_and_list_views() {
        let server = MockServer::start(HashMap::from([
            (
                "/agent-team/missions".to_string(),
                json_response(
                    r#"{"missions":[{"missionID":"mission-1","instanceCount":3,"runningCount":1,"completedCount":1,"failedCount":0,"cancelledCount":1}]}"#,
                ),
            ),
            (
                "/agent-team/instances".to_string(),
                json_response(
                    r#"{"instances":[{"instanceID":"agent-1","role":"reviewer","missionID":"mission-1","sessionID":"s-1","status":"running","parentInstanceID":"lead-1"}]}"#,
                ),
            ),
            (
                "/agent-team/approvals".to_string(),
                json_response(
                    r#"{"spawnApprovals":[{"approvalID":"spawn-1","createdAtMs":1,"request":{"missionID":"mission-1","reason":"Need helper"}}],"toolApprovals":[{"approvalID":"tool-1","sessionID":"s-1","toolCallID":"call-1","tool":"shell","status":"pending"}]}"#,
                ),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let summary = app.execute_command("/agent-team").await;
        assert!(summary.contains("Agent-Team Summary:"));
        assert!(summary.contains("Missions: 1"));
        assert!(summary.contains("Instances: 1"));
        assert!(summary.contains("Spawn approvals: 1"));
        assert!(summary.contains("Tool approvals: 1"));

        let missions = app.execute_command("/agent-team missions").await;
        assert!(missions.contains("Agent-Team Missions:"));
        assert!(missions.contains("mission-1 total=3 running=1 done=1 failed=0 cancelled=1"));

        let instances = app.execute_command("/agent-team instances mission-1").await;
        assert!(instances.contains("Agent-Team Instances:"));
        assert!(instances
            .contains("agent-1 role=reviewer mission=mission-1 status=running parent=lead-1"));

        let approvals = app.execute_command("/agent-team approvals").await;
        assert!(approvals.contains("Agent-Team Approvals:"));
        assert!(approvals.contains("spawn approval spawn-1"));
        assert!(approvals.contains("tool approval tool-1 (shell)"));
    }

    #[tokio::test]
    async fn agent_team_commands_handle_bindings_and_permission_replies() {
        let server = MockServer::start(HashMap::from([
            (
                "/agent-team/approvals/spawn/spawn-1/approve".to_string(),
                json_response(r#"{"ok":true}"#),
            ),
            (
                "/agent-team/approvals/spawn/spawn-1/deny".to_string(),
                json_response(r#"{"ok":true}"#),
            ),
            (
                "/permission/tool-1/reply".to_string(),
                json_response(r#"{"ok":true}"#),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let bindings = app.execute_command("/agent-team bindings").await;
        assert!(
            bindings == "No local agent-team state found."
                || bindings == "No local agent-team bindings found."
        );

        let approve_spawn = app
            .execute_command("/agent-team approve spawn spawn-1 looks good")
            .await;
        assert_eq!(approve_spawn, "Approved spawn approval spawn-1.");

        let approve_tool = app.execute_command("/agent-team approve tool tool-1").await;
        assert_eq!(approve_tool, "Approved tool request tool-1.");

        let deny_spawn = app.execute_command("/agent-team deny spawn spawn-1").await;
        assert_eq!(deny_spawn, "Denied spawn approval spawn-1.");

        let deny_tool = app.execute_command("/agent-team deny tool tool-1").await;
        assert_eq!(deny_tool, "Denied tool request tool-1.");
    }

    #[tokio::test]
    async fn agent_commands_manage_agent_panes() {
        let server = MockServer::start(HashMap::from([(
            "/api/session".to_string(),
            json_response(
                r#"{"id":"s-2","title":"A2 session","directory":null,"workspaceRoot":null,"time":{"created":1,"updated":2}}"#,
            ),
        )]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));
        app.state = chat_state("s-1");

        let created = app.execute_command("/agent new").await;
        assert_eq!(created, "Created new agent.");

        let listed = app.execute_command("/agent list").await;
        assert!(listed.contains("Agents:"));
        assert!(listed.contains("> A2 [s-2] Idle"));
        assert!(listed.contains("  A1 [s-1] Idle"));

        let switched = app.execute_command("/agent use A1").await;
        assert_eq!(switched, "Switched to A1.");

        let closed = app.execute_command("/agent close").await;
        assert_eq!(closed, "Closed active agent.");
        match &app.state {
            AppState::Chat {
                agents,
                active_agent_index,
                ..
            } => {
                assert_eq!(agents.len(), 1);
                assert_eq!(*active_agent_index, 0);
                assert_eq!(agents[0].agent_id, "A2");
            }
            _ => panic!("expected chat state"),
        }
    }

    #[tokio::test]
    async fn agent_fanout_creates_grid_and_switches_mode() {
        let mut app = App::new();
        app.state = chat_state("s-1");
        app.current_mode = TandemMode::Plan;

        let result = app.execute_command("/agent fanout 3").await;
        assert_eq!(
            result,
            "Started fanout: 3 total agents (created 2). Grid view enabled. Mode auto-switched from plan -> orchestrate."
        );
        assert_eq!(app.current_mode, TandemMode::Orchestrate);
        match &app.state {
            AppState::Chat {
                agents,
                ui_mode,
                grid_page,
                ..
            } => {
                assert_eq!(agents.len(), 3);
                assert_eq!(*ui_mode, UiMode::Grid);
                assert_eq!(*grid_page, 0);
                assert_eq!(agents[1].agent_id, "A2");
                assert_eq!(agents[2].agent_id, "A3");
            }
            _ => panic!("expected chat state"),
        }
    }

    #[tokio::test]
    async fn preset_commands_render_index_and_agent_views() {
        let server = MockServer::start(HashMap::from([
            (
                "/presets/index".to_string(),
                json_response(
                    r#"{"index":{"skill_modules":[{"id":"skill.a","version":"1","kind":"skill_module","layer":"base","path":"skills/a","tags":[],"publisher":null,"required_capabilities":[]}],"agent_presets":[{"id":"agent.main","version":"1","kind":"agent_preset","layer":"base","path":"agents/main","tags":[],"publisher":null,"required_capabilities":[]}],"automation_presets":[],"pack_presets":[],"generated_at_ms":42}}"#,
                ),
            ),
            (
                "/presets/compose/preview".to_string(),
                json_response(r#"{"composition":{"prompt":"merged preset prompt"}}"#),
            ),
            (
                "/presets/capability_summary".to_string(),
                json_response(r#"{"summary":{"required":["shell"],"optional":["git"]}}"#),
            ),
            (
                "/presets/fork".to_string(),
                json_response(r#"{"id":"agent-copy","kind":"agent_preset","layer":"override"}"#),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let index = app.execute_command("/preset index").await;
        assert!(index.contains("Preset index:"));
        assert!(index.contains("skill_modules: 1"));
        assert!(index.contains("agent_presets: 1"));
        assert!(index.contains("generated_at_ms: 42"));

        let compose = app
            .execute_command(r#"/preset agent compose Base prompt :: [{"id":"frag-1","phase":"plan","content":"think"}]"#)
            .await;
        assert!(compose.contains("Agent compose preview:"));
        assert!(compose.contains("merged preset prompt"));

        let summary = app
            .execute_command("/preset agent summary required=shell optional=git")
            .await;
        assert!(summary.contains("Agent capability summary:"));
        assert!(summary.contains("\"required\""));

        let fork = app
            .execute_command("/preset agent fork presets/base.yaml agent-copy")
            .await;
        assert!(fork.contains("Forked agent preset override:"));
        assert!(fork.contains("agent-copy"));
    }

    #[tokio::test]
    async fn preset_automation_commands_validate_and_save() {
        let server = MockServer::start(HashMap::from([
            (
                "/presets/capability_summary".to_string(),
                json_response(r#"{"summary":{"score":"ok","required":["shell"]}}"#),
            ),
            (
                "/presets/overrides/automation_preset/nightly".to_string(),
                json_response(r#"{"ok":true,"path":"automation_preset/nightly"}"#),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let invalid = app
            .execute_command("/preset agent compose Base prompt :: {\"bad\":true}")
            .await;
        assert_eq!(
            invalid,
            "fragments_json must be a JSON array of {id,phase,content}"
        );

        let summary = app
            .execute_command(
                r#"/preset automation summary [{"required":["shell"],"optional":["git"]}] :: required=python :: optional=gh"#,
            )
            .await;
        assert!(summary.contains("Automation capability summary (1 tasks):"));
        assert!(summary.contains("\"score\""));

        let saved = app
            .execute_command(
                r#"/preset automation save nightly :: [{"required":["shell"],"optional":["git"]}] :: required=python :: optional=gh"#,
            )
            .await;
        assert!(saved.contains("Saved automation preset override `nightly` with 1 task(s)."));
        assert!(saved.contains("automation_preset/nightly"));
    }

    #[tokio::test]
    async fn routine_commands_validate_usage_and_engine_requirements() {
        let mut app = App::new();

        assert_eq!(
            app.execute_command("/routines").await,
            "Engine client not connected."
        );
        assert_eq!(
            app.execute_command("/routine_create").await,
            "Usage: /routine_create <id> <interval_seconds> <entrypoint>"
        );
        assert_eq!(
            app.execute_command("/routine_edit nightly").await,
            "Usage: /routine_edit <id> <interval_seconds>"
        );
        assert_eq!(
            app.execute_command("/routine_run_now").await,
            "Usage: /routine_run_now <id> [run_count]"
        );
        assert_eq!(
            app.execute_command("/routine_history").await,
            "Usage: /routine_history <id> [limit]"
        );
        assert_eq!(
            app.execute_command("/routine_create nightly 60 plan nightly")
                .await,
            "Engine client not connected."
        );
        assert_eq!(
            app.execute_command("/routine_delete nightly").await,
            "Engine client not connected."
        );

        app.client = Some(EngineClient::new("http://127.0.0.1:1".to_string()));

        assert_eq!(
            app.execute_command("/routine_create nightly nope plan nightly")
                .await,
            "interval_seconds must be a positive integer."
        );
        assert_eq!(
            app.execute_command("/routine_edit nightly nope").await,
            "interval_seconds must be a positive integer."
        );
        assert_eq!(
            app.execute_command("/routine_run_now nightly nope").await,
            "run_count must be a positive integer."
        );
        assert_eq!(
            app.execute_command("/routine_history nightly nope").await,
            "limit must be a positive integer."
        );
    }

    #[tokio::test]
    async fn config_requests_and_copy_commands_use_expected_state() {
        let mut app = App::new();
        app.current_provider = Some("openai".to_string());
        app.current_model = Some("gpt-4.1".to_string());

        let config = app.execute_command("/config").await;
        assert!(config.contains("Configuration:"));
        assert!(config.contains("Current Provider: openai"));
        assert!(config.contains("Current Model: gpt-4.1"));

        let copy = app.execute_command("/copy").await;
        assert_eq!(copy, "Clipboard copy works in chat screens only.");

        app.state = chat_state("s-1");
        if let AppState::Chat {
            pending_requests,
            request_cursor,
            ..
        } = &mut app.state
        {
            pending_requests.push(PendingRequest {
                session_id: "s-1".to_string(),
                agent_id: "A1".to_string(),
                kind: PendingRequestKind::Permission(PendingPermissionRequest {
                    id: "perm-1".to_string(),
                    tool: "shell".to_string(),
                    args: None,
                    args_source: None,
                    args_integrity: None,
                    query: Some("ls".to_string()),
                    status: Some("pending".to_string()),
                }),
            });
            *request_cursor = 99;
        }

        let requests = app.execute_command("/requests").await;
        assert_eq!(requests, "Opened request center (1 pending).");
        match &app.state {
            AppState::Chat {
                modal,
                request_cursor,
                ..
            } => {
                assert_eq!(modal, &Some(ModalState::RequestCenter));
                assert_eq!(*request_cursor, 0);
            }
            _ => panic!("expected chat state"),
        }
    }

    #[tokio::test]
    async fn permission_commands_reply_and_filter_pending_requests() {
        let server = MockServer::start(HashMap::from([
            (
                "/permission".to_string(),
                json_response(
                    r#"{"requests":[{"id":"perm-1","sessionID":"s-1","status":"pending"},{"id":"perm-2","sessionID":"s-2","status":"pending"},{"id":"perm-3","sessionID":"s-1","status":"approved"}],"rules":[]}"#,
                ),
            ),
            (
                "/permission/perm-1/reply".to_string(),
                json_response(r#"{"ok":true}"#),
            ),
            (
                "/permission/perm-9/reply".to_string(),
                json_response(r#"{"ok":true}"#),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));
        app.state = chat_state("s-1");

        let approve_all = app.execute_command("/approve all").await;
        assert_eq!(approve_all, "Approved 1 pending permission request(s).");

        let approve_one = app.execute_command("/approve perm-9 always").await;
        assert_eq!(approve_one, "Approved permission request perm-9.");

        let deny = app.execute_command("/deny perm-9").await;
        assert_eq!(deny, "Denied permission request perm-9.");

        let answer = app.execute_command("/answer perm-9 once").await;
        assert_eq!(answer, "Replied to permission request perm-9.");
    }

    #[tokio::test]
    async fn context_run_commands_render_list_detail_and_driver_views() {
        let run_one = context_run_state_json("run-1", "running", "Investigate rollback", 200);
        let run_two = context_run_state_json("run-2", "paused", "Review logs", 100);
        let replay_run = context_run_state_json("run-1", "running", "Investigate rollback", 200);
        let persisted_run = context_run_state_json("run-1", "paused", "Investigate rollback", 210);
        let next_run = context_run_state_json("run-1", "running", "Investigate rollback", 220);
        let server = MockServer::start(HashMap::from([
            (
                "/context/runs".to_string(),
                json_response(
                    &serde_json::json!({
                        "runs": [
                            serde_json::from_str::<serde_json::Value>(&run_two).expect("run two"),
                            serde_json::from_str::<serde_json::Value>(&run_one).expect("run one")
                        ]
                    })
                    .to_string(),
                ),
            ),
            (
                "/context/runs/run-1".to_string(),
                json_response(
                    &serde_json::json!({
                        "run": serde_json::from_str::<serde_json::Value>(&run_one).expect("detail run"),
                        "rollback_preview_summary": { "step_count": 2 },
                        "rollback_history_summary": { "entry_count": 1 },
                        "last_rollback_outcome": { "outcome": "applied", "reason": "manual" },
                        "rollback_policy": { "eligible": true, "required_policy_ack": "allow_rollback_execution" }
                    })
                    .to_string(),
                ),
            ),
            (
                "/context/runs/run-1/events".to_string(),
                json_response(
                    &serde_json::json!({
                        "events": [
                            {
                                "event_id": "evt-2",
                                "run_id": "run-1",
                                "seq": 2,
                                "ts_ms": 220,
                                "type": "meta_next_step_selected",
                                "status": "running",
                                "step_id": "step-2",
                                "payload": {
                                    "why_next_step": "Need edit verification",
                                    "selected_step_id": "step-2"
                                }
                            },
                            {
                                "event_id": "evt-1",
                                "run_id": "run-1",
                                "seq": 1,
                                "ts_ms": 200,
                                "type": "tool_completed",
                                "status": "running",
                                "step_id": "step-1",
                                "payload": {}
                            }
                        ]
                    })
                    .to_string(),
                ),
            ),
            (
                "/context/runs/run-1/blackboard".to_string(),
                json_response(
                    &serde_json::json!({
                        "blackboard": {
                            "facts": [{ "id": "fact-1", "ts_ms": 1, "text": "Rollback ready" }],
                            "decisions": [{ "id": "decision-1", "ts_ms": 2, "text": "Pause before execute" }],
                            "open_questions": [{ "id": "question-1", "ts_ms": 3, "text": "Need approval?" }],
                            "artifacts": [{ "id": "artifact-1", "ts_ms": 4, "path": "/tmp/plan.md", "artifact_type": "note" }],
                            "summaries": { "rolling": "summary", "latest_context_pack": "pack" },
                            "revision": 9
                        }
                    })
                    .to_string(),
                ),
            ),
            (
                "/context/runs/run-1/replay".to_string(),
                json_response(
                    &serde_json::json!({
                        "ok": true,
                        "run_id": "run-1",
                        "from_checkpoint": true,
                        "checkpoint_seq": 3,
                        "events_applied": 4,
                        "replay": serde_json::from_str::<serde_json::Value>(&replay_run).expect("replay"),
                        "persisted": serde_json::from_str::<serde_json::Value>(&persisted_run).expect("persisted"),
                        "drift": {
                            "mismatch": true,
                            "status_mismatch": true,
                            "why_next_step_mismatch": false,
                            "step_count_mismatch": true
                        }
                    })
                    .to_string(),
                ),
            ),
            (
                "/context/runs/run-1/driver/next".to_string(),
                json_response(
                    &serde_json::json!({
                        "ok": true,
                        "dry_run": true,
                        "run_id": "run-1",
                        "selected_step_id": "step-2",
                        "target_status": "running",
                        "why_next_step": "Need edit verification",
                        "run": serde_json::from_str::<serde_json::Value>(&next_run).expect("next")
                    })
                    .to_string(),
                ),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let list = app.execute_command("/context_runs 1").await;
        assert!(list.contains("Context runs:"));
        assert!(list.contains("run-1 [running]"));
        assert!(!list.contains("run-2 [paused]"));

        let detail = app.execute_command("/context_run_get run-1").await;
        assert!(detail.contains("Context run run-1"));
        assert!(detail.contains("preview_steps: 2"));
        assert!(detail.contains("required_ack: allow_rollback_execution"));

        let events = app.execute_command("/context_run_events run-1 10").await;
        assert!(events.contains("Context run events (run-1):"));
        assert!(events.contains("meta_next_step_selected"));

        let blackboard = app.execute_command("/context_run_blackboard run-1").await;
        assert!(blackboard.contains("Context blackboard run-1"));
        assert!(blackboard.contains("facts: 1"));
        assert!(blackboard.contains("latest_context_pack: <present>"));

        let next = app.execute_command("/context_run_next run-1 dry").await;
        assert!(next.contains("ContextDriver next (preview)"));
        assert!(next.contains("selected_step: step-2"));

        let replay = app.execute_command("/context_run_replay run-1 3").await;
        assert!(replay.contains("Context replay run-1"));
        assert!(replay.contains("drift: true"));

        let lineage = app.execute_command("/context_run_lineage run-1 10").await;
        assert!(lineage.contains("Context decision lineage (run-1):"));
        assert!(lineage.contains("why=Need edit verification"));
    }

    #[tokio::test]
    async fn context_run_create_and_lifecycle_commands_render_engine_responses() {
        let created_run = context_run_state_json("run-1", "planning", "Investigate rollback", 50);
        let server = MockServer::start(HashMap::from([
            (
                "/context/runs".to_string(),
                json_response(
                    &serde_json::json!({
                        "run": serde_json::from_str::<serde_json::Value>(&created_run).expect("created run")
                    })
                    .to_string(),
                ),
            ),
            (
                "/context/runs/run-1/events".to_string(),
                json_response(
                    &serde_json::json!({
                        "event": {
                            "event_id": "evt-lifecycle",
                            "run_id": "run-1",
                            "seq": 7,
                            "ts_ms": 500,
                            "type": "run_updated",
                            "status": "running",
                            "step_id": null,
                            "payload": { "source": "tui" }
                        }
                    })
                    .to_string(),
                ),
            ),
        ]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));

        let created = app
            .execute_command("/context_run_create Investigate rollback")
            .await;
        assert_eq!(created, "Created context run run-1 [interactive].");

        let paused = app.execute_command("/context_run_pause run-1").await;
        assert_eq!(
            paused,
            "Context run run-1 paused (seq=7 event=evt-lifecycle)."
        );

        let resumed = app.execute_command("/context_run_resume run-1").await;
        assert_eq!(
            resumed,
            "Context run run-1 running (seq=7 event=evt-lifecycle)."
        );

        let cancelled = app.execute_command("/context_run_cancel run-1").await;
        assert_eq!(
            cancelled,
            "Context run run-1 cancelled (seq=7 event=evt-lifecycle)."
        );
    }

    #[tokio::test]
    async fn context_run_bind_and_sync_tasks_update_chat_state() {
        let synced_run = context_run_state_json("run-1", "running", "Investigate rollback", 300);
        let server = MockServer::start(HashMap::from([(
            "/context/runs/run-1/todos/sync".to_string(),
            json_response(
                &serde_json::json!({
                    "run": serde_json::from_str::<serde_json::Value>(&synced_run).expect("synced run")
                })
                .to_string(),
            ),
        )]))
        .expect("mock server");

        let mut app = App::new();
        app.client = Some(EngineClient::new(server.base_url()));
        app.state = chat_state("s-1");
        if let AppState::Chat { tasks, agents, .. } = &mut app.state {
            tasks.push(Task {
                id: "task-1".to_string(),
                description: "Investigate rollback".to_string(),
                status: TaskStatus::Working,
                pinned: true,
            });
            agents[0].active_run_id = Some("source-run".to_string());
        }

        let bound = app.execute_command("/context_run_bind run-1").await;
        assert_eq!(bound, "Bound A1 todowrite updates to context run run-1.");
        match &app.state {
            AppState::Chat { agents, .. } => {
                assert_eq!(agents[0].bound_context_run_id.as_deref(), Some("run-1"));
            }
            _ => panic!("expected chat state"),
        }

        let synced = app.execute_command("/context_run_sync_tasks run-1").await;
        assert!(synced.contains("Synced tasks into context run run-1."));
        assert!(synced.contains("status: running"));
        assert!(synced.contains("why_next_step: Need edit verification"));

        let cleared = app.execute_command("/context_run_bind off").await;
        assert_eq!(cleared, "Cleared context-run binding for A1.");
    }

    fn chat_state(session_id: &str) -> AppState {
        let agent = App::make_agent_pane("A1".to_string(), session_id.to_string());
        AppState::Chat {
            session_id: session_id.to_string(),
            command_input: ComposerInputState::new(),
            messages: Vec::new(),
            scroll_from_bottom: 0,
            tasks: Vec::<Task>::new(),
            active_task_id: None,
            agents: vec![agent],
            active_agent_index: 0,
            ui_mode: UiMode::Focus,
            grid_page: 0,
            modal: Option::<ModalState>::None,
            pending_requests: Vec::<PendingRequest>::new(),
            request_cursor: 0,
            permission_choice: 0,
            plan_wizard: PlanFeedbackWizardState::default(),
            last_plan_task_fingerprint: Vec::new(),
            plan_awaiting_approval: false,
            plan_multi_agent_prompt: None,
            plan_waiting_for_clarification_question: false,
            request_panel_expanded: false,
        }
    }

    fn context_run_state_json(
        run_id: &str,
        status: &str,
        objective: &str,
        updated_at_ms: u64,
    ) -> String {
        serde_json::json!({
            "run_id": run_id,
            "run_type": "interactive",
            "status": status,
            "objective": objective,
            "workspace": {
                "workspace_id": "ws-1",
                "canonical_path": "/tmp/workspace",
                "lease_epoch": 1
            },
            "steps": [
                { "step_id": "step-1", "title": "Inspect", "status": "done" },
                { "step_id": "step-2", "title": "Verify", "status": "runnable" }
            ],
            "why_next_step": "Need edit verification",
            "revision": 4,
            "created_at_ms": 10,
            "updated_at_ms": updated_at_ms
        })
        .to_string()
    }

    fn mission_state_json(
        mission_id: &str,
        status: &str,
        title: &str,
        goal: &str,
        revision: u64,
    ) -> String {
        serde_json::json!({
            "mission_id": mission_id,
            "status": status,
            "spec": {
                "mission_id": mission_id,
                "title": title,
                "goal": goal,
                "success_criteria": [],
                "entrypoint": null,
                "budgets": {},
                "capabilities": {},
                "metadata": null
            },
            "work_items": [
                {
                    "work_item_id": "w-1",
                    "title": "Verify rollback",
                    "detail": null,
                    "status": "review",
                    "depends_on": [],
                    "assigned_agent": null,
                    "run_id": null,
                    "artifact_refs": [],
                    "metadata": null
                }
            ],
            "revision": revision,
            "updated_at_ms": 100
        })
        .to_string()
    }

    struct MockServer {
        addr: std::net::SocketAddr,
        running: Arc<AtomicBool>,
        worker: Option<JoinHandle<()>>,
    }

    impl MockServer {
        fn start(routes: HashMap<String, String>) -> anyhow::Result<Self> {
            let listener = TcpListener::bind("127.0.0.1:0")?;
            listener.set_nonblocking(true)?;
            let addr = listener.local_addr()?;
            let running = Arc::new(AtomicBool::new(true));
            let worker_running = Arc::clone(&running);
            let worker = std::thread::spawn(move || {
                while worker_running.load(Ordering::SeqCst) {
                    match listener.accept() {
                        Ok((stream, _)) => {
                            let _ = handle_request(stream, &routes);
                        }
                        Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
                            std::thread::sleep(Duration::from_millis(10));
                        }
                        Err(_) => break,
                    }
                }
            });
            Ok(Self {
                addr,
                running,
                worker: Some(worker),
            })
        }

        fn base_url(&self) -> String {
            format!("http://{}", self.addr)
        }
    }

    impl Drop for MockServer {
        fn drop(&mut self) {
            self.running.store(false, Ordering::SeqCst);
            let _ = TcpStream::connect(self.addr);
            if let Some(worker) = self.worker.take() {
                let _ = worker.join();
            }
        }
    }

    fn json_response(body: &str) -> String {
        format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        )
    }

    fn handle_request(
        mut stream: TcpStream,
        routes: &HashMap<String, String>,
    ) -> anyhow::Result<()> {
        stream.set_read_timeout(Some(Duration::from_millis(250)))?;
        let mut buf = [0u8; 8192];
        let n = stream.read(&mut buf)?;
        if n == 0 {
            return Ok(());
        }
        let request = String::from_utf8_lossy(&buf[..n]);
        let first_line = request.lines().next().unwrap_or_default();
        let raw_path = first_line.split_whitespace().nth(1).unwrap_or("/");
        let path = raw_path.split('?').next().unwrap_or(raw_path);
        let response = routes.get(path).cloned().unwrap_or_else(|| {
            json_response(r#"{"error":"not found"}"#).replacen("200 OK", "404 Not Found", 1)
        });
        stream.write_all(response.as_bytes())?;
        stream.flush()?;
        Ok(())
    }
}