a3s 0.6.0

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
//! Codex-style terminal UI for the A3S Code agent.
//!
//! Built on the `a3s-tui` TEA framework: it drives an [`AgentSession`] via
//! `session.stream()` and renders the resulting [`AgentEvent`] stream as a live
//! chat transcript, with an inline (y/n/a) approval prompt for tool calls.
//!
//! Streaming bridge: `session.stream()` yields a `tokio::mpsc` receiver. A
//! self-re-issuing "pump" command reads one event, turns it into a `Msg`, and
//! the update handler issues the next pump — feeding the async event stream into
//! the synchronous TEA update loop one event at a time.

use std::collections::{BinaryHeap, HashSet};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};

use a3s_code_core::config::OsConfig;
use a3s_code_core::context::RecentWorkspaceFilesContextProvider;
use a3s_code_core::hitl::TimeoutAction;
use a3s_code_core::workspace::{
    LocalWorkspaceManifest, LocalWorkspaceManifestSnapshot, ManifestWorkspaceBackend,
    WorkspaceServices,
};
use a3s_code_core::{Agent, AgentEvent, AgentSession, SessionOptions, SystemPromptSlots};
use a3s_tui::cmd::{self, Cmd};
use a3s_tui::components::textarea::TextareaMsg;
use a3s_tui::components::viewport::ViewportMsg;
use a3s_tui::components::{Spinner, Textarea, Viewport};
use a3s_tui::event::KeyEvent;
use a3s_tui::keymap::{KeyBinding, Keymap};
use a3s_tui::layout::{Constraint, Layout};
use a3s_tui::streaming::StreamingMarkdown;
use a3s_tui::style::{Color, Style};
use a3s_tui::{Event, KeyCode, KeyModifiers, Model, ProgramBuilder};
use tokio::sync::{mpsc, Mutex};

use crate::top::{collect_processes, render_process_table, ProcessRow, ProcessTableView};

mod config;
mod gitutil;
mod image;
mod kbutil;
mod memutil;
mod os_im;
mod panels;
mod remote_ui;
mod render;
pub(crate) mod skills;
mod syntax;
mod update;
mod util;
use config::*;
use gitutil::*;
use image::*;
use memutil::*;
use render::*;
use skills::*;
use syntax::*;
use update::*;
use util::*;

/// Theme accent — OS blue. Single source of truth for the UI accent color.
// Tokyo Night palette — muted, cohesive accents used across the whole UI.
const ACCENT: Color = Color::Rgb(122, 162, 247); // soft blue (primary)
const TN_GREEN: Color = Color::Rgb(158, 206, 106);
const TN_YELLOW: Color = Color::Rgb(224, 175, 104);
const TN_RED: Color = Color::Rgb(247, 118, 142);
const TN_CYAN: Color = Color::Rgb(125, 207, 255);
const TN_ORANGE: Color = Color::Rgb(255, 158, 100);
const TN_PURPLE: Color = Color::Rgb(187, 154, 247); // magenta / purple accent
const TN_FG: Color = Color::Rgb(192, 202, 245); // body text
const TN_GRAY: Color = Color::Rgb(122, 132, 168); // completed / muted tasks

/// Self-contained system-prompt directive injected ONLY when signed in to the OS
/// platform. It disambiguates "OS" (the user means the signed-in OS open
/// platform, not this machine's operating system) AND inlines exactly how to call
/// the progressive API, so the model can act immediately — without first
/// discovering/loading the `a3s-os-capabilities` skill (that extra hop is why a
/// passive catalog entry rarely triggered: the model fell back to `whoami`).
/// `base_url` is the signed-in address so the endpoint is concrete.
fn os_platform_guide(base_url: &str) -> String {
    format!(
        "[OS platform] You are signed in to the OS open platform at {base_url} (via /login). \
DEFAULT RULE: while signed in, \"OS\" in the user's questions ALWAYS means THIS OS platform — \
never this machine's operating system. So \"what's my OS account\", \"what modules does OS have\", \
etc. are about the platform. Answer them via the platform's progressive API; do NOT answer from \
this machine (whoami / hostname / paths / working directory describe the local box, not the \
platform — they are the WRONG answer). The endpoint and auth token are ALREADY in your shell \
environment (exported at login) — use them directly; do NOT read ~/.a3s/os-auth.json or any config \
file on each call:\n\
  curl -s -X POST \"$A3S_OS_BASE_URL/api/v1/kernel/capabilities\" \
-H \"Authorization: Bearer $A3S_OS_TOKEN\" -H 'Content-Type: application/json' \
-d '{{\"action\":\"list\"}}'\n\
Body fields: `action` = list|search|describe|execute, plus `module` / `operation` / `params`. \
Go broad→narrow: `list` (modules) → `describe`/`search` for the one operation → `execute`. \
For `list`/`search`/`describe`, pipe through `jq` to extract only the fields you need so output \
stays a few lines (e.g. `| jq -r '.data.modules[].name'`). \
For `execute`, ALWAYS add `\"shaped\":true` to the request body — that is what makes the response \
carry the `.view` popup deep-link — and do NOT jq-narrow an execute response: pipe it whole (it is \
already compact), so `.view` survives. If you strip `.view` (or omit `\"shaped\":true`), the user \
loses the 查看视图 link. \
Summarize the result for the user in a few lines; do NOT paste the whole raw JSON back. \
After your summary, ALWAYS output the trace on its own line, exactly \
`↳ requestId <requestId> · <timestamp>`. \
You do NOT print the view link yourself: whenever the execute output carries a `.view`, the host \
automatically shows a one-click `🔗 查看视图` line that opens the authenticated 渐进式UI popup \
(the user's OS login is injected, no re-login). Never print the raw URL. The \
`a3s-os-capabilities` skill has full examples."
    )
}

/// Built-in slash commands shown in the `/` menu.
const SLASH_COMMANDS: &[(&str, &str)] = &[
    (
        "/model",
        "switch model (←/→ for Claude/GPT accounts if signed in)",
    ),
    ("/init", "analyze the project and generate AGENTS.md"),
    ("/config", "edit config.acl in the built-in editor"),
    ("/theme", "cycle the code-highlight theme (Atom One Dark …)"),
    (
        "/workflow",
        "view the latest ultracode dynamic workflow (read-only)",
    ),
    (
        "/review",
        "reopen the review checklist · or pick a local repos project to review",
    ),
    (
        "/deploy",
        "pick a repos project → Agentic CI/CD → OS gateway (needs /login)",
    ),
    (
        "/run",
        "pick a repos project → dev-mode debug run on A3S Runtime → access URL (needs /login)",
    ),
    (
        "/flow",
        "pick a flow DAG → OS workflow designer (edit + debug run, needs /login) · /flow <text> drafts one",
    ),
    (
        "/evolve",
        "pick a repo → set a goal → multi-round auto-improving dev (needs /login)",
    ),
    (
        "/output",
        "view every tool call this session (name · args · result)",
    ),
    ("/login", "sign in to the configured OS account"),
    ("/logout", "sign out from the configured OS account"),
    ("/view", "open the last OS view in a native window"),
    ("/plugin", "enable/disable Claude skills & plugins"),
    ("/reload", "re-scan skills/plugins (hot-reload the / menu)"),
    ("/update", "upgrade a3s to the latest release"),
    ("/btw", "ask a background side-question (/btw <prompt>)"),
    ("/top", "live process monitor (highlights coding agents)"),
    ("/ide", "superfile-style file browser + editor"),
    ("/im", "OS chat — DMs & groups (standalone; needs /login)"),
    ("/git", "git status / diff / stage / commit (gitui-style)"),
    (
        "/memory",
        "browse the agent's long-term memory (GitLens-style timeline)",
    ),
    (
        "/kb",
        "browse/manage the knowledge base · /kb <text|file|folder> adds",
    ),
    (
        "/ctx",
        "search past sessions (ctx) · /ctx <n> attach · /ctx save <n> keep as memory",
    ),
    ("/effort", "adjust model effort (low … max)"),
    ("/compact", "summarize + compact the conversation context"),
    ("/goal", "set a north-star goal the agent keeps in mind"),
    (
        "/loop",
        "run a task, auto-continuing until done (Esc stops)",
    ),
    (
        "/sleep",
        "consolidate today's work into memory (experience · preferences · knowledge)",
    ),
    ("/relay", "continue an unfinished task from another agent"),
    ("/help", "show commands and shortcuts"),
    (
        "/fork",
        "branch a new session from this point (original kept)",
    ),
    ("/clear", "reset the conversation"),
    ("/auto", "switch to auto-approve mode"),
    ("/exit", "quit a3s code"),
];

/// Slash commands that mutate the session / conversation and so must NOT run
/// mid-stream — hidden from the menu and rejected while a turn is in flight.
const IDLE_ONLY: &[&str] = &[
    "/clear", "/compact", "/model", "/effort", "/goal", "/loop", "/relay", "/reload", "/update",
    "/init", "/fork", "/review", "/sleep", "/flow",
];

/// Slash commands whose name starts with `input` (input begins with `/`).
fn slash_candidates(input: &str) -> Vec<(&'static str, &'static str)> {
    SLASH_COMMANDS
        .iter()
        .filter(|(cmd, _)| cmd.starts_with(input))
        .copied()
        .collect()
}

/// Glyph + colour for a plan task's status.
fn task_status_style(status: a3s_code_core::planning::TaskStatus) -> (char, Color) {
    use a3s_code_core::planning::TaskStatus;
    match status {
        TaskStatus::Completed => ('', TN_GRAY),
        TaskStatus::InProgress => ('', TN_YELLOW),
        TaskStatus::Failed => ('', TN_RED),
        TaskStatus::Skipped | TaskStatus::Cancelled => ('', TN_GRAY),
        _ => ('', TN_GRAY), // Pending
    }
}

/// A turn that delegated work (tools / subagents / planning) but stopped without
/// a final user-facing answer should auto-synthesize one. This applies in EVERY
/// mode, not just ultracode: parallel fan-out and planning run at all efforts, so
/// the "did work, produced no answer" gap can happen anywhere (e.g. a high-effort
/// plan that fans out to subagents which return artifacts-only). Fires at most
/// once per turn (`synthesis_used`).
fn needs_synthesis(
    synthesis_inflight: bool,
    synthesis_used: bool,
    had_agent_activity: bool,
    text_after_activity: bool,
) -> bool {
    !synthesis_inflight && !synthesis_used && had_agent_activity && !text_after_activity
}

/// Rough in-flight token estimate for text that's still streaming, before the
/// provider's exact `usage` arrives on End. ASCII text averages ~4 chars/token,
/// but CJK and other wide scripts are closer to ~1 token/char — so a flat
/// `chars / 4` under-counts Chinese by 3-4× and makes the live counter lurch
/// upward when it snaps to the real number. Count the two classes separately.
fn estimate_tokens(s: &str) -> usize {
    let (ascii, wide) = s.chars().fold((0usize, 0usize), |(a, w), c| {
        if c.is_ascii() {
            (a + 1, w)
        } else {
            (a, w + 1)
        }
    });
    ascii / 4 + wide
}

/// Conservative context window assumed for models that declare no `limit.context`
/// in config. Most modern models are >= this, so the ctx% indicator and
/// auto-compaction keep working instead of silently disabling (a 0 window turns
/// both off). Declared limits always override this.
const DEFAULT_CONTEXT_LIMIT: u32 = 128_000;

/// The fixed `max_context_tokens` the core uses for its auto-compaction trigger.
/// The core compares each turn's prompt tokens against this constant and has no
/// setter for the real model window, so we compensate by scaling the threshold.
const CORE_MAX_CONTEXT_TOKENS: f32 = 200_000.0;

/// Resolve a model's usable context window: the declared limit, or a sane
/// default when it's missing/zero so context management never silently no-ops.
fn resolve_ctx_limit(raw: Option<u32>) -> u32 {
    match raw {
        Some(c) if c > 0 => c,
        _ => DEFAULT_CONTEXT_LIMIT,
    }
}

/// Scale the core's auto-compact threshold so it fires at ~85% of `window` (the
/// model's REAL context window) rather than 85% of the core's fixed 200k. For a
/// 128k model: `0.85 * 128k / 200k = 0.544` → triggers at ~108.8k (= 85% of
/// 128k). Windows above ~235k clamp to 1.0 (trigger at 200k): a touch early, but
/// it never lets the window overflow. The floor only guards degenerate values —
/// a real floor (like the old 0.05) would push tiny windows' trigger PAST the
/// window itself (0.05 → 10k tokens > an 8k window: compaction could never
/// precede overflow).
fn auto_compact_threshold_for(window: u32) -> f32 {
    let window = if window > 0 {
        window as f32
    } else {
        CORE_MAX_CONTEXT_TOKENS
    };
    (0.85 * window / CORE_MAX_CONTEXT_TOKENS).clamp(0.01, 1.0)
}

/// Context-fill warning latch: maps `pct` to its tier (0/70/85) and says
/// whether crossing INTO a higher tier than `warned` should warn now. The
/// returned tier becomes the new latch, so dropping back (compaction, /clear,
/// model switch) re-arms the warning. Pure for unit-testing.
fn ctx_warn_tier(pct: usize, warned: u8) -> (u8, Option<u8>) {
    let tier: u8 = if pct >= 85 {
        85
    } else if pct >= 70 {
        70
    } else {
        0
    };
    (tier, (tier > warned).then_some(tier))
}

fn workflow_doc_for_tool(name: &str, args: Option<&serde_json::Value>) -> Option<(String, String)> {
    match name {
        "program" => {
            let src = args
                .and_then(|a| a.get("source"))
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())?;
            Some((
                format!("# Dynamic workflow script\n\n```javascript\n{src}\n```\n"),
                "dynamic workflow script · /workflow to view read-only".to_string(),
            ))
        }
        "parallel_task" => {
            let tasks = args
                .and_then(|a| a.get("tasks"))
                .and_then(|t| t.as_array())?
                .iter()
                .collect::<Vec<_>>();
            workflow_doc_for_tasks(&tasks, true)
        }
        "task" => {
            let args = args?;
            if let Some(tasks) = args.get("tasks").and_then(|t| t.as_array()) {
                let tasks = tasks.iter().collect::<Vec<_>>();
                workflow_doc_for_tasks(&tasks, tasks.len() > 1)
            } else {
                workflow_doc_for_tasks(&[args], false)
            }
        }
        _ => None,
    }
}

fn workflow_doc_for_tasks(
    tasks: &[&serde_json::Value],
    parallel: bool,
) -> Option<(String, String)> {
    if tasks.is_empty() {
        return None;
    }

    let mut doc = if parallel {
        format!(
            "# Dynamic workflow\n\nFanned out {} parallel subagent task(s):\n\n",
            tasks.len()
        )
    } else {
        "# Dynamic workflow\n\nDelegated subagent task(s):\n\n".to_string()
    };

    for (i, task) in tasks.iter().enumerate() {
        let desc = task
            .get("description")
            .or_else(|| task.get("prompt"))
            .or_else(|| task.get("task"))
            .and_then(|v| v.as_str())
            .unwrap_or("(task)");
        let agent = task
            .get("agent")
            .and_then(|v| v.as_str())
            .unwrap_or("agent");
        let prompt = task
            .get("prompt")
            .or_else(|| task.get("task"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        doc.push_str(&format!(
            "## {}. {desc}\n\nAgent: `{agent}`\n\n{prompt}\n\n",
            i + 1
        ));
    }

    let label = if parallel {
        format!(
            "dynamic workflow · {} parallel tasks · /workflow to view read-only",
            tasks.len()
        )
    } else {
        format!(
            "dynamic workflow · {} delegated task{} · /workflow to view read-only",
            tasks.len(),
            if tasks.len() == 1 { "" } else { "s" }
        )
    };
    Some((doc, label))
}

/// Brand/theme colour for a coding agent, used to tag its rows and tabs.
fn agent_color(agent: &str) -> Color {
    match agent {
        "a3s-code" => ACCENT,
        "claude code" => Color::Rgb(217, 119, 87), // Claude clay
        "codex" => Color::Rgb(16, 163, 127),       // OpenAI green
        "cursor" => Color::Rgb(180, 182, 200),
        "gemini" => Color::Rgb(124, 137, 245),
        _ => TN_GRAY,
    }
}

/// Snapshot host processes for the `/top` panel via the shared `a3s top`
/// collector, so the panel and `a3s top` agree on rows, agent detection, risk,
/// CWD, and ordering (agents first, then CPU descending).
async fn fetch_top() -> Vec<ProcessRow> {
    collect_processes().await.unwrap_or_default()
}

/// One visible row of the `/ide` file tree (a flattened, expandable tree).
struct IdeEntry {
    path: std::path::PathBuf,
    name: String,
    depth: usize,
    is_dir: bool,
    expanded: bool,
}

/// Editor input mode — vim-aligned: Normal navigates/operates, Insert types.
/// Freshly opened buffers start in Normal.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum EditMode {
    Normal,
    Insert,
}

/// An open, editable file in the `/ide` panel.
struct IdeFile {
    path: std::path::PathBuf,
    lines: Vec<String>, // text rows, or pre-rendered half-block rows if `image`
    scroll: usize,      // top visible row (vertical scroll)
    hscroll: usize,     // leftmost visible column (horizontal scroll; display columns)
    row: usize,         // cursor line
    col: usize,         // cursor column (char index)
    dirty: bool,
    image: bool,    // read-only image preview
    readonly: bool, // view-only (e.g. a dynamic-workflow artifact) — edits blocked
    mode: EditMode, // vim Normal/Insert (see `ide_key`)
    /// A pending operator/prefix awaiting its second keystroke (`d`, `c`, `g`, `y`).
    pending: Option<char>,
    /// Undo snapshots (lines + cursor) for `u`; bounded — configs are small.
    undo: Vec<(Vec<String>, usize, usize)>,
    clip: String,        // yank/delete register for p / P
    clip_linewise: bool, // register holds whole lines (dd/yy) vs an inline span
}

impl IdeFile {
    /// A freshly opened buffer: cursor at the top, Normal mode, empty undo.
    fn new(path: std::path::PathBuf, lines: Vec<String>, image: bool, readonly: bool) -> Self {
        IdeFile {
            path,
            lines: if lines.is_empty() {
                vec![String::new()]
            } else {
                lines
            },
            scroll: 0,
            hscroll: 0,
            row: 0,
            col: 0,
            dirty: false,
            image,
            readonly,
            mode: EditMode::Normal,
            pending: None,
            undo: Vec::new(),
            clip: String::new(),
            clip_linewise: false,
        }
    }
}

/// One completed tool call this session, retained for `/output`.
struct ToolCallRecord {
    name: String,
    args: Option<serde_json::Value>,
    output: String,
    exit_code: i32,
}

/// Render the `/output` viewer body: one `#n · name · status` header per call,
/// then its args and indented output. None when nothing has run.
fn format_tool_log_records(records: &[ToolCallRecord]) -> Option<String> {
    if records.is_empty() {
        return None;
    }
    let mut out = String::new();
    for (i, rec) in records.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        let status = if rec.exit_code == 0 {
            "ok".to_string()
        } else {
            format!("exit {}", rec.exit_code)
        };
        out.push_str(&format!("#{} · {} · {}\n", i + 1, rec.name, status));
        if let Some(args) = &rec.args {
            out.push_str(&format!(
                "  args: {}\n",
                serde_json::to_string(args).unwrap_or_default()
            ));
        }
        let trimmed = rec.output.trim_end();
        if !trimmed.is_empty() {
            out.push_str("  output:\n");
            for line in trimmed.lines() {
                out.push_str("    ");
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    Some(out)
}

/// The directive sent to the agent for a `?` deep-research turn: decompose the
/// question, search and read multiple sources, cross-check, and synthesize a
/// cited report. The user's query is appended.
fn deep_research_prompt(query: &str) -> String {
    format!(
        "Conduct deep research to answer the query below. Be thorough:\n\
         1. Break it into the key sub-questions worth investigating.\n\
         2. Use web search across those sub-questions, then read the most relevant \
         sources in full with web_fetch — don't rely on result snippets alone.\n\
         3. Cross-check claims across multiple independent sources; call out any \
         disagreement, uncertainty, or recency caveats.\n\
         4. Synthesize a comprehensive, well-structured answer with inline \
         citations and a final \"Sources\" list of the URLs you used.\n\n\
         Query: {query}"
    )
}

/// The persistent `/goal` north-star for a `?` deep-research task. Kept short
/// since it is prepended to every continuation turn of the long-horizon loop.
fn deep_research_goal(query: &str) -> String {
    format!("Deep research — deliver a comprehensive, well-cited report answering: {query}")
}

/// Append a one-column vertical scrollbar to the right of the viewport's visible
/// rows. The viewport is sized to `inner_width` (= screen width − 1, see
/// `relayout`) so the bar — a `│` track with an `█` thumb sized and positioned
/// from the scroll state — never clips content. The gutter stays blank when
/// nothing overflows the window.
fn append_scrollbar(view: &str, inner_width: usize, total: usize, scroll_percent: u8) -> String {
    let rows: Vec<&str> = view.split('\n').collect();
    let h = rows.len();
    let overflow = total > h && h > 0;
    // Thumb length proportional to the visible fraction; positioned by percent.
    let thumb_len = if overflow { (h * h / total).max(1) } else { 0 };
    let thumb_start = if overflow {
        (h - thumb_len) * scroll_percent as usize / 100
    } else {
        0
    };
    let track = Style::new().fg(TN_GRAY);
    let thumb = Style::new().fg(ACCENT);
    rows.iter()
        .enumerate()
        .map(|(i, row)| {
            let bar = if !overflow {
                " ".to_string()
            } else if i >= thumb_start && i < thumb_start + thumb_len {
                thumb.render("")
            } else {
                track.render("")
            };
            format!("{}{}", pad_to(row, inner_width), bar)
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The OSC 52 escape that asks the terminal to set the system clipboard to
/// `text` (base64). Works over SSH on terminals that support OSC 52. Capped so a
/// long reply can't blow past a terminal's OSC 52 size limit.
fn osc52_copy(text: &str) -> String {
    use base64::Engine;
    let capped: String = text.chars().take(64_000).collect();
    let b64 = base64::engine::general_purpose::STANDARD.encode(capped.as_bytes());
    format!("\x1b]52;c;{b64}\x07")
}

/// Marker the agent puts inline in its reply to offer the RemoteUI popup. The
/// host recognises a mouse click on any reply line containing it and opens the
/// remembered view (`/view` does the same). The link lives in the message text —
/// the host renders no button of its own.
const VIEW_BUTTON_MARKER: &str = "查看视图";

/// Put `text` on the system clipboard: OSC 52 (portable, survives SSH on
/// supporting terminals) plus the native tool where we have one (macOS pbcopy).
fn copy_to_clipboard(text: &str) {
    use std::io::Write;
    let mut out = std::io::stdout();
    let _ = out.write_all(osc52_copy(text).as_bytes());
    let _ = out.flush();
    #[cfg(target_os = "macos")]
    {
        if let Ok(mut child) = std::process::Command::new("pbcopy")
            .stdin(std::process::Stdio::piped())
            .spawn()
        {
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(text.as_bytes());
            }
            let _ = child.wait();
        }
    }
}

/// Background of an active text selection in the transcript.
const SELECTION_BG: Color = Color::Rgb(58, 64, 88);

/// An in-progress mouse text-selection in the transcript viewport, in screen
/// cells (visible row, column). `anchor` = drag start, `head` = current point.
#[derive(Clone, Copy)]
struct Selection {
    anchor: (u16, u16),
    head: (u16, u16),
}

impl Selection {
    fn is_empty(&self) -> bool {
        self.anchor == self.head
    }
    /// (top_row, top_col, bottom_row, bottom_col), as usize.
    fn ordered(&self) -> (usize, usize, usize, usize) {
        let (a, b) = if self.anchor <= self.head {
            (self.anchor, self.head)
        } else {
            (self.head, self.anchor)
        };
        (a.0 as usize, a.1 as usize, b.0 as usize, b.1 as usize)
    }
}

/// Substring of `s` spanning visible columns `[from, to)` (wide chars counted by
/// display width). A char straddling the start is dropped; one straddling the
/// end is kept.
fn slice_cols(s: &str, from: usize, to: usize) -> String {
    let mut col = 0usize;
    let mut out = String::new();
    for ch in s.chars() {
        if col >= to {
            break;
        }
        if col >= from {
            out.push(ch);
        }
        col += a3s_tui::style::visible_len(&ch.to_string());
    }
    out
}

/// Plain text of a selection over the rendered viewport `view`: screen rows
/// `r1..=r2`, columns `[c1, c2)` clipped on the first/last rows. Rows are
/// ANSI-stripped and trailing padding trimmed.
fn selection_to_text(view: &str, r1: usize, c1: usize, r2: usize, c2: usize) -> String {
    let rows: Vec<&str> = view.split('\n').collect();
    let mut out: Vec<String> = Vec::new();
    for r in r1..=r2 {
        let Some(row) = rows.get(r) else { break };
        let plain = a3s_tui::style::strip_ansi(row);
        let from = if r == r1 { c1 } else { 0 };
        let to = if r == r2 { c2 } else { usize::MAX };
        out.push(slice_cols(&plain, from, to).trim_end().to_string());
    }
    out.join("\n")
}

/// Re-render the viewport `view` with the selected span highlighted: selected
/// rows render in plain text (no syntax colour, transiently) with the selected
/// columns on `SELECTION_BG`; other rows keep their styling.
fn highlight_selection(view: &str, r1: usize, c1: usize, r2: usize, c2: usize) -> String {
    let bg = Style::new().bg(SELECTION_BG).fg(TN_FG);
    view.split('\n')
        .enumerate()
        .map(|(i, row)| {
            if i < r1 || i > r2 {
                return row.to_string();
            }
            let plain = a3s_tui::style::strip_ansi(row);
            let from = if i == r1 { c1 } else { 0 };
            let to = if i == r2 { c2 } else { usize::MAX };
            let before = slice_cols(&plain, 0, from);
            let sel = slice_cols(&plain, from, to);
            let after = slice_cols(&plain, to, usize::MAX);
            format!("{before}{}{after}", bg.render(&sel))
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// State of the `/ide` panel: the file tree, selection, and the open file.
/// Also backs `/config` (rooted at the config dir) and the `/kb` browser
/// (rooted at the vault, with delete enabled) — all superfile-styled.
struct Ide {
    entries: Vec<IdeEntry>,
    sel: usize,
    tree_scroll: usize,
    file: Option<IdeFile>,
    focus_editor: bool,
    /// Transient save status shown in the footer (set on Ctrl+S).
    flash: Option<String>,
    /// Left-panel title ("workspace" / "config" / "knowledge base").
    title: String,
    /// Superfile-style hover preview of the tree-selected file, keyed by path
    /// so it reloads only when the selection actually moves.
    preview: Option<(std::path::PathBuf, Vec<String>)>,
    /// `/kb` browser: the vault root. Enables `x` delete, hard-bounded to
    /// paths inside this root. `None` for /ide and /config.
    kb_root: Option<std::path::PathBuf>,
    /// A path armed for deletion — the next `x` on the same selection deletes.
    armed_delete: Option<std::path::PathBuf>,
}

impl Ide {
    /// A fresh panel over `entries` (no file open, tree focused).
    fn browse(entries: Vec<IdeEntry>, title: &str) -> Self {
        Ide {
            entries,
            sel: 0,
            tree_scroll: 0,
            file: None,
            focus_editor: false,
            flash: None,
            title: title.to_string(),
            preview: None,
            kb_root: None,
            armed_delete: None,
        }
    }
}

/// Whether the chat page's left pane + input act on conversations (`Chat`) or on
/// the contact directory search (`Search`). Tab toggles.
#[derive(Clone, Copy, PartialEq)]
enum ChatMode {
    Chat,
    Search,
}

/// `/im` chat page — a STANDALONE OS instant-messaging surface (left pane:
/// conversations, or a searchable contact directory | right pane: messages;
/// bottom: composer / search box). Talks to the OS IM REST API directly and is
/// deliberately kept OUT of the agent loop: chat content is never fed to the
/// coding agent as context. Live-ish via polling while the page is open.
struct ChatPanel {
    convs: Vec<os_im::ImConversation>,
    /// Selected conversation (index into `convs`).
    sel: usize,
    /// The conversation whose messages are currently loaded.
    active: Option<String>,
    messages: Vec<os_im::ImMessage>,
    /// My own user id, to right-align + label my messages.
    me: Option<String>,
    error: Option<String>,
    loading: bool,
    /// Chat vs. contact-search mode (Tab toggles).
    mode: ChatMode,
    /// Contact-search results (populated in `Search` mode).
    contacts: Vec<os_im::Contact>,
    /// Selected contact (index into `contacts`).
    contact_sel: usize,
}

/// Directory children for the tree, dirs first then files, noise skipped.
fn ide_children(dir: &std::path::Path, depth: usize) -> Vec<IdeEntry> {
    let mut v: Vec<IdeEntry> = std::fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|e| {
            let name = e.file_name().to_string_lossy().into_owned();
            if matches!(
                name.as_str(),
                ".git" | "node_modules" | "target" | ".DS_Store" | ".next" | "dist"
            ) {
                return None;
            }
            let is_dir = e.path().is_dir();
            Some(IdeEntry {
                path: e.path(),
                name,
                depth,
                is_dir,
                expanded: false,
            })
        })
        .collect();
    v.sort_by(|a, b| {
        b.is_dir
            .cmp(&a.is_dir)
            .then(a.name.to_lowercase().cmp(&b.name.to_lowercase()))
    });
    v
}

/// Project instructions for the agent's system prompt. a3s-code already
/// auto-loads `AGENTS.md`; this adds Claude Code's `CLAUDE.md` (preferred), so
/// existing projects work unchanged. Returns the content wrapped with a header.
fn project_instructions(workspace: &str) -> Option<String> {
    for name in ["CLAUDE.md", "AGENT.md"] {
        let p = std::path::Path::new(workspace).join(name);
        if let Ok(c) = std::fs::read_to_string(&p) {
            if !c.trim().is_empty() {
                return Some(format!("# Project Instructions ({name})\n\n{c}"));
            }
        }
    }
    None
}

/// Left margin for the whole UI (inner padding).
const PAD: usize = 2;

/// One `/effort` level. Effort scales reasoning depth on THREE axes so it is
/// meaningful on every model, not just Anthropic:
/// - `thinking_budget`: Anthropic extended-thinking tokens (ignored elsewhere);
/// - `max_tool_rounds`: how much multi-step work a single turn may do;
/// - `guideline`: a system-prompt depth steer (the lever that works on GPT/GLM/
///   OS models, which have no thinking budget) — `None` = the model's balanced
///   default.
///
/// `ultracode` additionally plans, then fans independent work out to parallel
/// subagents via `parallel_task`.
struct EffortProfile {
    label: &'static str,
    thinking_budget: usize,
    max_tool_rounds: usize,
    /// Auto-continuation turns: how many times the loop re-prompts to keep going
    /// when the model stops before the task is done. Higher effort persists longer.
    max_continuation_turns: u32,
    guideline: Option<&'static str>,
}

const EFFORT_LEVELS: &[EffortProfile] = &[
    EffortProfile {
        label: "low",
        thinking_budget: 1024,
        max_tool_rounds: 120,
        max_continuation_turns: 2,
        guideline: Some(EFFORT_LOW),
    },
    EffortProfile {
        label: "medium",
        thinking_budget: 4096,
        max_tool_rounds: 200,
        max_continuation_turns: 3,
        guideline: None,
    },
    EffortProfile {
        label: "high",
        thinking_budget: 8192,
        max_tool_rounds: 300,
        max_continuation_turns: 4,
        guideline: Some(EFFORT_HIGH),
    },
    EffortProfile {
        label: "xhigh",
        thinking_budget: 16384,
        max_tool_rounds: 400,
        max_continuation_turns: 6,
        guideline: Some(EFFORT_XHIGH),
    },
    EffortProfile {
        label: "max",
        thinking_budget: 32768,
        max_tool_rounds: 500,
        max_continuation_turns: 8,
        guideline: Some(EFFORT_MAX),
    },
    EffortProfile {
        label: "ultracode",
        thinking_budget: 32768,
        max_tool_rounds: 600,
        max_continuation_turns: 8,
        guideline: Some(ULTRACODE_GUIDELINES),
    },
];
/// Index of the `ultracode` level (special: planning + parallel subagents).
const ULTRACODE: usize = 5;

// Model-agnostic depth steers injected into the system prompt per effort level.
// They scale reasoning + verification rigor; `medium` has none (the baseline).
// Never tell the model to skip SAFETY checks — low trims optional rigor only.
const EFFORT_LOW: &str = "\
[effort: low] Favor speed and minimalism. Answer directly, make the smallest \
change that works (reading enough surrounding code to change it safely), and \
keep verification proportionate: still run the narrowest build/test/type-check \
that covers what you touched — just don't add checks or scope the task didn't \
warrant. Don't gold-plate.";
const EFFORT_HIGH: &str = "\
[effort: high] Favor depth. Reason through the approach before acting. After \
changes, verify the narrow path you touched (build / test / type-check) and \
check the obvious edge cases, then re-read your own diff for correctness before \
finishing.";
const EFFORT_XHIGH: &str = "\
[effort: xhigh] Work rigorously. Before committing to an approach, weigh at \
least one alternative. Verify thoroughly — run the relevant tests/build, probe \
edge cases and failure modes, and confirm the change actually does what was \
asked. Do a self-review pass for correctness and simplicity before concluding.";
const EFFORT_MAX: &str = "\
[effort: max] Maximum rigor; prefer correctness and completeness over speed. \
Decompose the problem, compare alternatives, and implement the strongest \
solution. Verify exhaustively: tests, build, edge cases, and boundary / \
adversarial inputs. Finish with a self-critique pass that actively hunts for \
what you may have missed or gotten wrong, and fix it before concluding.";
/// Ultracode system-prompt steer: keep the model focused on decomposition and
/// synthesis while the core planning runtime turns independent plan waves into
/// visible `parallel_task` subagents.
const ULTRACODE_GUIDELINES: &str = "\
[ultracode] Dynamic-workflow mode is available — you decide whether a turn needs \
it. Match the effort to the task: answer trivial or conversational input (a \
greeting, a single question, a one-step edit) directly, with no plan and no \
fan-out. When a task genuinely splits into independent branches, decompose it, \
run those branches as parallel background subagents via `parallel_task` (keep \
each child prompt bounded and evidence-oriented), then synthesize their results \
before continuing dependent work.";

/// A resumable/relayable session from this or another coding agent.
struct RelaySession {
    agent: &'static str,
    /// Native a3s-code session id (resume in place), if ours.
    native_id: Option<String>,
    /// Extracted last task, to continue here (foreign agents).
    seed: Option<String>,
    label: String,
    mtime: std::time::SystemTime,
}

/// Last user message in a Claude Code / Codex `.jsonl` transcript.
/// Extract a user message's text from one transcript line, across formats —
/// Claude `{message:{role,content}}` / `{role,content}` and Codex
/// `{payload:{role,content}}` with `input_text` parts. None if not a user line.
fn parse_user_line(line: &str) -> Option<String> {
    let v: serde_json::Value = serde_json::from_str(line).ok()?;
    let role = v
        .get("message")
        .and_then(|m| m.get("role"))
        .or_else(|| v.get("payload").and_then(|p| p.get("role")))
        .or_else(|| v.get("role"))
        .and_then(|r| r.as_str());
    if role != Some("user") {
        return None;
    }
    let content = v
        .get("message")
        .and_then(|m| m.get("content"))
        .or_else(|| v.get("payload").and_then(|p| p.get("content")))
        .or_else(|| v.get("content"))?;
    let txt = match content {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(a) => a
            .iter()
            .filter_map(|p| p.get("text").and_then(|t| t.as_str()))
            .collect::<Vec<_>>()
            .join(" "),
        _ => return None,
    };
    let txt = txt.trim();
    if txt.is_empty() || txt.starts_with('<') {
        return None;
    }
    Some(txt.to_string())
}

/// Most recent user message — read only the file tail (transcripts are big).
fn last_user_msg_jsonl(path: &std::path::Path) -> Option<String> {
    use std::io::{Read, Seek, SeekFrom};
    let mut f = std::fs::File::open(path).ok()?;
    let len = f.metadata().ok()?.len();
    let start = len.saturating_sub(128 * 1024);
    f.seek(SeekFrom::Start(start)).ok()?;
    let mut bytes = Vec::new();
    f.read_to_end(&mut bytes).ok()?;
    let text = String::from_utf8_lossy(&bytes);
    let mut lines: Vec<&str> = text.lines().collect();
    if start > 0 && !lines.is_empty() {
        lines.remove(0); // drop the partial first line
    }
    lines.iter().rev().find_map(|l| parse_user_line(l))
}

/// First user message — the initial task. Read the file head (cheap). Used as a
/// fallback for Codex, whose huge rollouts keep the prompt far from the tail.
fn first_user_msg_jsonl(path: &std::path::Path) -> Option<String> {
    use std::io::Read;
    let mut f = std::fs::File::open(path).ok()?;
    let mut buf = vec![0u8; 96 * 1024];
    let n = f.read(&mut buf).ok()?;
    let text = String::from_utf8_lossy(&buf[..n]);
    text.lines().find_map(parse_user_line)
}

/// Last user message from an a3s-code session JSON (for a task description).
fn last_user_msg_a3s(path: &std::path::Path) -> Option<String> {
    let text = std::fs::read_to_string(path).ok()?;
    let v: serde_json::Value = serde_json::from_str(&text).ok()?;
    for m in v.get("messages")?.as_array()?.iter().rev() {
        if m.get("role").and_then(|r| r.as_str()) != Some("user") {
            continue;
        }
        let txt = match m.get("content") {
            Some(serde_json::Value::String(s)) => s.clone(),
            Some(serde_json::Value::Array(a)) => a
                .iter()
                .filter_map(|p| p.get("text").and_then(|t| t.as_str()))
                .collect::<Vec<_>>()
                .join(" "),
            _ => continue,
        };
        if !txt.trim().is_empty() {
            return Some(txt.trim().to_string());
        }
    }
    None
}

/// A readable session name from a transcript filename (Codex/Claude fallback).
fn jsonl_session_name(p: &std::path::Path) -> String {
    p.file_stem()
        .and_then(|s| s.to_str())
        .map(|s| {
            let s = s.strip_prefix("rollout-").unwrap_or(s);
            s.chars().take(19).collect::<String>().replace('T', " ")
        })
        .unwrap_or_else(|| "session".into())
}

/// Scan a3s-code (native), Claude Code, and Codex session stores for this dir.
fn scan_relay(cwd: &str) -> Vec<RelaySession> {
    let mut out: Vec<RelaySession> = Vec::new();

    // The cwd plus its ancestors — so launching from a subdirectory still finds
    // the project root's sessions (Claude/Codex usually run at the root).
    let mut dirs: Vec<std::path::PathBuf> = Vec::new();
    let mut p = std::path::Path::new(cwd);
    loop {
        dirs.push(p.to_path_buf());
        match p.parent() {
            Some(par) if par != p && dirs.len() < 6 => p = par,
            _ => break,
        }
    }

    // a3s-code: our own session store under cwd/ancestors (resume natively).
    for d in &dirs {
        if let Ok(entries) = std::fs::read_dir(d.join(".a3s/tui-sessions")) {
            for e in entries.flatten() {
                let f = e.path();
                if let Some(id) = f.is_file().then(|| f.file_stem()?.to_str()).flatten() {
                    let mtime = std::fs::metadata(&f)
                        .and_then(|m| m.modified())
                        .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
                    // Show the last task as the description, like Claude/Codex.
                    let label = match last_user_msg_a3s(&f) {
                        Some(m) => format!("a3s-code · {}", truncate(&m, 56)),
                        None => format!("a3s-code · session {id}"),
                    };
                    out.push(RelaySession {
                        agent: "a3s-code",
                        native_id: Some(id.to_string()),
                        seed: None,
                        label,
                        mtime,
                    });
                }
            }
        }
    }

    if let Some(home) = std::env::var_os("HOME") {
        let home = std::path::PathBuf::from(home);
        // Claude Code: ~/.claude/projects/<encoded path>/**.jsonl for cwd+ancestors.
        for d in &dirs {
            let encoded = format!(
                "-{}",
                d.to_string_lossy()
                    .trim_start_matches('/')
                    .replace('/', "-")
            );
            collect_jsonl(
                &home.join(".claude/projects").join(&encoded),
                "claude code",
                &mut out,
            );
        }
        // Codex stores all sessions under one tree.
        collect_jsonl(&home.join(".codex/sessions"), "codex", &mut out);
    }

    // Newest first, then keep only the most recent few per agent — users care
    // about recent sessions, not the whole history.
    out.sort_by_key(|e| std::cmp::Reverse(e.mtime));
    const PER_AGENT: usize = 8;
    let mut kept: std::collections::HashMap<&'static str, usize> = std::collections::HashMap::new();
    out.retain(|s| {
        let n = kept.entry(s.agent).or_insert(0);
        *n += 1;
        *n <= PER_AGENT
    });
    out
}

/// Recursively gather `.jsonl` paths (+ mtime) under `dir` — Claude nests them
/// one level (`<id>/…`), Codex several (`sessions/YYYY/MM/DD/…`).
fn gather_jsonl(
    dir: &std::path::Path,
    depth: usize,
    max: usize,
    out: &mut Vec<(std::path::PathBuf, std::time::SystemTime)>,
) {
    if depth > max {
        return;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for e in entries.flatten() {
        let p = e.path();
        if p.is_dir() {
            gather_jsonl(&p, depth + 1, max, out);
        } else if p.extension().and_then(|x| x.to_str()) == Some("jsonl") {
            let mtime = e
                .metadata()
                .and_then(|m| m.modified())
                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
            out.push((p, mtime));
        }
    }
}

/// Add relay sessions for the most recent transcripts under `dir`. Only the
/// newest dozen are read for a description (cheap), the rest are stat-only.
fn collect_jsonl(dir: &std::path::Path, agent: &'static str, out: &mut Vec<RelaySession>) {
    let mut paths: Vec<(std::path::PathBuf, std::time::SystemTime)> = Vec::new();
    gather_jsonl(dir, 0, 6, &mut paths);
    paths.sort_by_key(|e| std::cmp::Reverse(e.1)); // newest first
    paths.truncate(12);
    for (p, mtime) in paths {
        // Most-recent task (tail); fall back to the initial prompt (head).
        let desc = last_user_msg_jsonl(&p).or_else(|| first_user_msg_jsonl(&p));
        let label = match &desc {
            Some(m) => format!("{agent} · {}", truncate(m, 56)),
            None => format!("{agent} · {}", jsonl_session_name(&p)),
        };
        out.push(RelaySession {
            agent,
            native_id: None,
            seed: desc,
            label,
            mtime,
        });
    }
}

/// Run mode, cycled with Shift+Tab.
#[derive(Clone, Copy, PartialEq)]
enum Mode {
    /// Approve every tool call.
    Default,
    /// Read-only tools auto-approved; writes still prompt (exploration/planning).
    Plan,
    /// Auto-approve every tool call.
    Auto,
}

impl Mode {
    fn next(self) -> Self {
        match self {
            Mode::Default => Mode::Plan,
            Mode::Plan => Mode::Auto,
            Mode::Auto => Mode::Default,
        }
    }

    fn glyph(self) -> &'static str {
        match self {
            Mode::Default => "",
            Mode::Plan => "",
            Mode::Auto => "⏵⏵",
        }
    }

    /// Short one-word name for the status line ("auto mode on").
    fn name(self) -> &'static str {
        match self {
            Mode::Default => "default",
            Mode::Plan => "plan",
            Mode::Auto => "auto",
        }
    }

    fn color(self) -> Color {
        match self {
            Mode::Default => TN_FG,
            Mode::Plan => TN_CYAN,
            Mode::Auto => TN_GREEN,
        }
    }

    /// Whether a tool call is auto-approved in this mode.
    fn auto_approves(self, tool: &str) -> bool {
        match self {
            Mode::Auto => true,
            Mode::Plan => is_readonly_tool(tool),
            Mode::Default => false,
        }
    }
}

fn is_readonly_tool(name: &str) -> bool {
    matches!(
        name,
        "read" | "grep" | "ls" | "glob" | "find" | "search" | "web_search" | "web_fetch"
    )
}

/// A user message queued while the agent is busy. Priority queue: lower `prio`
/// runs first, FIFO within a priority.
struct Queued {
    prio: u8,
    seq: u64,
    text: String,
}

impl PartialEq for Queued {
    fn eq(&self, o: &Self) -> bool {
        self.prio == o.prio && self.seq == o.seq
    }
}
impl Eq for Queued {}
impl Ord for Queued {
    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
        // BinaryHeap is a max-heap; invert so lowest prio, then lowest seq, pops first.
        o.prio.cmp(&self.prio).then(o.seq.cmp(&self.seq))
    }
}
impl PartialOrd for Queued {
    fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(o))
    }
}

/// Shared, single-consumer receiver for the active agent run. Wrapped so the
/// pump command can own a clone; pumps run sequentially, so the mutex never
/// actually contends.
type SharedRx = Arc<Mutex<mpsc::Receiver<AgentEvent>>>;
type SharedManifestRx =
    Arc<Mutex<tokio::sync::broadcast::Receiver<LocalWorkspaceManifestSnapshot>>>;

#[derive(PartialEq)]
enum State {
    Idle,
    Streaming,
    Awaiting,
}

#[derive(Clone)]
#[allow(clippy::enum_variant_names)]
enum Action {
    ScrollUp,
    ScrollDown,
    ScrollTop,
    ScrollBottom,
}

/// Set by `/update` when an upgrade is available: after the TUI exits (terminal
/// restored), `run` performs the upgrade (Homebrew or standalone download) and
/// re-execs the freshly-installed binary.
static UPGRADE_ON_EXIT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The latest version tag, stashed by `/update` for the post-exit upgrade.
static LATEST: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

enum Msg {
    Term(Event),
    // Boxed: AgentEvent is large; keeps the Msg enum small.
    Agent(Box<AgentEvent>),
    Submit(String),
    StreamStarted(SharedRx),
    StreamEnded,
    StreamError(String),
    WorkspaceManifest(Box<LocalWorkspaceManifestSnapshot>),
    WorkspaceManifestStopped,
    SpinnerTick,
    /// Advance the welcome-mascot animation frame.
    BannerTick,
    ModalConfirm(usize),
    Resume,
    Interrupted,
    /// Output of a `!`-prefixed shell command.
    ShellOutput(String),
    /// `/update` version check finished: the latest version tag, if reachable.
    UpdatePlan(Option<String>),
    /// OS login completed.
    OsLogin(Result<String, String>),
    /// Post-login SSH-key sync finished (registers the local pubkey with OS).
    SshKeySynced(crate::a3s_os::SshKeyOutcome),
    /// OS access token was refreshed (or refresh failed) in the background.
    OsRefreshed(Result<crate::a3s_os::StoredOsSession, String>),
    /// OS unified-gateway model ids fetched for the `/model` picker.
    OsGatewayModels(Result<Vec<crate::a3s_os::GatewayModel>, String>),
    /// Answer from a `/btw` background side-thread.
    SideNote(String),
    /// Refreshed process snapshot for the `/top` panel.
    TopData(Vec<ProcessRow>),
    /// Tick to re-fetch the `/top` snapshot.
    TopRefresh,
    /// `/im` conversation list loaded (or an error).
    ImConvs(Result<Vec<os_im::ImConversation>, String>),
    /// `/im` message history for a conversation loaded.
    ImHistory(String, Result<Vec<os_im::ImMessage>, String>),
    /// `/im` send result (the persisted message, or an error).
    ImSent(Result<Box<os_im::ImMessage>, String>),
    /// `/im <userId>` opened/created a DM (select + load it).
    ImDmOpened(Result<Box<os_im::ImConversation>, String>),
    /// `/im` contact-search results (org co-members matching the query).
    ImContacts(Result<Vec<os_im::Contact>, String>),
    /// `/im` resolved the signed-in user's own id (for own-message alignment).
    ImMe(String),
    /// Tick to re-poll the open `/im` page (list + active history).
    ImPoll,
    /// No-op — lets fire-and-forget async work satisfy the `Cmd -> Msg` contract.
    Noop,
    /// `/fork` copied the session under a new id (Ok) — swap the active session to
    /// it — or failed (Err with a reason).
    Forked(Result<String, String>),
    /// Result of the async `/relay` session scan.
    RelayData(Vec<RelaySession>),
    /// `/git` status + recent log snapshot.
    GitStatus(Vec<GitFile>, Vec<String>),
    /// `/git` diff for the selected file.
    GitDiff(Vec<String>),
    /// `/memory` timeline loaded (the store index, newest first).
    MemoryLoaded(Vec<MemEntry>),
    /// `/kb` ingest finished; carries the one-line summary to show.
    KbAdded(String),
    /// `/ctx <query>` finished: raw `ctx search --json` stdout (or the error).
    CtxResults(Result<String, String>),
    /// `/ctx <n>` finished: (hit title, transcript window) to stage as context.
    CtxWindow(Result<(String, String), String>),
    /// `/ctx save <n>` finished: Ok(hit title) once written to the memory store.
    CtxSaved(Result<String, String>),
    /// `/sleep` finished persisting its consolidated memories (count on Ok).
    SleepSaved(Result<usize, String>),
    /// `/flow` pushed a DAG into its OS asset: (flow name, designer url).
    FlowOpened(Result<(String, String), String>),
    /// `/memory` → ctx back-jump finished: (ctx event id, transcript window).
    CtxMemorySource(Result<(String, String), String>),
    /// Inactivity auto-review summary text.
    AutoReview(String),
    /// `/compact` produced this conversation summary; reseed a fresh session.
    Compacted(String),
    /// Startup update check completed with the latest published version (if any).
    UpdateCheck(Option<String>),
}

impl From<Event> for Msg {
    fn from(event: Event) -> Self {
        // Ctrl+C is handled in the key loop (double-press to quit), not here.
        Msg::Term(event)
    }
}

/// Read one event from the active run and turn it into a `Msg`.
fn pump(rx: SharedRx) -> Cmd<Msg> {
    cmd::cmd(move || async move {
        let mut guard = rx.lock().await;
        match guard.recv().await {
            Some(event) => Msg::Agent(Box::new(event)),
            None => Msg::StreamEnded,
        }
    })
}

fn pump_manifest(rx: SharedManifestRx) -> Cmd<Msg> {
    cmd::cmd(move || async move {
        let mut guard = rx.lock().await;
        loop {
            match guard.recv().await {
                Ok(snapshot) => return Msg::WorkspaceManifest(Box::new(snapshot)),
                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                    return Msg::WorkspaceManifestStopped;
                }
            }
        }
    })
}

fn spinner_tick() -> Cmd<Msg> {
    cmd::tick(Duration::from_millis(80), Msg::SpinnerTick)
}

/// Drives the welcome-mascot animation while the banner is on screen.
fn banner_tick() -> Cmd<Msg> {
    cmd::tick(Duration::from_millis(280), Msg::BannerTick)
}

fn with_recent_workspace_context(
    opts: SessionOptions,
    manifest: &Arc<LocalWorkspaceManifest>,
) -> SessionOptions {
    opts.with_context_provider(Arc::new(RecentWorkspaceFilesContextProvider::new(
        manifest.clone(),
    )))
}

fn touch_workspace_file_path_for_manifest(
    manifest: &LocalWorkspaceManifest,
    workspace: &str,
    path: &Path,
) {
    let root = Path::new(workspace);
    if let Ok(relative) = path.strip_prefix(root) {
        if let Some(path) = relative.to_str() {
            manifest.touch_file(path);
        }
    }
}

/// A running (or just-finished) parallel subagent task, for the bottom tracker.
struct SubAgent {
    task_id: String,
    agent: String,
    description: String,
    started: Instant,
    ended: Option<Instant>,
    tokens: u64,
    done: bool,
    success: Option<bool>,
}

struct App {
    session: Arc<AgentSession>,
    /// Agent + session-rebuild bits, kept so `/model` can switch models by
    /// resuming the session under a new model (no in-place model setter exists).
    agent: Arc<Agent>,
    store: Arc<dyn a3s_code_core::store::SessionStore>,
    confirmation: a3s_code_core::hitl::ConfirmationPolicy,
    /// This session's id (for model-switch resume + the exit hint).
    session_id: String,
    /// "provider/model" ids from the config, for the /model picker.
    models: Vec<String>,
    /// Context-window size per model id, for the ctx% indicator.
    model_ctx: std::collections::HashMap<String, u32>,
    /// Context window of the active model (0 = unknown).
    context_limit: u32,
    /// Prompt tokens of the last turn = current context fill.
    last_prompt_tokens: usize,
    /// Highest context-fill tier already warned about (0 / 70 / 85), so each
    /// warning prints once per fill-up and re-arms when usage drops back.
    ctx_warned_tier: u8,
    /// Selected index in the /model panel; `Some` means the panel is open.
    model_menu: Option<usize>,
    /// Active tab in the /model panel (0 = config; account tabs when signed in).
    model_tab: usize,
    /// Custom LLM client to inject for signed-in account tabs; None uses config.acl.
    llm_override: Option<Arc<dyn a3s_code_core::llm::LlmClient>>,
    /// Optional OS endpoint from config.acl; enables /login and /logout.
    os_config: Option<OsConfig>,
    /// Restored OS login (from `~/.a3s/os-auth.json`, persisted across runs);
    /// `None` = signed out. Loaded on startup, set by /login, cleared by /logout.
    os_session: Option<crate::a3s_os::StoredOsSession>,
    /// True while an OS access-token refresh is in flight (guards the BannerTick
    /// trigger from spawning a second refresh before the first resolves).
    os_refreshing: bool,
    /// OS unified-gateway models for the `/model` picker, lazily fetched on
    /// first `/model` while signed in. `None` = not fetched yet; `Some([])` = the
    /// gateway is unavailable/unconfigured.
    os_gateway_models: Option<Vec<String>>,
    /// The precise reason the last gateway-models fetch failed (e.g. `/v1` not
    /// proxied → HTML, auth error, unreachable), shown in the `/model` picker.
    os_gateway_error: Option<String>,
    /// Last OS view seen in a tool result. RemoteUI is user-triggered: `/view`
    /// or clicking the agent's inline "查看视图" link opens it in the native
    /// a3s-webview window — it is never auto-opened.
    last_view: Option<remote_ui::ViewSpec>,
    /// Current model effort (index into EFFORT_LEVELS).
    effort: usize,
    /// `/effort` slider panel: temp selection while open.
    effort_panel: Option<usize>,
    /// `/theme` picker: temp theme index while open.
    theme_panel: Option<usize>,
    /// /relay panel: resumable/relayable sessions, the active agent tab, and the
    /// selected index within that tab (when open).
    relay: Vec<RelaySession>,
    relay_menu: Option<usize>,
    relay_tab: usize,
    /// First Ctrl+C arms quit; a second within the window exits.
    quit_armed: Option<Instant>,
    /// Last user activity; drives the inactivity auto-review.
    last_activity: Instant,
    /// True once the idle conversation has been auto-reviewed (until next input).
    auto_reviewed: bool,
    /// Shell mode: a leading `!` becomes the prompt, the rest is the command.
    shell_mode: bool,
    /// Deep-research mode: a leading `?` turns the input into a deep-research
    /// query — sent to the agent with a multi-source research directive. Box
    /// turns cyan.
    research_mode: bool,
    /// Code-review mode: a leading `&` turns the input into a git repo URL to
    /// clone + deep-review, strictly read-only. Box turns purple. The turn's
    /// ```a3s-review report opens the issue checklist (`review` below).
    review_mode: bool,
    /// True from a `&` submit until its report is parsed (or the run is
    /// interrupted/fails). Gates capture_review so a turn that merely QUOTES
    /// an a3s-review block can't open a phantom checklist.
    review_pending: bool,
    /// True from a `/sleep` submit until its report is parsed (or the run is
    /// interrupted/fails). Gates capture_sleep the same way.
    sleep_pending: bool,
    /// Last parsed `&` review report (issues + checkbox state). Survives the
    /// panel closing so `/review` can reopen it.
    review: Option<panels::review::ReviewState>,
    /// `/deploy` project picker (login-gated); open when `Some`.
    repo_picker: Option<panels::repos::RepoPanel>,
    /// `/flow` DAG picker (login-gated); open when `Some`.
    flow: Option<panels::flow::FlowPanel>,
    /// `/evolve` repo picker (login-gated); open when `Some`.
    evolve: Option<panels::evolve::EvolvePanel>,
    /// True after `/evolve` picks a repo: the next submit is the improvement
    /// direction (sets the standing goal + starts the dev loop).
    evolve_mode: bool,
    /// The repo an evolve session targets `(dir, name)`, set on picker select.
    evolve_target: Option<(std::path::PathBuf, String)>,
    /// Whether the review issue-checklist overlay is showing.
    review_open: bool,
    /// `ctx` CLI detected at startup (past-session history search).
    ctx_ready: bool,
    /// Last `/ctx` search hits, addressable as `/ctx <n>`.
    ctx_hits: Vec<panels::ctx::CtxHit>,
    /// A transcript window staged by `/ctx <n>`, attached (one-shot) to the
    /// next outgoing message.
    pending_ctx: Option<String>,
    /// True for the single `Msg::Submit` the `/loop` mechanism emits to
    /// auto-continue — so on_submit doesn't attach a staged `/ctx` window to
    /// this machine turn.
    loop_continuation: bool,
    /// ALL assistant text of the current turn (across mid-turn tool-call
    /// finalizes, which clear the live streaming buffer). capture_review scans
    /// this when a provider leaves `End.text` empty.
    turn_text: String,
    /// Active transcript text-selection (mouse drag → highlight → copy on
    /// release); `None` when there's no selection.
    selection: Option<Selection>,
    /// Latest dynamic-workflow artifact (ultracode parallel_task dispatch),
    /// shown collapsed in the transcript and openable read-only via `/workflow`.
    last_workflow: Option<String>,
    /// Clipboard images pasted (Ctrl+V), sent with the next message.
    pending_images: Vec<a3s_code_core::llm::Attachment>,
    /// Persistent north-star goal (`/goal`), prepended to each prompt.
    goal: Option<String>,
    /// When the current `/goal` was set — drives the "Pursuing goal (1h 32m)"
    /// elapsed timer in the status bar. `None` whenever `goal` is `None`.
    goal_since: Option<Instant>,
    /// Remaining auto-continue turns for `/loop` (0 = off).
    loop_remaining: usize,
    /// Live parallelism for the status bar: running tools + running subagents.
    active_tools: usize,
    active_agents: usize,
    /// Parallel subagent tasks shown in the bottom tracker panel.
    subagents: Vec<SubAgent>,
    /// True once this turn used tools/planning/subagents that need a final
    /// user-facing synthesis if the model stops without text afterwards.
    turn_had_agent_activity: bool,
    /// True once assistant text arrived after the latest tool/planning/subagent
    /// activity in this turn.
    turn_text_after_activity: bool,
    /// Guard for the hidden ultracode continuation that turns raw workflow
    /// results into a final answer.
    ultracode_synthesis_inflight: bool,
    /// At most one hidden synthesis continuation per user turn.
    ultracode_synthesis_used: bool,
    /// Project instructions (CLAUDE.md/AGENT.md), injected into the system prompt.
    instructions: Option<String>,
    /// Summary of earlier conversation after a manual `/compact` (reseed).
    compact_summary: Option<String>,
    /// Shared in-memory workspace file manifest, refreshed by a background watcher.
    workspace_manifest: Arc<LocalWorkspaceManifest>,
    workspace_manifest_rx: SharedManifestRx,
    /// Manifest-backed workspace backend used by agent tools.
    workspace_services: Arc<WorkspaceServices>,
    /// Brief rainbow-ribbon flourish on the input border when ultracode is picked.
    rainbow_until: Option<Instant>,
    rainbow_frame: usize,
    /// Ultracode confirm animation playing in the /effort panel before it closes.
    effort_anim: Option<Instant>,
    /// Active `/btw` side-chat shown as a panel: (question, answer-once-ready).
    btw: Option<(String, Option<String>)>,
    viewport: Viewport,
    textarea: Textarea,
    spinner: Spinner,
    streaming: StreamingMarkdown,
    /// Whether the current turn streamed any text deltas (vs. text only at End).
    got_delta: bool,
    /// Set while `/compact` is summarizing — drives the progress bar + blocks input.
    compacting: Option<Instant>,
    /// Set while `/update` is upgrading — drives a progress bar + blocks input;
    /// on success the app restarts into the new binary.
    updating: Option<Instant>,
    /// Last time the streaming viewport was rebuilt — throttles the O(n) rebuild
    /// to ~30fps so a flood of deltas doesn't starve animation on the 1 loop.
    last_paint: Option<Instant>,
    /// Live reasoning ("thinking") text for the current turn, shown dimmed above
    /// the answer and cleared when the answer is finalized.
    thinking: String,
    state: State,
    messages: Vec<String>,
    rx: Option<SharedRx>,
    pending_tool: Option<(String, String)>,
    /// Selected row in the tool-approval options panel (0 yes · 1 always · 2 no).
    approval_sel: usize,
    /// Submitted prompts, oldest first, for ↑/↓ recall.
    history: Vec<String>,
    /// Cursor into `history` while browsing; `None` means "fresh input".
    history_pos: Option<usize>,
    /// Model name reported by the provider (captured from the first turn).
    model: Option<String>,
    /// Cumulative OUTPUT (generated) tokens this session — what `↓` reports.
    output_tokens: usize,
    /// Accumulated streamed JSON args of the in-progress tool call, so the
    /// result line can show what the tool actually did (command/path/pattern).
    tool_args: String,
    /// Live stdout of the in-progress tool (e.g. a running command), shown
    /// dimmed under the action and cleared when the tool completes.
    tool_output: String,
    /// Every completed tool call this session (name/args/output), shown by `/output`.
    tool_log: Vec<ToolCallRecord>,
    /// When the current run started, for the live elapsed-time indicator.
    stream_started: Option<Instant>,
    /// Name of the tool currently executing (shown live with a blinking dot).
    running_tool: Option<String>,
    /// Animation counter for the blinking running-tool dot (advances per tick).
    blink_tick: u8,
    /// Frame counter for the welcome-mascot animation.
    anim: u8,
    /// Run mode (Shift+Tab cycles default → plan → auto).
    mode: Mode,
    /// The mode to restore once an autonomous directive run finishes —
    /// `Some` while such a run auto-switched to `Mode::Auto`.
    autonomy_restore: Option<Mode>,
    /// User messages submitted while the agent is busy, run when it frees up.
    queue: BinaryHeap<Queued>,
    /// Monotonic counter for FIFO ordering within a queue priority.
    seq: u64,
    /// Text of the message currently being processed (the running task).
    running_task: Option<String>,
    /// Live plan/TODO from planning mode: (task text, status glyph, colour),
    /// pinned above the input. Updated from PlanningEnd/TaskUpdated events.
    plan: Vec<(String, String, char, Color)>, // (id, content, glyph, colour)
    /// `/top` process panel: `Some(rows)` when open; `top_scroll` is the scroll
    /// offset and `top_sel` the highlighted (absolute) row index.
    top: Option<Vec<ProcessRow>>,
    top_scroll: usize,
    top_sel: usize,
    /// `/top` agent drill-down: `Some(pid)` focuses one coding agent's process
    /// subtree (the agent root + its descendants). `None` shows all processes.
    top_focus: Option<u32>,
    /// Pending force-kill confirmation in `/top`: (pid, command label).
    top_kill: Option<(u32, String)>,
    /// `/ide` file-tree + viewer panel (Some when open).
    ide: Option<Ide>,
    /// `/im` standalone chat page (Some when open). Independent of the agent loop.
    chat: Option<ChatPanel>,
    /// `/git` full-screen panel (Some when open).
    git: Option<Git>,
    /// `/memory` full-screen timeline panel (Some when open).
    memory: Option<MemPanel>,
    /// `/help` overlay panel is showing.
    help_open: bool,
    /// Turns completed this session, for the status-bar task counter.
    completed: usize,
    /// Working directory shown for context.
    cwd: String,
    /// Git branch of the workspace (if any), shown in the bottom status bar.
    branch: Option<String>,
    /// Selected index in the `/` command menu.
    slash_sel: usize,
    /// Workspace files (for the `@` file picker) + its selected index.
    files: Vec<String>,
    file_sel: usize,
    /// Expanded directories in the `@` picker tree (collapsed by default).
    at_expanded: std::collections::HashSet<String>,
    /// Count of discoverable Claude skills (incl. plugin-bundled) for the banner.
    skill_count: usize,
    /// Loaded skills (name, description) for the slash menu + `/plugin`.
    skills: Vec<(String, String)>,
    /// Skill names the user disabled via `/plugins` (persisted, hidden from `/`).
    disabled_skills: std::collections::HashSet<String>,
    /// `/plugins` panel: selected row while open.
    plugins_panel: Option<usize>,
    /// Newer release found at startup (latest version), if any.
    update_available: Option<String>,
    width: u16,
    height: u16,
    keymap: Keymap<Action>,
}

impl App {
    pub(crate) fn touch_workspace_file(&self, path: &str) {
        self.workspace_manifest.touch_file(path);
    }
}

impl Model for App {
    type Msg = Msg;

    fn init(&mut self) -> Option<Cmd<Msg>> {
        // Auto-check for a newer release on every launch (non-blocking).
        let mut cmds = vec![cmd::cmd(|| async {
            Msg::UpdateCheck(check_latest_version().await)
        })];
        cmds.push(pump_manifest(self.workspace_manifest_rx.clone()));
        // Heartbeat for EVERY session (fresh or resumed) — the BannerTick handler
        // self-gates the mascot animation, but it's also the sole driver of the
        // ultracode /effort confirm→apply and the idle auto-review. Resumed
        // sessions used to start no heartbeat, so neither ever fired.
        cmds.push(banner_tick());
        if self.messages.is_empty() {
            self.viewport.set_content(&self.banner());
        } else {
            // Resumed session — show the prior conversation, scrolled to the end.
            self.rebuild_viewport();
            self.viewport.update(ViewportMsg::Bottom);
        }
        Some(cmd::batch(cmds))
    }

    fn update(&mut self, msg: Msg) -> Option<Cmd<Msg>> {
        match msg {
            Msg::Term(Event::Resize { width, height }) => {
                self.selection = None; // screen-coord selection is stale after resize
                self.width = width;
                self.height = height;
                self.relayout();
                self.textarea
                    .set_width(width.saturating_sub((PAD + 2) as u16));
                // An open /ide image buffer is rasterized at open-time width —
                // re-render it for the new panel size or its rows overflow the
                // frame (styled rows can't be re-truncated).
                if let Some(f) = self
                    .ide
                    .as_mut()
                    .and_then(|i| i.file.as_mut())
                    .filter(|f| f.image)
                {
                    let inner = panels::spf::ide_split(width as usize).1.saturating_sub(2);
                    let body = (height as usize).saturating_sub(5);
                    f.lines = render_image_file(&f.path, inner, body)
                        .unwrap_or_else(|| vec!["<cannot decode image>".into()]);
                    f.scroll = 0;
                }
                // Re-wrap the live answer at the new width instead of discarding it
                // (the old reset lost any text streamed before the resize).
                let raw = self.streaming.raw_content().to_string();
                self.streaming = StreamingMarkdown::new((width as usize).saturating_sub(PAD + 2));
                if !raw.is_empty() {
                    self.streaming.push(&raw);
                }
                self.rebuild_viewport();
            }

            // Bracketed paste: drop the whole pasted block into the input as
            // one edit (newlines become real line breaks) instead of N submitted
            // lines / a3s-lane queue spam — Claude-Code-style paste DX.
            Msg::Term(Event::Paste(text)) => {
                self.last_activity = Instant::now();
                self.textarea.insert_str(&text);
                self.relayout();
            }

            Msg::Term(Event::Key(key)) => {
                self.last_activity = Instant::now();
                self.auto_reviewed = false;
                self.selection = None; // any keypress dismisses the copy highlight
                                       // Ctrl+C: arm on the first press, exit on a second within 2s.
                if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
                    match self.quit_armed {
                        Some(t) if t.elapsed() < Duration::from_secs(2) => return Some(cmd::quit()),
                        _ => {
                            self.quit_armed = Some(Instant::now());
                            self.push_line(
                                &Style::new()
                                    .fg(TN_YELLOW)
                                    .render("  press Ctrl+C again to exit"),
                            );
                            return None;
                        }
                    }
                }
                // Esc closes the /btw side-chat panel.
                if self.btw.is_some() && key.code == KeyCode::Esc {
                    self.btw = None;
                    return None;
                }
                // The /help overlay closes on any key.
                if self.help_open {
                    self.help_open = false;
                    return None;
                }
                // /git panel takes all keys while open.
                if self.git.is_some() {
                    return self.git_key(&key);
                }
                // /memory panel takes all keys while open.
                if self.memory.is_some() {
                    return self.memory_key(&key);
                }
                // /ide panel takes all keys while open — except while a tool
                // approval is pending: the prompt is overlaid on the page and
                // must get the keys, or the turn stalls invisibly.
                if self.ide.is_some() {
                    if self.state == State::Awaiting {
                        return self.handle_approval_key(&key);
                    }
                    self.ide_key(&key);
                    return None;
                }
                // /im chat page takes all keys while open (nav + composer).
                if self.chat.is_some() {
                    return self.handle_chat_key(&key);
                }
                // /top panel takes keys while open.
                if self.top.is_some() {
                    // A force-kill confirmation grabs keys first.
                    if self.top_kill.is_some() {
                        match key.code {
                            KeyCode::Char('y' | 'Y') | KeyCode::Enter => {
                                let pid = self.top_kill.take().unwrap().0;
                                return Some(cmd::cmd(move || async move {
                                    let _ = tokio::process::Command::new("kill")
                                        .arg("-9")
                                        .arg(pid.to_string())
                                        .output()
                                        .await;
                                    Msg::TopData(fetch_top().await) // refresh after kill
                                }));
                            }
                            KeyCode::Char('n' | 'N') | KeyCode::Esc => self.top_kill = None,
                            _ => {}
                        }
                        return None;
                    }
                    let rows = self.top_rows();
                    let last = rows.len().saturating_sub(1);
                    match key.code {
                        // Esc backs out of an agent focus first, then closes.
                        KeyCode::Esc => {
                            if self.top_focus.is_some() {
                                self.top_focus = None;
                                self.top_sel = 0;
                                self.top_scroll = 0;
                            } else {
                                self.top = None;
                            }
                        }
                        KeyCode::Up | KeyCode::Char('k') => {
                            self.top_sel = self.top_sel.saturating_sub(1)
                        }
                        KeyCode::Down | KeyCode::Char('j') => {
                            self.top_sel = (self.top_sel + 1).min(last)
                        }
                        KeyCode::PageUp => self.top_sel = self.top_sel.saturating_sub(10),
                        KeyCode::PageDown => self.top_sel = (self.top_sel + 10).min(last),
                        // Enter / → drills into the selected coding agent's
                        // process subtree (its child processes).
                        KeyCode::Enter | KeyCode::Right => {
                            if self.top_focus.is_none() {
                                if let Some(row) = rows.get(self.top_sel) {
                                    if row.agent.is_some() {
                                        self.top_focus = Some(row.pid);
                                        self.top_sel = 0;
                                        self.top_scroll = 0;
                                    }
                                }
                            }
                        }
                        // Shift+K asks to force-kill the highlighted process.
                        KeyCode::Char('K') => {
                            self.top_kill =
                                rows.get(self.top_sel).map(|r| (r.pid, r.command.clone()));
                        }
                        _ => {}
                    }
                    // Keep the selection within the visible window.
                    let body = (self.height as usize).saturating_sub(3);
                    if self.top_sel < self.top_scroll {
                        self.top_scroll = self.top_sel;
                    } else if self.top_sel >= self.top_scroll + body {
                        self.top_scroll = self.top_sel + 1 - body;
                    }
                    return None;
                }
                // Shift+Tab cycles run mode in any state.
                if key.code == KeyCode::BackTab {
                    self.mode = self.mode.next();
                    return None;
                }
                if self.state == State::Awaiting {
                    return self.handle_approval_key(&key);
                }
                // /model picker takes keys while open — consume EVERY key so
                // nothing leaks to the hidden input box behind the overlay.
                if self.model_menu.is_some() {
                    return self.handle_model_key(&key).unwrap_or(None);
                }
                // /effort slider takes keys while open.
                if let Some(sel) = self.effort_panel {
                    match key.code {
                        KeyCode::Left => self.effort_panel = Some(sel.saturating_sub(1)),
                        KeyCode::Right => {
                            self.effort_panel = Some((sel + 1).min(EFFORT_LEVELS.len() - 1))
                        }
                        KeyCode::Enter => {
                            self.effort = sel;
                            if sel == ULTRACODE {
                                // Play a flourish in the panel, then close + apply
                                // (handled on the banner tick).
                                self.effort_anim = Some(Instant::now());
                                self.rainbow_frame = 0;
                            } else {
                                self.effort_panel = None;
                                self.apply_effort();
                            }
                        }
                        KeyCode::Esc => {
                            self.effort_panel = None;
                            self.effort_anim = None;
                        }
                        _ => {}
                    }
                    return None;
                }
                // /theme picker: ↑/↓ preview, Enter apply, Esc cancel.
                if let Some(sel) = self.theme_panel {
                    match key.code {
                        KeyCode::Up => self.theme_panel = Some(sel.saturating_sub(1)),
                        KeyCode::Down => self.theme_panel = Some((sel + 1).min(THEMES.len() - 1)),
                        KeyCode::Enter => {
                            SYNTAX_THEME.store(sel, std::sync::atomic::Ordering::Relaxed);
                            self.theme_panel = None;
                            self.rebuild_viewport();
                            self.push_line(
                                &Style::new()
                                    .fg(TN_GREEN)
                                    .render(&format!("  ◆ code theme: {}", THEMES[sel].name)),
                            );
                        }
                        KeyCode::Esc => self.theme_panel = None,
                        _ => {}
                    }
                    return None;
                }
                // /plugins panel: ↑/↓ select, Space enable/disable, Esc close.
                if let Some(sel) = self.plugins_panel {
                    let last = self.skills.len().saturating_sub(1);
                    match key.code {
                        KeyCode::Up => self.plugins_panel = Some(sel.saturating_sub(1)),
                        KeyCode::Down => self.plugins_panel = Some((sel + 1).min(last)),
                        KeyCode::Char(' ') => {
                            if let Some((name, _)) = self.skills.get(sel.min(last)) {
                                let name = name.clone();
                                if !self.disabled_skills.remove(&name) {
                                    self.disabled_skills.insert(name);
                                }
                                save_disabled_skills(&self.disabled_skills);
                            }
                        }
                        KeyCode::Esc => self.plugins_panel = None,
                        _ => {}
                    }
                    return None;
                }
                // /relay picker takes keys while open.
                // /relay picker: consume EVERY key so none leaks to the input.
                if self.relay_menu.is_some() {
                    return self.handle_relay_key(&key).unwrap_or(None);
                }
                // `&` review issue checklist: consume EVERY key while open.
                if self.review_open {
                    return self.handle_review_key(&key);
                }
                // `/deploy` project picker: consume EVERY key while open.
                if self.repo_picker.is_some() {
                    return self.handle_repo_picker_key(&key);
                }
                // `/flow` DAG picker: same.
                if self.flow.is_some() {
                    return self.handle_flow_key(&key);
                }
                // `/evolve` repo picker: consume EVERY key while open.
                if self.evolve.is_some() {
                    return self.handle_evolve_key(&key);
                }
                // Shift+End jumps to the latest output and resumes auto-follow.
                if key.code == KeyCode::End && key.modifiers.contains(KeyModifiers::SHIFT) {
                    self.viewport.update(ViewportMsg::Bottom);
                    self.viewport.set_auto_scroll(true);
                    return None;
                }
                if let Some(action) = self.keymap.resolve(&key) {
                    let m = match action {
                        Action::ScrollUp => ViewportMsg::PageUp,
                        Action::ScrollDown => ViewportMsg::PageDown,
                        Action::ScrollTop => ViewportMsg::Top,
                        Action::ScrollBottom => ViewportMsg::Bottom,
                    };
                    self.viewport.update(m);
                    // Pause auto-follow while scrolled up; resume once back at the
                    // bottom — so streaming output doesn't yank the view down.
                    self.viewport.set_auto_scroll(self.viewport.at_bottom());
                    return None;
                }
                // Esc leaves shell/research/review mode first (discarding the
                // partial input), taking priority over the streaming interrupt
                // below.
                if (self.shell_mode || self.research_mode || self.review_mode || self.evolve_mode)
                    && key.code == KeyCode::Esc
                {
                    self.shell_mode = false;
                    self.research_mode = false;
                    self.review_mode = false;
                    self.evolve_mode = false;
                    self.evolve_target = None;
                    self.textarea.clear();
                    return None;
                }
                // Esc interrupts the in-progress run (input stays usable otherwise).
                if self.state == State::Streaming && key.code == KeyCode::Esc {
                    self.push_line(&Style::new().fg(TN_YELLOW).render("  ⎋ interrupting…"));
                    let session = self.session.clone();
                    return Some(cmd::cmd(move || async move {
                        session.cancel().await;
                        Msg::Interrupted
                    }));
                }
                // Slash-command menu: ↑/↓ select, Enter run, Tab complete, Esc
                // dismiss — takes priority over history recall while open.
                if self.slash_menu_open() {
                    if let Some(result) = self.handle_slash_key(&key) {
                        return result;
                    }
                }
                // `@` file picker takes nav keys while open.
                if self.file_menu_open() {
                    if let Some(result) = self.handle_file_key(&key) {
                        return result;
                    }
                }
                // ↑/↓ recall prompt history (single-line input only, so multi-line
                // editing keeps normal cursor movement).
                if matches!(key.code, KeyCode::Up | KeyCode::Down)
                    && !self.textarea.value().contains('\n')
                    && !self.history.is_empty()
                {
                    self.history_recall(key.code == KeyCode::Up);
                    return None;
                }
                // Ctrl+V pastes a clipboard image (macOS Cmd+V is swallowed by the
                // terminal, so the app can't see it) to attach to the next message.
                if key.code == KeyCode::Char('v') && key.modifiers.contains(KeyModifiers::CONTROL) {
                    self.paste_clipboard_image();
                    return None;
                }
                // Input is always live (you can keep typing while the agent works);
                // a submit while busy is queued and run when the current turn ends.
                if let Some(TextareaMsg::Submit(text)) = self.textarea.handle_key(&key) {
                    return Some(cmd::msg(Msg::Submit(text)));
                }
                // A leading `!` enters shell mode, a leading `?` enters
                // deep-research mode, a leading `&` enters code-review mode
                // (the prefix is stripped). Each stays on until Esc or a
                // submit (handled elsewhere).
                let val = self.textarea.value();
                if !self.shell_mode && !self.research_mode && !self.review_mode {
                    if let Some(rest) = val.strip_prefix('!') {
                        self.shell_mode = true;
                        self.textarea.set_value(rest);
                    } else if let Some(rest) = val.strip_prefix('?') {
                        self.research_mode = true;
                        self.textarea.set_value(rest);
                    } else if let Some(rest) = val.strip_prefix('&') {
                        self.review_mode = true;
                        self.textarea.set_value(rest);
                    }
                }
            }

            Msg::Term(Event::Mouse(m)) => {
                use a3s_tui::event::{MouseButton, MouseEventKind};
                // Full-screen /ide //config //kb page: the transcript isn't
                // visible, so transcript scroll/select must not act on it
                // (a drag would silently copy hidden text).
                if self.ide.is_some() {
                    return None;
                }
                let vp_rows = self.viewport_rows();
                // Content columns exclude the rightmost scrollbar column.
                let max_col = (self.width as usize).saturating_sub(2) as u16;
                match m.kind {
                    MouseEventKind::ScrollUp => {
                        self.selection = None;
                        self.viewport.update(ViewportMsg::ScrollUp(3));
                    }
                    MouseEventKind::ScrollDown => {
                        self.selection = None;
                        self.viewport.update(ViewportMsg::ScrollDown(3));
                    }
                    // Drag to select transcript text. Capture stays on so the wheel
                    // still scrolls; the app owns selection, so scroll + copy work
                    // together (no mode toggle). Release copies to the clipboard.
                    MouseEventKind::Down(MouseButton::Left) => {
                        self.selection = if (m.row as usize) < vp_rows {
                            let p = (m.row, m.column.min(max_col));
                            Some(Selection { anchor: p, head: p })
                        } else {
                            None
                        };
                    }
                    MouseEventKind::Drag(MouseButton::Left) => {
                        if let Some(s) = self.selection.as_mut() {
                            let row = m.row.min(vp_rows.saturating_sub(1) as u16);
                            s.head = (row, m.column.min(max_col));
                        }
                    }
                    MouseEventKind::Up(MouseButton::Left) => {
                        if let Some(s) = self.selection {
                            if s.is_empty() {
                                // A plain click: open the OS view if it landed on
                                // the agent's inline "查看视图" link; else just clear.
                                let view = self.viewport.view();
                                let clicked = a3s_tui::style::strip_ansi(
                                    view.split('\n')
                                        .nth(s.anchor.0 as usize)
                                        .unwrap_or_default(),
                                );
                                self.selection = None;
                                if clicked.contains(VIEW_BUTTON_MARKER) {
                                    if let Some(spec) = self.last_view.clone() {
                                        self.open_remote_view(&spec);
                                    }
                                }
                            } else {
                                let (r1, c1, r2, c2) = s.ordered();
                                let text = selection_to_text(&self.viewport.view(), r1, c1, r2, c2);
                                if text.trim().is_empty() {
                                    self.selection = None;
                                } else {
                                    // Keep the highlight visible as "copied" feedback.
                                    copy_to_clipboard(&text);
                                }
                            }
                        }
                    }
                    _ => {}
                }
                // Pause auto-follow while scrolled up (so streaming output won't
                // yank the view down); resume once back at the bottom.
                self.viewport.set_auto_scroll(self.viewport.at_bottom());
            }

            Msg::Submit(text) => return self.on_submit(text),

            Msg::StreamStarted(rx) => {
                self.rx = Some(rx.clone());
                return Some(pump(rx));
            }

            Msg::StreamError(e) => {
                self.push_line(&Style::new().fg(TN_RED).render(&format!("  error: {e}")));
                self.loop_remaining = 0; // a failed turn stops the /loop
                self.review_pending = false; // a turn that never started can't
                self.sleep_pending = false; // deliver a review/sleep report
                self.restore_autonomy();
                self.finish();
                // Don't strand messages queued while this turn was starting.
                return self.drain_queue();
            }

            Msg::WorkspaceManifest(snapshot) => {
                self.files = snapshot.file_paths();
                self.file_sel = self.file_sel.min(self.files.len().saturating_sub(1));
                return Some(pump_manifest(self.workspace_manifest_rx.clone()));
            }

            Msg::WorkspaceManifestStopped => {
                let snapshot = self.workspace_manifest.snapshot();
                self.files = snapshot.file_paths();
                self.file_sel = self.file_sel.min(self.files.len().saturating_sub(1));
            }

            Msg::Interrupted => {
                // Esc force-aborted the turn: keep partial output, drop the
                // stream (finish() clears rx so late events are ignored), idle.
                self.finalize_streaming();
                self.push_line(&Style::new().fg(TN_YELLOW).render("  ⎋ interrupted"));
                self.loop_remaining = 0; // Esc also stops a /loop
                self.review_pending = false; // and abandons a `&` review
                self.sleep_pending = false; // and a `/sleep` consolidation
                self.restore_autonomy();
                self.finish();
                return self.drain_queue();
            }

            Msg::Agent(event) => return self.on_agent_event(*event),

            Msg::StreamEnded => {
                // Channel closed without a normal End event (abnormal close).
                if self.state == State::Streaming {
                    self.finalize_streaming();
                }
                // A `&` review report fully streamed before the drop still
                // counts — same for a `/sleep` consolidation report.
                let turn_text = self.turn_text.clone();
                self.capture_review(&turn_text);
                let sleep_save = self.capture_sleep(&turn_text);
                self.disarm_sleep_if_over(sleep_save.is_some());
                return match (sleep_save, self.complete_turn()) {
                    (Some(save), Some(next)) => Some(cmd::batch(vec![save, next])),
                    (save, next) => save.or(next),
                };
            }

            Msg::SpinnerTick => {
                self.spinner.tick();
                self.blink_tick = self.blink_tick.wrapping_add(1);
                if self.state == State::Streaming {
                    self.update_viewport_with_stream();
                    return Some(spinner_tick());
                }
            }

            Msg::BannerTick => {
                // Re-render the animated mascot only while the banner is shown
                // (start screen / after /clear); the heartbeat keeps running so
                // the animation resumes whenever the banner reappears.
                if self.messages.is_empty()
                    && self.state == State::Idle
                    && self.top.is_none()
                    && self.ide.is_none()
                    && self.git.is_none()
                    && self.memory.is_none()
                    && !self.help_open
                {
                    self.anim = self.anim.wrapping_add(1);
                    self.viewport.set_content(&self.banner());
                }
                // Advance the ultracode rainbow flourish (re-renders via the view).
                if self.rainbow_until.is_some() || self.effort_anim.is_some() {
                    self.rainbow_frame = self.rainbow_frame.wrapping_add(1);
                }
                // Ultracode confirm flourish: play in the /effort panel ~1.1s,
                // then close the panel and apply (which lights the input borders).
                if let Some(t) = self.effort_anim {
                    if t.elapsed() > Duration::from_millis(1100) {
                        self.effort_anim = None;
                        self.effort_panel = None;
                        self.apply_effort();
                    }
                }
                // Inactivity auto-review: after a quiet stretch with a real
                // conversation, summarise it once as a side note (Claude-style).
                if !self.auto_reviewed
                    && self.state == State::Idle
                    && !self.messages.is_empty()
                    && self.last_activity.elapsed() > Duration::from_secs(300)
                {
                    self.auto_reviewed = true;
                    let agent = self.agent.clone();
                    let workspace = self.cwd.clone();
                    let history = self.session.history();
                    let review = cmd::cmd(move || async move {
                        let conf = a3s_code_core::hitl::ConfirmationPolicy::enabled()
                            .with_timeout(500, TimeoutAction::Reject);
                        let prompt = "Briefly review this conversation so far: summarise the \
                             key decisions and what's done, then list any open threads or next \
                             steps. Keep it to a few lines.";
                        let mut answer = String::new();
                        if let Ok(sess) = agent.session(
                            workspace,
                            Some(SessionOptions::new().with_confirmation_policy(conf)),
                        ) {
                            if let Ok((mut rx, _j)) = sess.stream(prompt, Some(&history)).await {
                                while let Some(ev) = rx.recv().await {
                                    match ev {
                                        AgentEvent::TextDelta { text } => answer.push_str(&text),
                                        AgentEvent::End { text, .. } => {
                                            if answer.trim().is_empty() {
                                                answer = text;
                                            }
                                            break;
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                        Msg::AutoReview(answer)
                    });
                    return Some(cmd::batch(vec![banner_tick(), review]));
                }
                // Keep the OS access token fresh: refresh proactively before it
                // expires so the agent's $A3S_OS_TOKEN never goes stale mid-session.
                if !self.os_refreshing {
                    if let Some(s) = &self.os_session {
                        if crate::a3s_os::needs_refresh(s) {
                            self.os_refreshing = true;
                            let session = s.clone();
                            let refresh = cmd::cmd(move || async move {
                                Msg::OsRefreshed(
                                    crate::a3s_os::refresh_session(&session)
                                        .await
                                        .map_err(|e| e.to_string()),
                                )
                            });
                            return Some(cmd::batch(vec![banner_tick(), refresh]));
                        }
                    }
                }
                return Some(banner_tick());
            }

            Msg::AutoReview(text) => {
                if !text.trim().is_empty() {
                    // Dim + unobtrusive — it's a passive side note, not output.
                    let dim =
                        |s: &str| format!("  {}", Style::new().fg(TN_GRAY).italic().render(s));
                    let mut lines = vec![dim("⟳ inactivity review")];
                    lines.extend(text.trim().lines().map(dim));
                    self.push_line(&lines.join("\n"));
                }
            }

            Msg::Compacted(summary) => {
                self.compacting = None;
                if summary.trim().is_empty() {
                    self.push_line(
                        &Style::new()
                            .fg(TN_RED)
                            .render("  compaction failed (empty summary)"),
                    );
                    return None;
                }
                // Reseed a FRESH session (new id, no history) carrying just the
                // summary in its system prompt — that's the actual compaction.
                self.compact_summary = Some(summary.trim().to_string());
                self.session_id = new_session_id();
                let model = self.model.clone();
                match self.rebuild_session(model.as_deref()) {
                    Ok((s, _)) => {
                        self.session = Arc::new(s);
                        self.messages.clear();
                        self.output_tokens = 0;
                        self.last_prompt_tokens = 0;
                        self.ctx_warned_tier = 0; // fresh window: re-arm fill warnings
                        self.push_line(
                            &Style::new()
                                .fg(TN_GREEN)
                                .bold()
                                .render("  ✦ context compacted — continuing from this summary:"),
                        );
                        self.push_line(&gutter(
                            TN_CYAN,
                            self.compact_summary.as_deref().unwrap_or(""),
                        ));
                        self.rebuild_viewport();
                    }
                    Err(e) => self.push_line(
                        &Style::new()
                            .fg(TN_RED)
                            .render(&format!("  compaction failed: {e}")),
                    ),
                }
            }

            Msg::UpdateCheck(latest) => {
                let newer = latest
                    .as_deref()
                    .is_some_and(|l| !crate::update::version_ge(env!("CARGO_PKG_VERSION"), l));
                if newer {
                    self.update_available = latest;
                    // Refresh the start screen so the notice shows in the banner
                    // without clobbering it with a transcript line.
                    if self.messages.is_empty() {
                        self.viewport.set_content(&self.banner());
                    }
                }
            }

            Msg::ModalConfirm(idx) => {
                let approved = idx == 0;
                self.state = State::Streaming;
                if let Some((tool_id, label)) = self.pending_tool.take() {
                    // Approved → silent (the tool runs, ToolEnd shows the result);
                    // denied → a brief note since no result will follow.
                    if !approved {
                        self.push_line(
                            &Style::new()
                                .fg(TN_RED)
                                .render(&format!("  ⎿ denied {label}")),
                        );
                    }
                    let session = self.session.clone();
                    return Some(cmd::batch(vec![
                        cmd::cmd(move || async move {
                            let _ = session.confirm_tool_use(&tool_id, approved, None).await;
                            Msg::Resume
                        }),
                        spinner_tick(),
                    ]));
                }
            }

            Msg::Resume => {
                if let Some(rx) = self.rx.clone() {
                    return Some(pump(rx));
                }
            }

            Msg::ShellOutput(text) => {
                let body = text.lines().take(40).collect::<Vec<_>>().join("\n");
                self.push_line(&gutter(TN_GRAY, body.trim_end()));
            }

            Msg::UpdatePlan(latest) => {
                self.updating = None;
                self.relayout();
                let current = env!("CARGO_PKG_VERSION");
                match latest {
                    None => self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  couldn't reach the release server — try again later"),
                    ),
                    Some(l) if crate::update::version_ge(current, &l) => self.push_line(
                        &Style::new()
                            .fg(TN_GREEN)
                            .render(&format!("  ✓ already up to date (a3s {current})")),
                    ),
                    Some(l) => {
                        // macOS/Linux self-update in place (Homebrew or a direct
                        // download); unsupported platforms get the download link.
                        if crate::update::can_self_update() {
                            if let Ok(mut g) = LATEST.lock() {
                                *g = Some(l.clone());
                            }
                            UPGRADE_ON_EXIT.store(true, std::sync::atomic::Ordering::Relaxed);
                            self.push_line(&Style::new().fg(TN_GREEN).render(&format!(
                                "  → a3s {l} available — closing to upgrade, then restarting…"
                            )));
                            return Some(cmd::quit());
                        }
                        self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                            "  → a3s {l} available — download: https://github.com/A3S-Lab/Cli/releases/latest"
                        )));
                    }
                }
            }

            Msg::OsLogin(result) => match result {
                Ok(label) => {
                    // The browser flow already saved to disk; load it into memory
                    // and rebuild so the login-gated skill activates this run.
                    self.os_session = self
                        .os_config
                        .as_ref()
                        .and_then(crate::a3s_os::current_session);
                    if let Some(s) = &self.os_session {
                        crate::a3s_os::export_os_env(s);
                    }
                    self.refresh_after_auth();
                    self.push_line(&Style::new().fg(TN_GREEN).render(&format!(
                        "  ✓ signed in to OS as {label} · capabilities skill active"
                    )));
                    // Auto-register this machine's SSH public key with OS so
                    // git-over-SSH works without manual key setup (idempotent,
                    // best-effort — never blocks the completed login).
                    if let Some(s) = self.os_session.clone() {
                        return Some(cmd::cmd(move || async move {
                            Msg::SshKeySynced(crate::a3s_os::sync_ssh_key(s).await)
                        }));
                    }
                }
                Err(error) => self.push_line(
                    &Style::new()
                        .fg(TN_RED)
                        .render(&format!("  login failed: {error}")),
                ),
            },

            Msg::SshKeySynced(outcome) => {
                use crate::a3s_os::SshKeyOutcome;
                match outcome {
                    SshKeyOutcome::Registered(fp) => self.push_line(&Style::new().fg(TN_GREEN).render(
                        &format!("  ✓ 本机 SSH 公钥已登记到 OS({fp})· git clone(ssh) 就绪"),
                    )),
                    SshKeyOutcome::AlreadyRegistered => self.push_line(
                        &Style::new()
                            .fg(TN_GRAY)
                            .render("  · SSH 公钥已在 OS,跳过登记"),
                    ),
                    SshKeyOutcome::NoLocalKey => self.push_line(&Style::new().fg(TN_YELLOW).render(
                        "  · 未找到本机 SSH 公钥;生成后重新 /login 即可自动登记:ssh-keygen -t ed25519",
                    )),
                    SshKeyOutcome::Failed(e) => self.push_line(
                        &Style::new()
                            .fg(TN_GRAY)
                            .render(&format!("  · SSH key 同步跳过:{e}")),
                    ),
                }
            }

            Msg::OsRefreshed(result) => {
                self.os_refreshing = false;
                match result {
                    Ok(session) => {
                        // Re-export the fresh token so the agent's $A3S_OS_TOKEN
                        // stays valid; no session rebuild needed (the skill reads
                        // the env var at call time). Stay quiet — it's routine.
                        crate::a3s_os::export_os_env(&session);
                        self.os_session = Some(session);
                    }
                    Err(_) => {
                        // Leave the existing session; the next BannerTick retries
                        // while it's still within the refresh window, and /login
                        // remains the fallback once it truly expires.
                    }
                }
            }

            Msg::OsGatewayModels(result) => {
                match result {
                    // Record each model's real context window (when the gateway
                    // reports one) so switching to it sizes auto-compact + the
                    // status bar correctly, then cache the ids.
                    Ok(models) => {
                        for m in &models {
                            if let Some(ctx) = m.context {
                                self.model_ctx.insert(m.id.clone(), ctx);
                            }
                        }
                        self.os_gateway_models = Some(models.into_iter().map(|m| m.id).collect());
                        self.os_gateway_error = None;
                    }
                    // Keep the precise reason so the picker + switch attempt can
                    // explain WHY the gateway is unavailable.
                    Err(e) => {
                        self.os_gateway_models = Some(Vec::new());
                        self.os_gateway_error = Some(e);
                    }
                }
                self.open_model_menu();
            }

            Msg::SideNote(text) => {
                if let Some((q, _)) = self.btw.take() {
                    self.btw = Some((q, Some(text.trim().to_string())));
                }
            }

            Msg::TopData(rows) => {
                if self.top.is_some() {
                    self.top = Some(rows);
                    return Some(cmd::tick(Duration::from_millis(1500), Msg::TopRefresh));
                }
            }
            Msg::TopRefresh => {
                if self.top.is_some() {
                    return Some(cmd::cmd(|| async { Msg::TopData(fetch_top().await) }));
                }
            }
            Msg::ImConvs(result) => return self.on_im_convs(result),
            Msg::ImHistory(id, result) => return self.on_im_history(id, result),
            Msg::ImSent(result) => {
                if let Some(chat) = &mut self.chat {
                    match result {
                        Ok(msg) => {
                            chat.error = None;
                            if chat.active.as_deref() == Some(msg.conversation_id.as_str()) {
                                chat.messages.push(*msg);
                            }
                        }
                        Err(e) => chat.error = Some(e),
                    }
                }
            }
            Msg::ImPoll => {
                if self.chat.is_some() {
                    // IM is login-gated: if the session went away (logout / failed
                    // refresh), close the page instead of polling unauthenticated.
                    if self.os_session.is_none() {
                        self.chat = None;
                        return None;
                    }
                    return Some(self.chat_refresh());
                }
            }
            Msg::ImDmOpened(result) => return self.on_im_dm_opened(result),
            Msg::ImMe(id) => {
                if let Some(chat) = &mut self.chat {
                    if !id.is_empty() {
                        chat.me = Some(id);
                    }
                }
            }
            Msg::ImContacts(result) => {
                if let Some(chat) = &mut self.chat {
                    match result {
                        Ok(contacts) => {
                            chat.contacts = contacts;
                            chat.contact_sel = 0;
                            chat.error = None;
                        }
                        Err(e) => chat.error = Some(e),
                    }
                }
            }
            Msg::Noop => {}
            Msg::Forked(result) => {
                match result {
                    Ok(new_id) => {
                        // Swap the active session to the fork (which carries the copied
                        // history). Set the id first — rebuild_session keys off it — and
                        // revert on failure so id and session never desync. The
                        // transcript stays on screen: the fork continues from here.
                        let prev = std::mem::replace(&mut self.session_id, new_id);
                        let model = self.model.clone();
                        match self.rebuild_session(model.as_deref()) {
                            Ok((s, _)) => {
                                self.session = Arc::new(s);
                                let short: String = self.session_id.chars().take(8).collect();
                                self.push_line(&gutter(
                                TN_CYAN,
                                &format!("⑂ forked into a new session ({short}) — the original is kept"),
                            ));
                            }
                            Err(e) => {
                                self.session_id = prev;
                                self.push_line(
                                    &Style::new()
                                        .fg(TN_RED)
                                        .render(&format!("  fork failed: {e}")),
                                );
                            }
                        }
                    }
                    Err(e) => {
                        self.push_line(&Style::new().fg(TN_YELLOW).render(&format!("  /fork: {e}")))
                    }
                }
            }
            Msg::RelayData(sessions) => {
                if self.relay_menu.is_some() {
                    self.relay = sessions;
                }
            }

            Msg::GitStatus(files, log) => {
                if let Some(g) = &mut self.git {
                    g.files = files;
                    g.log = log;
                    g.sel = g.sel.min(g.files.len().saturating_sub(1));
                    g.log_sel = g.log_sel.min(g.log.len().saturating_sub(1));
                    g.note.clear();
                    return self.git_load_diff();
                }
            }
            Msg::GitDiff(lines) => {
                if let Some(g) = &mut self.git {
                    g.diff = lines;
                    g.diff_scroll = 0;
                }
            }
            Msg::MemoryLoaded(entries) => {
                if let Some(m) = &mut self.memory {
                    m.note = format!("{} entries", entries.len());
                    m.entries = entries;
                    m.sel = 0;
                    m.refresh_detail();
                }
            }
            Msg::KbAdded(summary) => {
                let color = if summary.starts_with('') {
                    TN_RED
                } else {
                    TN_GRAY
                };
                self.push_line(&Style::new().fg(color).render(&format!("  {summary}")));
            }
            Msg::CtxResults(res) => self.on_ctx_results(res),
            Msg::CtxWindow(res) => self.on_ctx_window(res),
            Msg::CtxSaved(res) => self.on_ctx_saved(res),

            Msg::SleepSaved(res) => self.on_sleep_saved(res),

            Msg::FlowOpened(res) => self.on_flow_opened(res),
            Msg::CtxMemorySource(res) => match res {
                Ok((event_id, window)) => {
                    self.memory = None; // leave the panel to show the source
                    self.open_readonly_in_ide(&format!("ctx-source-{event_id}.txt"), &window);
                }
                Err(e) => {
                    if let Some(m) = self.memory.as_mut() {
                        m.note = format!("ctx source unavailable: {e}");
                    }
                }
            },

            _ => {}
        }
        None
    }

    fn view(&self) -> String {
        if self.help_open {
            return self.render_help();
        }
        if let Some(g) = &self.git {
            return self.render_git(g);
        }
        if let Some(m) = &self.memory {
            return self.render_memory(m);
        }
        if let Some(ide) = &self.ide {
            // A pending tool approval overlays the full-screen page so it is
            // never invisible (its keys take priority in the key dispatch).
            let page = self.render_ide(ide);
            return self.overlay_approval(page);
        }
        if let Some(chat) = &self.chat {
            return self.render_chat(chat);
        }
        if self.top.is_some() {
            return self.render_top_panel();
        }
        let width = self.width as usize;
        let raw_view = self.viewport.view();
        // Paint an active text-selection over the visible rows, then add the bar.
        let shown = match &self.selection {
            Some(s) if !s.is_empty() => {
                let (r1, c1, r2, c2) = s.ordered();
                highlight_selection(&raw_view, r1, c1, r2, c2)
            }
            _ => raw_view,
        };
        let viewport_view = append_scrollbar(
            &shown,
            width.saturating_sub(1),
            self.viewport.total_lines(),
            self.viewport.scroll_percent(),
        );
        // Input mode hint: `!` = shell command (pink), `?` = deep research (cyan),
        // `&` = code review (purple), `/btw` = side-channel (yellow), otherwise
        // the normal prompt (accent blue).
        let inp = self.textarea.value();
        let (sym, icolor, border): (&str, Color, Color) = if self.shell_mode {
            ("!", Color::Rgb(255, 105, 180), Color::Rgb(255, 105, 180))
        } else if self.research_mode {
            ("?", TN_CYAN, TN_CYAN)
        } else if self.review_mode {
            ("&", TN_PURPLE, TN_PURPLE)
        } else if self.evolve_mode {
            ("", TN_GREEN, TN_GREEN)
        } else if inp.starts_with("/btw") {
            ("", TN_YELLOW, TN_YELLOW)
        } else {
            ("", ACCENT, TN_GRAY)
        };
        // Brief rainbow ribbon on BOTH input borders right after picking
        // ultracode; otherwise plain bottom + effort-chip top.
        let bar = width.saturating_sub(2 * PAD);
        let rainbow = self
            .rainbow_until
            .is_some_and(|t| t.elapsed() < Duration::from_millis(1600));
        const PALETTE: [Color; 7] = [
            Color::Rgb(255, 0, 0),
            Color::Rgb(255, 127, 0),
            Color::Rgb(255, 255, 0),
            Color::Rgb(0, 220, 0),
            Color::Rgb(0, 150, 255),
            Color::Rgb(75, 0, 200),
            Color::Rgb(160, 0, 230),
        ];
        let ribbon = |offset: usize| {
            let mut s = " ".repeat(PAD);
            for i in 0..bar {
                let c = PALETTE[(i + self.rainbow_frame + offset) % PALETTE.len()];
                s.push_str(&Style::new().fg(c).bold().render(""));
            }
            s
        };
        let separator = if rainbow {
            ribbon(3)
        } else {
            Style::new()
                .fg(border)
                .render(&format!("{}{}", " ".repeat(PAD), "".repeat(bar)))
        };
        let top_separator = if rainbow {
            ribbon(0)
        } else {
            let elabel = format!("{}", EFFORT_LEVELS[self.effort].label);
            // Context-window usage at the top-right of the input (Claude-style).
            let ctxlabel = if self.context_limit > 0 {
                let pct = (self.last_prompt_tokens * 100 / self.context_limit as usize).min(100);
                format!("{pct}% context used  ")
            } else {
                String::new()
            };
            let left = bar.saturating_sub(elabel.chars().count() + ctxlabel.chars().count() + 4);
            format!(
                "{}{} {}{} {}",
                " ".repeat(PAD),
                Style::new().fg(border).render(&"".repeat(left)),
                Style::new().fg(TN_GRAY).render(&ctxlabel),
                Style::new().fg(ACCENT).bold().render(&elabel),
                Style::new().fg(border).render("──"),
            )
        };

        // Activity line directly above the input: spinner while the agent works,
        // an inline approval prompt while awaiting, empty when idle.
        let activity = if self.updating.is_some() {
            // The upgrade itself runs in the shell after exit (real brew
            // progress); in-TUI this is just the quick version check.
            Style::new()
                .fg(TN_GREEN)
                .render("  ⬇ checking for updates…")
        } else if let Some(t0) = self.compacting {
            // Time-estimated progress bar (compaction has no real % to report).
            let secs = t0.elapsed().as_secs();
            let pct = ((secs as f64 / 30.0) * 100.0).min(95.0) as usize;
            let filled = pct * 24 / 100;
            let bar = format!("{}{}", "".repeat(filled), "".repeat(24 - filled));
            Style::new().fg(ACCENT).render(&format!(
                "  ✦ Compacting context… ({}) {bar} {pct}%",
                fmt_elapsed(t0.elapsed())
            ))
        } else {
            match self.state {
                State::Streaming => {
                    // Pulsing sparkle + "Thinking…" with live elapsed + token count.
                    let g = ['', '', '', '', '', ''][(self.blink_tick as usize / 2) % 6];
                    let spark = Style::new().fg(ACCENT).render(&g.to_string());
                    let working = shimmer("Working…", self.blink_tick as usize);
                    let mut tail = String::new();
                    if let Some(t0) = self.stream_started {
                        // Live output estimate: finalized output tokens + a
                        // CJK-aware estimate of the in-flight reasoning + answer
                        // (snaps to exact completion usage on End).
                        let est = self.output_tokens
                            + estimate_tokens(self.streaming.raw_content())
                            + estimate_tokens(&self.thinking);
                        tail.push_str(&format!(" ({}", fmt_elapsed(t0.elapsed())));
                        if est > 0 {
                            tail.push_str(&format!(" · ↓ {} tokens", humanize(est)));
                        }
                        tail.push(')');
                    }
                    let tail = Style::new().fg(ACCENT).render(&tail);
                    format!("  {spark} {working}{tail}")
                }
                // The approval options panel (overlay_approval) is the UI now.
                State::Awaiting => String::new(),
                State::Idle => String::new(),
            }
        };

        let prompt = Style::new().fg(icolor).bold().render(&format!("{sym} "));
        let typed = self.textarea.view();
        let typed = if sym == "!" || sym == "?" || inp.starts_with("/btw") {
            Style::new().fg(icolor).render(&typed)
        } else {
            typed
        };
        // First line carries the prompt; continuation lines (multi-line input)
        // are indented to align under the prompt (PAD margin + "{sym} " = PAD+2).
        let input_view = {
            let cont = " ".repeat(PAD + 2);
            let mut parts = typed.split('\n');
            let first = parts.next().unwrap_or("");
            let mut s = format!("{}{}{}", " ".repeat(PAD), prompt, first);
            for line in parts {
                s.push('\n');
                s.push_str(&cont);
                s.push_str(line);
            }
            s
        };

        // Bottom status bar (Claude-style, two lines):
        //   dir git:(branch) <model> (<window> context) ctx:N%   [+ live chips]
        //   ⏵⏵ <mode> mode on (shift+tab to cycle) · …
        let dim = |s: &str| Style::new().fg(TN_GRAY).render(s);
        let dir = self.cwd.rsplit('/').next().unwrap_or(&self.cwd);
        let mut line1 = format!("  {}", Style::new().fg(ACCENT).bold().render(dir));
        if let Some(b) = &self.branch {
            line1.push_str(&format!(
                " {}{}{}",
                dim("git:("),
                Style::new().fg(TN_YELLOW).render(b),
                dim(")")
            ));
        }
        if let Some(m) = &self.model {
            let name = m.rsplit('/').next().unwrap_or(m);
            line1.push_str(&format!("  {}", Style::new().fg(TN_FG).render(name)));
            if self.context_limit > 0 {
                let win = if self.context_limit >= 1_000_000 {
                    format!("{}M", self.context_limit / 1_000_000)
                } else {
                    format!("{}k", self.context_limit / 1000)
                };
                line1.push_str(&format!(" {}", dim(&format!("({win} context)"))));
            }
        }
        if self.context_limit > 0 {
            let pct = (self.last_prompt_tokens * 100 / self.context_limit as usize).min(100);
            // Color by fill so the approach to the ~85% auto-compact point is visible.
            let c = if pct >= 85 {
                TN_RED
            } else if pct >= 70 {
                TN_YELLOW
            } else {
                TN_GRAY
            };
            line1.push_str(&format!(
                " {}",
                Style::new().fg(c).render(&format!("ctx:{pct}%"))
            ));
        } else if self.output_tokens > 0 {
            line1.push_str(&format!(" {}", dim(&format!("{} tok", self.output_tokens))));
        }
        // Live chips, only when active.
        if self.goal.is_some() {
            let elapsed = self
                .goal_since
                .map(|t| format!(" ({})", fmt_elapsed(t.elapsed())))
                .unwrap_or_default();
            line1.push_str(&format!(
                "  {}",
                Style::new()
                    .fg(TN_CYAN)
                    .render(&format!("🎯 Pursuing goal{elapsed}"))
            ));
        }
        if self.loop_remaining > 0 {
            line1.push_str(&format!("{}", self.loop_remaining));
        }
        if self.active_agents > 0 {
            line1.push_str(&format!("{} agents", self.active_agents));
        }
        if self.active_tools > 0 {
            line1.push_str(&format!("{} running", self.active_tools));
        }
        if let Some(v) = &self.update_available {
            line1.push_str(&format!("{v}"));
        }
        let status1 = pad_to(&line1, width);
        let mode_part = Style::new().fg(self.mode.color()).bold().render(&format!(
            "  {} {} mode on",
            self.mode.glyph(),
            self.mode.name()
        ));
        let hints = dim(" (shift+tab to cycle) · /help · ↑↓ history · esc");
        let status2 = pad_to(&format!("{mode_part}{hints}"), width);

        // Gap line between transcript and loading — or a floating "jump to
        // latest" hint when the user has scrolled up away from the bottom.
        let spacer = if self.viewport.at_bottom() {
            String::new()
        } else {
            let label = " ↓ more below · Shift+End to jump to latest ";
            let pad = width.saturating_sub(a3s_tui::style::visible_len(label)) / 2;
            format!(
                "{}{}",
                " ".repeat(pad),
                Style::new().fg(Color::Black).bg(ACCENT).render(label)
            )
        };
        let tasks = self.task_lines();
        let task_block = tasks.join("\n");
        // Plan/TODO panel stays pinned above the input.
        let plan = self.plan_lines();
        let plan_block = plan.join("\n");
        // Parallel-subagent tracker is pinned at the very bottom, below the
        // status bar (not above the input) so it doesn't push the prompt around.
        let subs = self.subagent_lines();
        let sub_block = subs.join("\n");
        let composed = Layout::vertical()
            .item(&viewport_view, Constraint::Fill)
            .item(&spacer, Constraint::Fixed(1))
            .item(&activity, Constraint::Fixed(1))
            .item(&plan_block, Constraint::Fixed(plan.len() as u16))
            .item(&top_separator, Constraint::Fixed(1))
            .item(&input_view, Constraint::Fixed(self.input_height()))
            .item(&separator, Constraint::Fixed(1))
            .item(&status1, Constraint::Fixed(1))
            .item(&status2, Constraint::Fixed(1))
            .item(&sub_block, Constraint::Fixed(subs.len() as u16))
            .item(&task_block, Constraint::Fixed(tasks.len() as u16))
            .render(self.height);

        let composed = self.overlay_slash_menu(composed);
        let composed = self.overlay_file_menu(composed);
        let composed = self.overlay_model_menu(composed);
        let composed = self.overlay_relay_menu(composed);
        let composed = self.overlay_review_menu(composed);
        let composed = self.overlay_repo_picker(composed);
        let composed = self.overlay_flow_menu(composed);
        let composed = self.overlay_evolve_menu(composed);
        let composed = self.overlay_effort(composed);
        let composed = self.overlay_theme(composed);
        let composed = self.overlay_plugins(composed);
        let composed = self.overlay_approval(composed);
        self.overlay_btw(composed)
    }

    fn cursor(&self) -> Option<(u16, u16)> {
        // In the /ide editor, place the cursor at the edit position — inside
        // the right panel: tree width + its left border + the `%4d ` gutter.
        if let Some(ide) = &self.ide {
            if ide.focus_editor {
                if let Some(f) = &ide.file {
                    let width = self.width as usize;
                    let (tw, _) = panels::spf::ide_split(width);
                    let gutter = if panels::spf::ide_gutter_on(width) {
                        5
                    } else {
                        0
                    };
                    let x = tw + 1 + gutter + f.display_col().saturating_sub(f.hscroll);
                    let col = x.min(width.saturating_sub(2)) as u16;
                    let row = (1 + f.row.saturating_sub(f.scroll)) as u16;
                    return Some((col, row));
                }
            }
            return None;
        }
        // Real cursor at the input insertion point whenever the input is live —
        // idle OR streaming (you can keep typing while the agent works). Hidden
        // only during an approval prompt.
        if self.state == State::Awaiting
            || self.top.is_some()
            || self.git.is_some()
            || self.memory.is_some()
            || self.help_open
        {
            return None;
        }
        // Below the input: separator + 2 status lines + the subagent panel +
        // the task panel. The input spans `input_height` rows; cursor on its row.
        let below = 3 + self.subagent_lines().len() as u16 + self.task_lines().len() as u16;
        let row = self.height.saturating_sub(below + self.input_height())
            + self.textarea.cursor_row() as u16;
        let col = (PAD + 2) as u16 + self.textarea.cursor_display_col() as u16; // PAD + "❯ "
        Some((col, row))
    }
}

impl App {
    fn on_submit(&mut self, text: String) -> Option<Cmd<Msg>> {
        let trimmed = text.trim();
        if trimmed.is_empty() {
            return None;
        }
        // No input while compacting or upgrading.
        if self.compacting.is_some() || self.updating.is_some() {
            self.textarea.clear();
            return None;
        }
        // Evolve mode: the submit after `/evolve` picks a repo is the improvement
        // direction — set the standing goal + loop budget and kick off the first
        // dev turn (subsequent turns keep the goal, so it's multi-round).
        if self.evolve_mode {
            let direction = trimmed.to_string();
            self.history.push(trimmed.to_string());
            self.history_pos = None;
            self.textarea.clear();
            let cmd = self.submit_evolve(&direction);
            self.relayout();
            return cmd;
        }
        // Shell mode (`!`) runs a shell command directly (not through the agent).
        if self.shell_mode {
            self.shell_mode = false;
            let cmd = trimmed.trim_start_matches('!').trim().to_string();
            if cmd.is_empty() {
                return None;
            }
            self.messages.push(gutter(
                Color::Rgb(255, 105, 180),
                &Style::new().bold().render(&format!("! {cmd}")),
            ));
            self.textarea.clear();
            self.rebuild_viewport();
            return Some(cmd::cmd(move || async move {
                let out = tokio::process::Command::new("sh")
                    .arg("-c")
                    .arg(&cmd)
                    .output()
                    .await;
                let text = match out {
                    Ok(o) => {
                        let mut s = String::from_utf8_lossy(&o.stdout).into_owned();
                        s.push_str(&String::from_utf8_lossy(&o.stderr));
                        if s.trim().is_empty() {
                            format!("(exit {})", o.status.code().unwrap_or(-1))
                        } else {
                            s
                        }
                    }
                    Err(e) => format!("failed to run: {e}"),
                };
                Msg::ShellOutput(text)
            }));
        }
        // Deep-research mode (`?`) is a long-horizon task: it anchors the work
        // with the `/goal` mechanism (a persistent north-star prepended to every
        // turn) AND auto-continues via the `/loop` mechanism until the agent
        // reports completion (or Esc). The first turn carries the full
        // decompose → search + read → cross-check → synthesize directive.
        if self.research_mode {
            self.research_mode = false;
            let query = trimmed.trim_start_matches('?').trim().to_string();
            if query.is_empty() {
                self.textarea.clear();
                return None;
            }
            self.history.push(trimmed.to_string());
            self.history_pos = None;
            self.textarea.clear();
            self.goal = Some(deep_research_goal(&query));
            self.goal_since = Some(Instant::now());
            self.messages.push(gutter(
                TN_CYAN,
                &Style::new()
                    .bold()
                    .render(&format!("🔬 deep research: {query}")),
            ));
            self.push_line(&Style::new().fg(TN_GRAY).render(
                "  🎯 goal set · ↻ auto-continues until done (Esc stops · /goal clear drops it)",
            ));
            let prompt = deep_research_prompt(&query);
            let display = format!("🔬 {query}");
            // Long-horizon budget: keep researching across turns toward the
            // goal, with tool prompts auto-approved for the run's duration.
            self.engage_autonomy(8);
            if self.state == State::Idle {
                return self.start_stream_inner(prompt, display, true, true, false);
            }
            self.seq += 1;
            self.queue.push(Queued {
                prio: 1,
                seq: self.seq,
                text: prompt,
            });
            self.push_line(&Style::new().fg(TN_GRAY).render("    ⋯ queued"));
            self.relayout();
            return None;
        }
        // Code-review mode (`&`): clone the given git repo and run a deep,
        // strictly read-only quality inspection. The `/loop` mechanism keeps
        // the agent on it until a turn ends with the machine-readable
        // ```a3s-review report, which capture_review parses into the checkbox
        // panel where the user picks (or selects all) issues to fix — nothing
        // is fixed automatically. Idle-only: review state (pending flag, loop
        // budget, checklist) is App-wide, so a second review racing the first
        // through the queue would clobber it.
        if self.review_mode {
            // Rejected-while-busy keeps the mode + typed URL for a retry.
            if self.state != State::Idle {
                self.push_line(&Style::new().fg(TN_YELLOW).render(
                    "  a code review can't start while a turn is running — press Esc to stop first",
                ));
                return None;
            }
            self.review_mode = false;
            let url = trimmed.trim_start_matches('&').trim().to_string();
            if url.is_empty() {
                self.textarea.clear();
                return None;
            }
            self.history.push(trimmed.to_string());
            self.history_pos = None;
            self.textarea.clear();
            self.review_pending = true;
            self.messages.push(gutter(
                TN_PURPLE,
                &Style::new()
                    .bold()
                    .render(&format!("🔎 code review: {url}")),
            ));
            let clone_dir = repo_dir();
            self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                "  clone into {} → deep inspection → issue checklist to pick fixes (no auto-fix · Esc stops)",
                clone_dir.display()
            )));
            let prompt = panels::review::code_review_prompt(&url, &clone_dir.to_string_lossy());
            let display = format!("🔎 {url}");
            self.engage_autonomy(8);
            return self.start_stream_inner(prompt, display, true, true, false);
        }
        // Block session-mutating commands while a turn is streaming.
        if self.state != State::Idle {
            let cmd0 = trimmed.split_whitespace().next().unwrap_or("");
            if IDLE_ONLY.contains(&cmd0) {
                self.textarea.clear();
                self.push_line(&Style::new().fg(TN_YELLOW).render(&format!(
                    "  {cmd0} is unavailable while a turn is running — press Esc to stop first"
                )));
                return None;
            }
        }
        if let Some(rest) = trimmed.strip_prefix("/login") {
            if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
                // e.g. "/login-token" is not the /login command.
            } else {
                self.textarea.clear();
                let Some(os_config) = self.os_config.clone() else {
                    self.push_line(&format!(
                        "{}\n{}\n{}\n{}",
                        Style::new()
                            .fg(TN_YELLOW)
                            .render("  /login needs an OS endpoint, but none is configured."),
                        Style::new().fg(TN_GRAY).render(
                            "  Add it to ~/.a3s/config.acl (or your project's .a3s/config.acl):"
                        ),
                        Style::new()
                            .fg(TN_CYAN)
                            .render("      os = \"https://your-os-host.example.com\""),
                        Style::new()
                            .fg(TN_GRAY)
                            .render("  then restart a3s code and run /login again."),
                    ));
                    return None;
                };
                let token = rest.trim();
                if !token.is_empty() {
                    match crate::a3s_os::login_with_token(&os_config, token) {
                        Ok(session) => {
                            let label = session.display_label();
                            crate::a3s_os::export_os_env(&session);
                            self.os_session = Some(session);
                            self.refresh_after_auth();
                            self.push_line(&Style::new().fg(TN_GREEN).render(&format!(
                                "  ✓ signed in to OS as {label} · capabilities skill active"
                            )));
                        }
                        Err(error) => self.push_line(
                            &Style::new()
                                .fg(TN_RED)
                                .render(&format!("  login failed: {error}")),
                        ),
                    }
                    return None;
                }

                // Already signed in (restored from a previous run) → no need to
                // re-authenticate; tell the user how to switch instead.
                if let Some(s) = &self.os_session {
                    self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                        "  already signed in to OS as {} · /logout to switch accounts",
                        s.display_label()
                    )));
                    return None;
                }

                self.push_line(
                    &Style::new()
                        .fg(TN_GRAY)
                        .render("  opening OS login in your browser…"),
                );
                return Some(cmd::cmd(move || async move {
                    let result = crate::a3s_os::login_via_browser(os_config)
                        .await
                        .map(|session| session.display_label())
                        .map_err(|error| error.to_string());
                    Msg::OsLogin(result)
                }));
            }
        }
        if trimmed == "/logout" {
            self.textarea.clear();
            let Some(os_config) = self.os_config.clone() else {
                self.push_line(&Style::new().fg(TN_YELLOW).render(
                    "  configure `os = \"https://...\"` in .a3s/config.acl to enable /logout",
                ));
                return None;
            };
            match crate::a3s_os::logout(&os_config) {
                Ok(true) => {
                    self.os_session = None;
                    self.chat = None; // IM requires an OS login — close it on sign-out.
                    crate::a3s_os::remove_capability_skill_dir();
                    crate::a3s_os::clear_os_env();
                    self.refresh_after_auth();
                    self.push_line(
                        &Style::new()
                            .fg(TN_GREEN)
                            .render("  ✓ signed out from OS · capabilities skill removed"),
                    );
                }
                Ok(false) => {
                    self.os_session = None;
                    self.chat = None; // IM requires an OS login — close it on sign-out.
                    crate::a3s_os::remove_capability_skill_dir();
                    crate::a3s_os::clear_os_env();
                    self.refresh_after_auth();
                    self.push_line(&Style::new().fg(TN_GRAY).render("  no OS login was stored"));
                }
                Err(error) => self.push_line(
                    &Style::new()
                        .fg(TN_RED)
                        .render(&format!("  logout failed: {error}")),
                ),
            }
            return None;
        }
        // `/kb <text | file | folder>` ingests raw material into the project
        // knowledge base (.a3s/kb/sources/). Deterministic file I/O off the UI
        // thread; `/okf` later compiles the sources into OKF concept pages.
        // `/ctx <query>` searches past agent sessions; `/ctx <n>` stages hit n
        // as context for the next message (ctx CLI, local SQLite index).
        if let Some(rest) = trimmed.strip_prefix("/ctx") {
            if rest.is_empty() || rest.starts_with(char::is_whitespace) {
                return self.handle_ctx_command(rest);
            }
        }
        if let Some(rest) = trimmed.strip_prefix("/kb") {
            if rest.is_empty() || rest.starts_with(char::is_whitespace) {
                let arg = rest.trim().to_string();
                self.textarea.clear();
                // Bare `/kb` opens the vault browser (superfile-style manage:
                // browse · preview · edit · x delete). With an arg it ingests.
                if arg.is_empty() {
                    let root = kbutil::kb_dir(&self.cwd);
                    if !root.is_dir() {
                        self.push_line(&Style::new().fg(TN_GRAY).render(
                            "  KB is empty — /kb <text> | /kb <file> | /kb <folder> adds to it",
                        ));
                        return None;
                    }
                    let mut ide = Ide::browse(ide_children(&root, 0), "knowledge base");
                    ide.kb_root = Some(root);
                    self.ide = Some(ide);
                    return None;
                }
                let cwd = self.cwd.clone();
                let now = chrono::Utc::now().to_rfc3339();
                return Some(cmd::cmd(move || async move {
                    let summary =
                        tokio::task::spawn_blocking(move || kbutil::add_to_kb(&cwd, &arg, &now))
                            .await
                            .unwrap_or_else(|e| format!("✗ /kb failed: {e}"));
                    Msg::KbAdded(summary)
                }));
            }
        }
        // `/im [userId]` opens the standalone OS chat page; an optional user
        // id opens/creates that DM directly. Kept OUT of the agent loop.
        if let Some(rest) = trimmed.strip_prefix("/im") {
            if rest.is_empty() || rest.starts_with(char::is_whitespace) {
                self.textarea.clear();
                let arg = rest.trim().to_string();
                let dm_with = (!arg.is_empty()).then_some(arg);
                return self.open_chat(dm_with);
            }
        }
        // `/btw <prompt>` runs a background side-thread (separate ephemeral
        // session, the main conversation as context) without disturbing the
        // current turn; its answer arrives as a side note.
        if let Some(rest) = trimmed.strip_prefix("/btw") {
            let q = rest.trim().to_string();
            self.textarea.clear();
            if q.is_empty() {
                self.push_line(&Style::new().fg(TN_GRAY).render("  usage: /btw <question>"));
                return None;
            }
            self.btw = Some((q.clone(), None));
            let agent = self.agent.clone();
            let workspace = self.cwd.clone();
            let history = self.session.history();
            return Some(cmd::cmd(move || async move {
                // Side-thread is a quick Q&A; auto-reject tool prompts (no UI).
                let conf = a3s_code_core::hitl::ConfirmationPolicy::enabled()
                    .with_timeout(500, TimeoutAction::Reject);
                let sess = match agent.session(
                    workspace,
                    Some(SessionOptions::new().with_confirmation_policy(conf)),
                ) {
                    Ok(s) => s,
                    Err(e) => return Msg::SideNote(format!("(/btw failed: {e})")),
                };
                let mut answer = String::new();
                if let Ok((mut rx, _join)) = sess.stream(&q, Some(&history)).await {
                    while let Some(ev) = rx.recv().await {
                        match ev {
                            AgentEvent::TextDelta { text } => answer.push_str(&text),
                            AgentEvent::End { text, .. } => {
                                if answer.trim().is_empty() {
                                    answer = text;
                                }
                                break;
                            }
                            _ => {}
                        }
                    }
                }
                Msg::SideNote(answer)
            }));
        }
        // `/goal [text|clear]` — a persistent goal prepended to every prompt.
        if let Some(rest) = trimmed.strip_prefix("/goal") {
            let g = rest.trim();
            self.textarea.clear();
            if g.is_empty() {
                match &self.goal {
                    Some(cur) => self.push_line(&gutter(
                        TN_CYAN,
                        &format!("🎯 goal: {cur}   (/goal clear to remove)"),
                    )),
                    None => self.push_line(
                        &Style::new()
                            .fg(TN_GRAY)
                            .render("  usage: /goal <what you're working toward>"),
                    ),
                }
            } else if g == "clear" {
                self.goal = None;
                self.goal_since = None;
                self.push_line(&Style::new().fg(TN_GRAY).render("  goal cleared"));
                return None;
            } else {
                // Set the persistent goal AND start working toward it now (the
                // goal is prepended to this and every later prompt).
                self.goal = Some(g.to_string());
                self.goal_since = Some(Instant::now());
                self.push_line(&gutter(TN_CYAN, &format!("🎯 goal set: {g}")));
                return Some(cmd::msg(Msg::Submit(g.to_string())));
            }
            return None;
        }
        // `/loop <task>` — run the task, then auto-continue until done / Esc.
        if let Some(rest) = trimmed.strip_prefix("/loop") {
            let task = rest.trim().to_string();
            self.textarea.clear();
            if task.is_empty() {
                self.push_line(
                    &Style::new().fg(TN_GRAY).render(
                        "  usage: /loop <task>   (auto-continues up to 8 turns; Esc stops)",
                    ),
                );
                return None;
            }
            self.engage_autonomy(8);
            return Some(cmd::msg(Msg::Submit(task)));
        }
        // `/sleep [focus]` — end-of-day consolidation: the `/loop` mechanism
        // drives the agent through reviewing today's work (cross-session via
        // `ctx` when installed) until a turn ends with the machine-readable
        // ```a3s-sleep report, which capture_sleep persists into long-term
        // memory (experience · preferences · knowledge). Idle-only.
        if let Some(rest) = trimmed
            .strip_prefix("/sleep")
            // Token boundary (the /login pattern): "/sleepy" is a message, not
            // this command — and must not bypass the IDLE_ONLY gate above.
            .filter(|r| r.is_empty() || r.starts_with(char::is_whitespace))
        {
            let focus = rest.trim().to_string();
            self.textarea.clear();
            self.sleep_pending = true;
            self.engage_autonomy(8);
            self.push_line(
                &Style::new()
                    .fg(TN_GRAY)
                    .render("  ☾ sleep — consolidating today's work into memory… (Esc stops)"),
            );
            let directive = panels::sleep::sleep_directive(
                &focus,
                self.ctx_ready,
                &panels::sleep::sleep_today(),
            );
            // Like `&` review: send the directive but show a short display
            // line (echoing the boilerplate as a user message is just noise).
            let display = if focus.is_empty() {
                "☾ sleep".to_string()
            } else {
                format!("☾ sleep · {focus}")
            };
            return self.start_stream_inner(directive, display, true, true, false);
        }
        // `/flow` — pick a local DAG JSON and open it in the OS workflow
        // designer (login-gated); `/flow <描述>` orchestrates a basic DAG into
        // the flows folder (local, no login needed). Token-boundary filtered
        // so "/flowx" stays a normal message and can't bypass the idle gate.
        if let Some(rest) = trimmed
            .strip_prefix("/flow")
            .filter(|r| r.is_empty() || r.starts_with(char::is_whitespace))
        {
            let description = rest.trim().to_string();
            self.textarea.clear();
            if description.is_empty() {
                if self.os_session.is_none() {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  /flow needs OS — sign in with /login first"),
                    );
                } else {
                    self.open_flow_panel();
                }
                return None;
            }
            let dir = flow_dir();
            self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                "  ⧉ drafting a flow DAG → {} (then /flow opens it in the designer)",
                dir.display()
            )));
            self.engage_autonomy(8);
            let prompt = panels::flow::flow_gen_prompt(&description, &dir.to_string_lossy());
            let display = format!("⧉ flow: {}", truncate(&description, 60));
            return self.start_stream_inner(prompt, display, true, true, false);
        }
        // Slash commands run inline in any state.
        match trimmed {
            "/exit" | "/quit" => return Some(cmd::quit()),
            "/fork" => {
                // Branch a new session from the current one: copy the persisted
                // SessionData under a fresh id, then swap the active session to it
                // (Msg::Forked). The original id keeps its state, so it stays
                // resumable — the two diverge from here. Idle-only (guarded above),
                // so the last turn is already flushed to the store.
                self.textarea.clear();
                let store = self.store.clone();
                let src = self.session_id.clone();
                let dst = new_session_id();
                return Some(cmd::cmd(move || async move {
                    match store.load(&src).await {
                        Ok(Some(mut data)) => {
                            data.id = dst.clone();
                            match store.save(&data).await {
                                Ok(()) => Msg::Forked(Ok(dst)),
                                Err(e) => Msg::Forked(Err(format!("could not save the fork: {e}"))),
                            }
                        }
                        Ok(None) => Msg::Forked(Err(
                            "nothing to fork yet — start a conversation first".into(),
                        )),
                        Err(e) => Msg::Forked(Err(format!("could not read the session: {e}"))),
                    }
                }));
            }
            "/clear" => {
                self.messages.clear();
                self.plan.clear();
                self.subagents.clear();
                self.queue.clear();
                self.completed = 0;
                self.textarea.clear();
                // A fresh conversation can't deliver the old review's report
                // or sleep consolidation, and must not inherit a staged `/ctx`
                // window or stale hits.
                self.review_pending = false;
                self.sleep_pending = false;
                self.restore_autonomy();
                self.pending_ctx = None;
                self.ctx_hits.clear();
                // Actually reset the conversation, not just the screen: swap in a
                // fresh session (new id, no history, no carried compact summary)
                // and zero the token/ctx counters. /clear is idle-only (guarded
                // above), so replacing the session is safe. Set the id first
                // (rebuild_session keys off it) and revert it if the rebuild fails
                // so id and session never desync.
                let prev_id = std::mem::replace(&mut self.session_id, new_session_id());
                let model = self.model.clone();
                match self.rebuild_session(model.as_deref()) {
                    Ok((s, _)) => {
                        self.session = Arc::new(s);
                        self.compact_summary = None;
                        self.output_tokens = 0;
                        self.last_prompt_tokens = 0;
                        self.ctx_warned_tier = 0; // fresh window: re-arm fill warnings
                    }
                    Err(_) => self.session_id = prev_id,
                }
                self.relayout();
                self.rebuild_viewport();
                return None;
            }
            "/init" => {
                // Agent-driven: analyze the repo and write AGENTS.md (auto-loaded
                // by the core, like CLAUDE.md). Guarded idle by IDLE_ONLY above.
                self.textarea.clear();
                self.messages.push(user_bubble(
                    "/init — generate AGENTS.md",
                    self.width as usize,
                ));
                self.rebuild_viewport();
                return self.start_stream(
                    "Analyze this codebase and create (or update) an AGENTS.md file at the \
                     project root. Include: a concise project overview, the exact build / test / \
                     lint / run commands, the high-level architecture and key directories, and \
                     the conventions an AI coding agent should follow. Base everything on what's \
                     actually in the repo, and write the file with your file-writing tool."
                        .to_string(),
                );
            }
            "/compact" => {
                self.textarea.clear();
                if self.state != State::Idle {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  finish the current turn before compacting"),
                    );
                    return None;
                }
                let history = self.session.history();
                if history.is_empty() {
                    self.push_line(&Style::new().fg(TN_GRAY).render("  nothing to compact yet"));
                    return None;
                }
                self.compacting = Some(Instant::now()); // progress bar + input lock
                let agent = self.agent.clone();
                let workspace = self.cwd.clone();
                // Re-compacting must subsume the PRIOR summary — it lives in the
                // system prompt, not in `history`, so without this everything
                // before the last /compact would be dropped from the new summary.
                let prompt = match &self.compact_summary {
                    Some(prev) => format!(
                        "An earlier part of this conversation was already condensed into this \
                         summary:\n\n{prev}\n\nProduce a SINGLE updated summary that fully \
                         incorporates the summary above AND the conversation history below, so a \
                         fresh session can continue seamlessly: the goal, key decisions, \
                         files/commands touched, current state, and the immediate next steps. Be \
                         thorough but compact."
                    ),
                    None => "Summarize this conversation so a fresh session can continue \
                         seamlessly: the goal, key decisions, files/commands touched, current \
                         state, and the immediate next steps. Be thorough but compact."
                        .to_string(),
                };
                return Some(cmd::cmd(move || async move {
                    let conf = a3s_code_core::hitl::ConfirmationPolicy::enabled()
                        .with_timeout(500, TimeoutAction::Reject);
                    let mut summary = String::new();
                    if let Ok(sess) = agent.session(
                        workspace,
                        Some(SessionOptions::new().with_confirmation_policy(conf)),
                    ) {
                        if let Ok((mut rx, _j)) = sess.stream(&prompt, Some(&history)).await {
                            while let Some(ev) = rx.recv().await {
                                match ev {
                                    AgentEvent::TextDelta { text } => summary.push_str(&text),
                                    AgentEvent::End { text, .. } => {
                                        if summary.trim().is_empty() {
                                            summary = text;
                                        }
                                        break;
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                    Msg::Compacted(summary)
                }));
            }
            "/help" => {
                self.textarea.clear();
                self.help_open = true;
                return None;
            }
            "/view" => {
                self.textarea.clear();
                if let Some(spec) = self.last_view.clone() {
                    self.open_remote_view(&spec);
                } else {
                    self.push_line(&Style::new().fg(TN_GRAY).render(
                        "  no OS view yet — run an OS query that returns a viewUrl, then /view",
                    ));
                }
                return None;
            }
            "/auto" => {
                self.mode = Mode::Auto;
                self.textarea.clear();
                self.rebuild_viewport();
                return None;
            }
            "/config" => {
                self.textarea.clear();
                // Resolve the config; if there's none, generate a starter so the
                // user always lands in the editor with something to edit.
                let path = find_config().map(std::path::PathBuf::from).or_else(|| {
                    let p = default_config_path()?;
                    let _ = write_template_config(&p);
                    Some(p)
                });
                match path {
                    Some(p) => self.open_config_in_ide(&p),
                    None => self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  could not locate a home directory for ~/.a3s/config.acl"),
                    ),
                }
                return None;
            }
            "/model" => {
                self.textarea.clear();
                // Signed in to OS + gateway models not fetched (or a previous fetch
                // failed → empty) → (re)fetch the OpenAI-compatible /v1/models so the
                // picker can offer the unified gateway, then open. A transient
                // gateway error thus recovers on the next /model instead of sticking
                // until restart. Otherwise open immediately.
                if let Some(s) = self.os_session.clone() {
                    let need_fetch = self.os_gateway_models.as_ref().is_none_or(|m| m.is_empty());
                    if need_fetch {
                        let (addr, token) = (s.address.clone(), s.access_token.clone());
                        return Some(cmd::cmd(move || async move {
                            Msg::OsGatewayModels(
                                crate::a3s_os::fetch_gateway_models(&addr, &token).await,
                            )
                        }));
                    }
                }
                self.open_model_menu();
                return None;
            }
            "/effort" => {
                self.textarea.clear();
                self.effort_panel = Some(self.effort);
                return None;
            }
            "/top" => {
                self.textarea.clear();
                self.top = Some(Vec::new());
                self.top_scroll = 0;
                self.top_sel = 0;
                self.top_focus = None;
                return Some(cmd::cmd(|| async { Msg::TopData(fetch_top().await) }));
            }
            "/ide" => {
                self.textarea.clear();
                let entries = ide_children(std::path::Path::new(&self.cwd), 0);
                self.ide = Some(Ide::browse(entries, "workspace"));
                return None;
            }
            "/plugin" | "/plugins" => {
                self.textarea.clear();
                if self.skills.is_empty() {
                    self.push_line(&Style::new().fg(TN_GRAY).render(
                        "  no skills/plugins found (~/.claude/skills, ~/.codex/skills, ~/.claude/plugins)",
                    ));
                } else {
                    self.plugins_panel = Some(0);
                }
                return None;
            }
            "/theme" => {
                self.textarea.clear();
                let cur = SYNTAX_THEME.load(std::sync::atomic::Ordering::Relaxed);
                self.theme_panel = Some(cur.min(THEMES.len() - 1));
                return None;
            }
            "/workflow" => {
                self.textarea.clear();
                match self.last_workflow.clone() {
                    Some(doc) => self.open_readonly_in_ide("dynamic-workflow.md", &doc),
                    None => self.push_line(&Style::new().fg(TN_GRAY).render(
                        "  no dynamic workflow yet — run an ultracode task that fans out via parallel_task",
                    )),
                }
                return None;
            }
            "/review" => {
                self.textarea.clear();
                if self.review.is_some() {
                    // A report exists: /review reopens its checklist.
                    self.review_open = true;
                } else {
                    // No report yet: pick a local repos project to review
                    // (the `&` flow without the clone; no login needed).
                    self.open_repo_picker(panels::repos::RepoAction::Review);
                }
                return None;
            }
            // `/deploy` — login-gated: pick a repos project → Agentic CI/CD →
            // auto-configure its OS gateway access address.
            "/deploy" => {
                self.textarea.clear();
                if self.os_session.is_none() {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  /deploy needs OS — sign in with /login first"),
                    );
                } else {
                    self.open_repo_picker(panels::repos::RepoAction::Deploy);
                }
                return None;
            }
            // `/run` — login-gated: pick a repos project → quick dev-mode debug
            // run on the A3S Runtime → report its access address.
            "/run" => {
                self.textarea.clear();
                if self.os_session.is_none() {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  /run needs OS — sign in with /login first"),
                    );
                } else {
                    self.open_repo_picker(panels::repos::RepoAction::Run);
                }
                return None;
            }
            // `/evolve` — login-gated: pick a repos project → set an improvement
            // goal → multi-round auto-improving development session.
            "/evolve" => {
                self.textarea.clear();
                if self.os_session.is_none() {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  /evolve needs OS — sign in with /login first"),
                    );
                } else {
                    self.open_evolve_panel();
                }
                return None;
            }
            "/output" => {
                self.textarea.clear();
                match self.format_tool_log() {
                    Some(content) => self.open_readonly_in_ide("tool-calls.txt", &content),
                    None => self.push_line(
                        &Style::new()
                            .fg(TN_GRAY)
                            .render("  no tool calls yet this session"),
                    ),
                }
                return None;
            }
            "/reload" => {
                self.textarea.clear();
                // Hot-reload: re-discover skill dirs, refresh the UI catalog,
                // and rebuild the session so the core skill registry and
                // next Claude/system prompt see the same skills.
                let dirs = agent_skill_dirs(&self.cwd);
                self.skills = load_skills(&dirs);
                self.skill_count = count_skill_files(&dirs);
                let model = self.model.clone();
                match self.rebuild_session(model.as_deref()) {
                    Ok((session, _)) => {
                        self.session = Arc::new(session);
                        self.push_line(&Style::new().fg(TN_GREEN).render(&format!(
                            "  ↻ reloaded — {} skills available",
                            self.skills.len()
                        )));
                    }
                    Err(error) => {
                        self.push_line(
                            &Style::new()
                                .fg(TN_RED)
                                .render(&format!("  reload failed: {error}")),
                        );
                    }
                }
                return None;
            }
            "/update" => {
                self.textarea.clear();
                self.updating = Some(Instant::now()); // "checking…" + input lock
                self.relayout();
                return Some(cmd::cmd(|| async {
                    // Quick version check only; the actual upgrade runs in the
                    // shell after the TUI exits (run()), so brew's/curl's own
                    // progress shows and the restart picks up the new binary.
                    let latest = tokio::task::spawn_blocking(crate::update::fetch_latest)
                        .await
                        .ok()
                        .flatten();
                    Msg::UpdatePlan(latest)
                }));
            }
            "/git" => {
                self.textarea.clear();
                self.git = Some(Git {
                    files: Vec::new(),
                    sel: 0,
                    diff: Vec::new(),
                    diff_scroll: 0,
                    log: Vec::new(),
                    log_sel: 0,
                    view: GitView::Status,
                    commit_input: None,
                    note: "loading…".into(),
                });
                let repo = self.cwd.clone();
                return Some(cmd::cmd(move || async move {
                    let (files, log) = git_status_log(repo).await;
                    Msg::GitStatus(files, log)
                }));
            }
            "/memory" => {
                self.textarea.clear();
                // Open immediately ("loading…"); parse the store index off the UI
                // thread (it can be multi-MB) so the panel never janks on open.
                let dir = memory_dir();
                self.memory = Some(MemPanel {
                    entries: Vec::new(),
                    sel: 0,
                    detail: memutil::MemDetail::default(),
                    detail_scroll: 0,
                    dir: dir.clone(),
                    note: "loading…".into(),
                });
                return Some(cmd::cmd(move || async move {
                    let entries = tokio::task::spawn_blocking(move || memutil::load_timeline(&dir))
                        .await
                        .unwrap_or_default();
                    Msg::MemoryLoaded(entries)
                }));
            }
            "/relay" => {
                self.textarea.clear();
                // Open immediately (tabs show right away); scan off the UI thread
                // so reading large transcripts never freezes the panel.
                self.relay.clear();
                self.relay_menu = Some(0);
                self.relay_tab = 0;
                let cwd = self.cwd.clone();
                return Some(cmd::cmd(move || async move {
                    let sessions = tokio::task::spawn_blocking(move || scan_relay(&cwd))
                        .await
                        .unwrap_or_default();
                    Msg::RelayData(sessions)
                }));
            }
            _ => {}
        }

        self.history.push(trimmed.to_string());
        self.history_pos = None;
        // Show the user message in a background bubble, then run now (if idle)
        // or queue it (if the agent is busy).
        self.messages
            .push(user_bubble(trimmed, self.width as usize));
        self.textarea.clear();
        // One-shot `/ctx <n>` context: attach the staged transcript to THIS
        // genuine typed message only (never a `/loop` "Continue." re-entry),
        // invisibly — the display bubble above stays clean. Travels with the
        // message whether it runs now or is queued.
        let loop_cont = std::mem::take(&mut self.loop_continuation);
        let prompt = match (loop_cont, self.pending_ctx.take()) {
            (false, Some(c)) => format!("{c}\n\n{trimmed}"),
            _ => trimmed.to_string(),
        };
        if self.state == State::Idle {
            self.start_stream(prompt)
        } else {
            self.seq += 1;
            self.queue.push(Queued {
                prio: 1,
                seq: self.seq,
                text: prompt,
            });
            self.push_line(&Style::new().fg(TN_GRAY).render("    ⋯ queued"));
            self.relayout();
            None
        }
    }

    /// Begin streaming a prompt (the user message must already be on screen).
    /// Grab a clipboard image, preview it inline, and queue it for the next send.
    fn paste_clipboard_image(&mut self) {
        let dest =
            std::env::temp_dir().join(format!("a3s-paste-{}.png", self.pending_images.len()));
        if !clipboard_image_to(&dest) {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  no image in clipboard (Ctrl+V pastes a copied/screenshot image)"),
            );
            return;
        }
        let Ok(bytes) = std::fs::read(&dest) else {
            return;
        };
        self.messages.push(gutter(
            ACCENT,
            "📎 pasted image (sends with your next message):",
        ));
        // Render narrower than the viewport so half-block rows never wrap (a
        // wrapped row splits the picture and garbles it). Indent to align.
        let cols = (self.width as usize).saturating_sub(PAD + 2).min(72);
        if let Some(lines) = render_image_file(&dest, cols, 16) {
            for l in lines {
                self.messages.push(format!("{}{l}", " ".repeat(PAD)));
            }
        }
        self.rebuild_viewport();
        self.pending_images
            .push(a3s_code_core::llm::Attachment::png(bytes));
    }

    fn start_stream(&mut self, prompt: String) -> Option<Cmd<Msg>> {
        self.start_stream_inner(prompt.clone(), prompt, true, true, false)
    }

    fn start_ultracode_synthesis(
        &mut self,
        prompt: String,
        display_task: String,
    ) -> Option<Cmd<Msg>> {
        self.ultracode_synthesis_used = true;
        self.push_line(&Style::new().fg(TN_GRAY).render("  ⇉ synthesizing results…"));
        self.start_stream_inner(prompt, display_task, false, false, true)
    }

    fn start_stream_inner(
        &mut self,
        prompt: String,
        display_task: String,
        clear_turn_artifacts: bool,
        include_attachments: bool,
        synthesis: bool,
    ) -> Option<Cmd<Msg>> {
        self.streaming.clear();
        self.got_delta = false; // track if this turn streamed any text deltas
        self.turn_text.clear();
        self.turn_had_agent_activity = false;
        self.turn_text_after_activity = false;
        self.ultracode_synthesis_inflight = synthesis;
        if !synthesis {
            self.ultracode_synthesis_used = false;
        }
        self.last_paint = None; // first delta of the turn paints immediately
        self.viewport.set_auto_scroll(true); // sending a message jumps to latest
        if clear_turn_artifacts {
            self.plan.clear(); // fresh plan per user turn; planning events refill it
            self.subagents.clear(); // keep completed agents visible until the next user turn
        }
        self.running_task = Some(display_task);
        self.state = State::Streaming;
        self.relayout();
        self.stream_started = Some(Instant::now());
        self.spinner.start();
        self.rebuild_viewport();
        let session = self.session.clone();
        let atts = if include_attachments {
            std::mem::take(&mut self.pending_images)
        } else {
            Vec::new()
        };
        // Keep the agent aligned with the standing goal (display stays clean).
        let prompt = match &self.goal {
            Some(g) => format!("[Ongoing goal: {g}]\n\n{prompt}"),
            None => prompt,
        };
        // (A `/ctx <n>` staged transcript window is attached upstream, only to a
        // genuine typed user message — see on_submit — never to a `/loop`, `&`,
        // `?`, or synthesis continuation.)
        // ultracode no longer rewrites the user turn. Whether a turn plans and
        // fans out is decided by the core's message-gated planning
        // (PlanningMode::Auto) plus the `parallel_task` tool description — not an
        // unconditional per-turn imperative, which made even "hi" trigger a plan
        // and workspace exploration.
        Some(cmd::batch(vec![
            cmd::cmd(move || async move {
                let res = if atts.is_empty() {
                    session.stream(prompt.as_str(), None).await
                } else {
                    session
                        .stream_with_attachments(prompt.as_str(), &atts, None)
                        .await
                };
                match res {
                    Ok((rx, _join)) => Msg::StreamStarted(Arc::new(Mutex::new(rx))),
                    Err(e) => Msg::StreamError(e.to_string()),
                }
            }),
            spinner_tick(),
        ]))
    }

    /// Pop the next queued message and start streaming it, if any.
    fn drain_queue(&mut self) -> Option<Cmd<Msg>> {
        let next = self.queue.pop()?;
        self.start_stream(next.text)
    }

    /// Shared turn-completion: count the turn, run any ultracode synthesis, go
    /// idle, then either continue a `/loop` or drain the next queued message.
    /// Called from BOTH the normal `AgentEvent::End` arm (the happy path, which
    /// returns without re-pumping so `StreamEnded` never fires) and the
    /// `StreamEnded` channel-closed arm — previously this lived only in
    /// `StreamEnded`, so on success the queue never drained and `/loop` ran once.
    fn complete_turn(&mut self) -> Option<Cmd<Msg>> {
        if self.state == State::Streaming {
            self.completed += 1;
        }
        let synthesis = self.prepare_ultracode_synthesis();
        self.finish();
        if let Some((prompt, display_task)) = synthesis {
            return self.start_ultracode_synthesis(prompt, display_task);
        }
        // /loop: auto-continue until the agent says DONE, the cap is hit, or Esc.
        // Queued user messages take priority.
        if self.loop_remaining > 0 && self.queue.is_empty() {
            self.loop_remaining -= 1;
            let n = self.loop_remaining;
            self.push_line(
                &Style::new()
                    .fg(TN_GRAY)
                    .render(&format!("  ↻ loop ({n} left · Esc to stop)")),
            );
            // Mark the continuation as machine-driven so on_submit doesn't
            // attach a staged `/ctx` window to it.
            self.loop_continuation = true;
            return Some(cmd::msg(Msg::Submit(
                "Continue. If the task is fully complete, reply DONE and stop.".to_string(),
            )));
        }
        // The loop is drained (or was never armed): an autonomous run that
        // auto-switched to auto mode is over — restore the user's mode.
        if self.loop_remaining == 0 {
            self.restore_autonomy();
        }
        // Run the next queued message (submitted while busy), if any.
        self.drain_queue()
    }

    /// An autonomous directive run is starting (/sleep, reviews, /deploy,
    /// /run, /flow drafts, /evolve, /loop): switch to auto-approve so tool
    /// prompts can't stall it, and arm the loop budget that re-prompts until
    /// the deliverable lands. The prior mode is restored when the run ends
    /// (loop drained, interrupt, error, or /clear). A user already in auto
    /// mode keeps it — nothing is remembered or restored.
    fn engage_autonomy(&mut self, budget: usize) {
        self.loop_remaining = self.loop_remaining.max(budget);
        if self.mode != Mode::Auto {
            self.autonomy_restore = Some(self.mode);
            self.mode = Mode::Auto;
            self.push_line(&Style::new().fg(TN_GRAY).render(
                "  ⏵⏵ auto mode engaged for this task — restores when it completes (Esc stops)",
            ));
        }
    }

    /// Restore the pre-autonomy mode (no-op when nothing was auto-switched).
    fn restore_autonomy(&mut self) {
        if let Some(prev) = self.autonomy_restore.take() {
            self.mode = prev;
            self.push_line(
                &Style::new()
                    .fg(TN_GRAY)
                    .render("  ⏵ autonomous task ended — auto mode restored to your previous mode"),
            );
        }
    }

    fn on_agent_event(&mut self, event: AgentEvent) -> Option<Cmd<Msg>> {
        // After an interrupt, rx is cleared — ignore any late buffered events.
        self.rx.as_ref()?;
        match event {
            AgentEvent::TextDelta { text } => {
                self.mark_assistant_text(&text);
                self.got_delta = true;
                self.turn_text.push_str(&text);
                self.streaming.push(&text);
                self.update_viewport_with_stream();
            }
            AgentEvent::ReasoningDelta { text } => {
                self.thinking.push_str(&text);
                self.update_viewport_with_stream();
            }
            AgentEvent::ToolStart { name, .. } => {
                // Finalize any assistant text; show the tool live with a blinking
                // dot. The final "• action / └ result" lands on ToolEnd.
                self.mark_agent_activity();
                self.finalize_streaming();
                self.tool_args.clear();
                self.tool_output.clear();
                self.active_tools += 1;
                self.running_tool = Some(name);
            }
            AgentEvent::ToolInputDelta { delta } => {
                self.tool_args.push_str(&delta);
            }
            AgentEvent::ToolOutputDelta { delta, .. } => {
                self.tool_output.push_str(&delta);
                self.update_viewport_with_stream();
            }
            AgentEvent::ToolEnd {
                name,
                output,
                exit_code,
                metadata,
                ..
            } => {
                self.mark_agent_activity();
                self.running_tool = None;
                self.active_tools = self.active_tools.saturating_sub(1);
                let args: Option<serde_json::Value> = serde_json::from_str(&self.tool_args).ok();
                self.push_line(&render_tool_end(
                    &name,
                    exit_code,
                    &output,
                    metadata.as_ref(),
                    args.as_ref(),
                    self.width as usize,
                ));
                self.capture_workflow(&name, args.as_ref());
                // RemoteUI: a OS viewUrl in the tool output is openable. Remember
                // it for `/view`, and if the API marked it embeddable (sized popup),
                // open it now in the native a3s-webview window (auth via $A3S_OS_TOKEN).
                // The progressive API returns a RELATIVE view url; complete it
                // against the signed-in OS origin (the TUI is "the edge").
                let os_origin = self
                    .os_session
                    .as_ref()
                    .map(|s| crate::a3s_os::os_origin(&s.address));
                if let Some(spec) = remote_ui::find_view_url(&output, os_origin.as_deref()) {
                    // RemoteUI is user-triggered — never auto-open. Remember the
                    // view for `/view`, and surface a clickable "查看视图" line
                    // ourselves (deterministic) rather than trusting the model to
                    // print the marker — weaker models often forget it or jq the
                    // `.view` object away. Only emit for a NEW view (no dupes).
                    let is_new = self.last_view.as_ref() != Some(&spec);
                    self.last_view = Some(spec);
                    if is_new {
                        self.push_line(&gutter(
                            TN_CYAN,
                            &format!("🔗 {VIEW_BUTTON_MARKER}  (click or /view to open)"),
                        ));
                    }
                }
                // Retain the call for `/output`. Cap each output so a huge build
                // log can't bloat the in-memory record.
                // ponytail: 8 KB/call cap; the transcript already holds the full text
                let logged = if output.len() > 8192 {
                    let mut s: String = output.chars().take(8000).collect();
                    s.push_str("\n… (output truncated — see transcript)");
                    s
                } else {
                    output
                };
                self.tool_log.push(ToolCallRecord {
                    name,
                    args,
                    output: logged,
                    exit_code,
                });
                self.tool_args.clear();
                self.tool_output.clear();
            }
            // Parallel/child task lifecycle (parallel_task, task) — show each
            // sub-task starting, its progress, and how it finished.
            AgentEvent::SubagentStart {
                task_id,
                agent,
                description,
                ..
            } => {
                self.mark_agent_activity();
                self.finalize_streaming();
                self.active_agents += 1;
                // Track it in the live bottom panel instead of a transcript line.
                self.subagents.push(SubAgent {
                    task_id,
                    agent,
                    description,
                    started: Instant::now(),
                    ended: None,
                    tokens: 0,
                    done: false,
                    success: None,
                });
                self.relayout();
            }
            AgentEvent::SubagentProgress {
                task_id, metadata, ..
            } => {
                self.mark_agent_activity();
                // Per-child OUTPUT tokens for the panel's `↓`. Each child turn-end
                // reports that turn's completion_tokens once, so SUM them across
                // turns (tool-event progress carries no usage, so it won't add).
                // The old code took max(total_tokens), i.e. the largest single
                // turn's prompt+completion ≈ the child's context size, not output.
                let toks = metadata
                    .get("completion_tokens")
                    .or_else(|| metadata.pointer("/usage/completion_tokens"))
                    .and_then(|v| v.as_u64());
                if let Some(s) = self.subagents.iter_mut().find(|s| s.task_id == task_id) {
                    if let Some(t) = toks {
                        s.tokens += t;
                    }
                }
            }
            AgentEvent::SubagentEnd {
                task_id,
                agent,
                output,
                success,
                ..
            } => {
                self.mark_agent_activity();
                self.active_agents = self.active_agents.saturating_sub(1);
                if let Some(s) = self.subagents.iter_mut().find(|s| s.task_id == task_id) {
                    s.done = true;
                    s.success = Some(success);
                    s.ended = Some(Instant::now());
                }
                self.relayout();
                let (mark, color) = if success {
                    ("", TN_GREEN)
                } else {
                    ("", TN_RED)
                };
                let snippet = output.lines().next().unwrap_or("").trim();
                let snippet = truncate(snippet, self.width.saturating_sub(20) as usize);
                self.push_line(&Style::new().fg(color).render(&format!(
                    "{mark} {agent}{}",
                    if snippet.is_empty() {
                        String::new()
                    } else {
                        format!(" · {snippet}")
                    }
                )));
            }
            AgentEvent::ContextCompacted {
                before_messages,
                after_messages,
                percent_before,
                ..
            } => {
                // The core auto-compacted mid-turn (pruned tool outputs + summarized
                // old messages). The next turn's prompt reflects the smaller context,
                // so ctx% self-corrects on the following End — just surface a note.
                // The core emits this whenever the threshold is crossed, even
                // when nothing could shrink (short histories can't summarize);
                // a note per round would spam "auto-compacted" while nothing
                // happened. Only surface real reductions — prune-only rounds
                // (equal count, smaller content) show up via ctx% instead.
                if after_messages < before_messages {
                    // `percent_before` is relative to the core's fixed 200k
                    // window; rescale to the model's REAL window to match ctx%.
                    let pct = if self.context_limit > 0 {
                        (percent_before * CORE_MAX_CONTEXT_TOKENS * 100.0
                            / self.context_limit as f32)
                            .round()
                            .min(100.0) as u32
                    } else {
                        (percent_before * 100.0).round() as u32
                    };
                    self.push_line(&Style::new().fg(TN_GRAY).italic().render(&format!(
                        "  ✦ context auto-compacted at {pct}% · {before_messages}{after_messages} messages"
                    )));
                }
            }
            AgentEvent::ConfirmationRequired {
                tool_id,
                tool_name,
                args,
                ..
            } => {
                if self.mode.auto_approves(&tool_name) {
                    // Silent: the mode indicator already shows auto-approve is on;
                    // a line per tool is just noise. Do NOT start another
                    // spinner_tick here — the turn's tick loop is already running
                    // (state stays Streaming through auto-approval). Stacking one
                    // per auto-approved tool made the spinner advance several
                    // frames per 80ms = the "时快时慢" speed-up.
                    let session = self.session.clone();
                    return Some(cmd::cmd(move || async move {
                        let _ = session.confirm_tool_use(&tool_id, true, None).await;
                        Msg::Resume
                    }));
                }
                // Claude-style: no "requests:" transcript line — the prompt on
                // the activity line shows the tool; after approval the tool just
                // runs and its result lands via ToolEnd.
                self.state = State::Awaiting;
                self.approval_sel = 0;
                let label = tool_label(&tool_name, Some(&args));
                self.pending_tool = Some((tool_id, label));
                return None; // wait for the user; do not pump
            }
            // Live context fill: every LLM round-trip reports its prompt size,
            // so ctx% (and the fill warnings) track DURING long multi-tool
            // turns instead of freezing until End.
            AgentEvent::TurnEnd { usage, .. } => {
                if usage.prompt_tokens > 0 {
                    self.last_prompt_tokens = usage.prompt_tokens;
                    self.maybe_warn_ctx();
                }
            }
            AgentEvent::End {
                text, usage, meta, ..
            } => {
                // /loop: stop once the agent signals completion (the word DONE).
                // Not during /sleep: its completion signal is the a3s-sleep
                // report itself, and consolidation narration ("what was done
                // today") would false-trigger this and kill the run early.
                if self.loop_remaining > 0 && !self.sleep_pending {
                    let r = if text.is_empty() {
                        self.streaming.raw_content().to_string()
                    } else {
                        text.clone()
                    };
                    if r.split(|c: char| !c.is_alphabetic())
                        .any(|w| w.eq_ignore_ascii_case("done"))
                    {
                        self.loop_remaining = 0;
                    }
                }
                // `&` review scans the WHOLE turn's text: with a delta-only
                // provider a tool call after the report would have cleared the
                // live buffer, losing a fully delivered report.
                let review_text = if text.is_empty() {
                    self.turn_text.clone()
                } else {
                    text.clone()
                };
                // Only fall back to End.text when the provider never streamed
                // deltas this turn. Using the live buffer's emptiness here dups
                // text: a mid-turn finalize (e.g. a tool call) empties the buffer,
                // so End.text (the full message) would be appended a second time.
                if !self.got_delta && !text.is_empty() {
                    self.mark_assistant_text(&text);
                    self.streaming.push(&text);
                }
                self.finalize_streaming();
                // `&` code review: a ```a3s-review report in the final message
                // ends the review loop and opens the issue checklist.
                self.capture_review(&review_text);
                // `/sleep`: an ```a3s-sleep report ends the consolidation loop
                // and persists the distilled memories (async, batched below).
                let sleep_save = self.capture_sleep(&review_text);
                self.disarm_sleep_if_over(sleep_save.is_some());
                // `↓` counts OUTPUT (generated) tokens. Summing total_tokens per
                // turn re-counts the whole context every turn (the prompt is
                // re-sent each round) and balloons far past what was generated.
                // completion_tokens is the output; fall back to total-prompt if a
                // provider omits it.
                self.output_tokens += if usage.completion_tokens > 0 {
                    usage.completion_tokens
                } else {
                    usage.total_tokens.saturating_sub(usage.prompt_tokens)
                };
                // ctx% is NOT updated here: End.usage.prompt_tokens is the
                // per-turn SUM of every round's prompt (the context is re-sent
                // each round, same ballooning as above), not the current
                // context size — a multi-round turn would read rounds× too
                // high and fire false fill warnings. The TurnEnd arm already
                // recorded the real per-round size, final round included.
                if self.model.is_none() {
                    self.model = meta.and_then(|m| m.response_model.or(m.request_model));
                }
                // Count the turn, idle, then continue /loop or drain the queue.
                // A captured sleep report's save runs alongside.
                return match (sleep_save, self.complete_turn()) {
                    (Some(save), Some(next)) => Some(cmd::batch(vec![save, next])),
                    (save, next) => save.or(next),
                };
            }
            AgentEvent::Error { message } => {
                self.push_line(
                    &Style::new()
                        .fg(TN_RED)
                        .render(&format!("  error: {message}")),
                );
                self.loop_remaining = 0; // a failed turn stops the /loop
                self.review_pending = false; // and abandons a `&` review
                self.sleep_pending = false; // and a `/sleep` consolidation
                self.restore_autonomy();
                self.finish();
                // Don't strand messages queued while this turn was running.
                return self.drain_queue();
            }
            // Planning mode: capture the plan and live task-status updates for
            // the pinned TODO panel above the input.
            AgentEvent::PlanningEnd { plan, .. } => {
                self.mark_agent_activity();
                self.set_plan(&plan.steps);
            }
            AgentEvent::TaskUpdated { tasks, .. } => {
                self.mark_agent_activity();
                self.set_plan(&tasks);
            }
            // Per-step lifecycle also drives the panel, in case TaskUpdated is
            // sparse: a step turns ▶ on start and ✔/✗/⊘ on completion.
            AgentEvent::StepStart { step_id, .. } => {
                self.mark_agent_activity();
                self.set_task_status(&step_id, '', TN_YELLOW);
            }
            AgentEvent::StepEnd {
                step_id, status, ..
            } => {
                self.mark_agent_activity();
                let (g, c) = task_status_style(status);
                self.set_task_status(&step_id, g, c);
            }
            // TurnStart, ToolInputDelta, memory, confirmation echoes,
            // etc. — not surfaced in this MVP.
            _ => {}
        }
        // Keep draining the stream.
        self.rx.clone().map(pump)
    }

    /// One-shot transcript warning as the context fills: a heads-up at 70%
    /// and a red alert at 85% (the auto-compact point). Called wherever
    /// `last_prompt_tokens` updates; the latch re-arms when usage drops.
    fn maybe_warn_ctx(&mut self) {
        if self.context_limit == 0 {
            return;
        }
        let pct = (self.last_prompt_tokens * 100 / self.context_limit as usize).min(100);
        let (latch, warn) = ctx_warn_tier(pct, self.ctx_warned_tier);
        self.ctx_warned_tier = latch;
        if warn.is_some() {
            // push_line rebuilds the viewport from `messages` only, which
            // would hide a still-streaming round's text (invisible through a
            // whole approval wait if this round ends in a gated tool call).
            // Finalize it into the transcript first — same as ToolStart does.
            self.finalize_streaming();
        }
        match warn {
            Some(85) => self.push_line(&Style::new().fg(TN_RED).render(&format!(
                "  ✦ context {pct}% full — auto-compacting soon; /compact to summarize now"
            ))),
            Some(_) => self.push_line(&Style::new().fg(TN_YELLOW).render(&format!(
                "  ✦ context {pct}% full — auto-compacts near 85%; /compact to summarize early"
            ))),
            None => {}
        }
    }

    fn mark_agent_activity(&mut self) {
        self.turn_had_agent_activity = true;
        self.turn_text_after_activity = false;
    }

    fn mark_assistant_text(&mut self, text: &str) {
        if !text.trim().is_empty() {
            self.turn_text_after_activity = true;
        }
    }

    fn prepare_ultracode_synthesis(&self) -> Option<(String, String)> {
        if !needs_synthesis(
            self.ultracode_synthesis_inflight,
            self.ultracode_synthesis_used,
            self.turn_had_agent_activity,
            self.turn_text_after_activity,
        ) {
            return None;
        }

        let user_task = self
            .running_task
            .as_deref()
            .filter(|task| !task.trim().is_empty())
            .unwrap_or("the previous task");
        let mut prompt = format!(
            "[synthesis]\n\
             The previous turn completed planning/tool/subagent work \
             but stopped without a final user-facing answer.\n\n\
             Original user task:\n{user_task}\n\n\
             Write the final answer now in the user's language. Synthesize the \
             completed work into a useful response. Do not call tools or start \
             more subagents unless it is strictly necessary to avoid an incorrect \
             answer. If a child run produced no text output, summarize the \
             available plan/status instead of exposing raw task metadata.\n"
        );

        if !self.plan.is_empty() {
            prompt.push_str("\nPlan/status:\n");
            for (_, text, glyph, _) in &self.plan {
                let status = match glyph {
                    '' => "done",
                    '' => "in progress",
                    '' => "failed",
                    _ => "pending",
                };
                prompt.push_str(&format!("- [{status}] {text}\n"));
            }
        }

        if !self.subagents.is_empty() {
            prompt.push_str("\nSubagents:\n");
            for agent in &self.subagents {
                let status = match agent.success {
                    Some(true) => "done",
                    Some(false) => "failed",
                    None if agent.done => "done",
                    None => "unknown",
                };
                prompt.push_str(&format!(
                    "- [{status}] {}: {}\n",
                    agent.agent, agent.description
                ));
            }
        }

        if let Some(workflow) = &self.last_workflow {
            prompt.push_str("\nLatest workflow artifact excerpt:\n");
            prompt.push_str(&truncate(workflow, 4000));
            prompt.push('\n');
        }

        Some((prompt, user_task.to_string()))
    }

    fn finalize_streaming(&mut self) {
        let rendered = self.streaming.view();
        if !rendered.trim().is_empty() {
            let block = gutter(TN_GREEN, &rendered);
            // Safety net against duplicate output: skip if this exact block
            // already appeared in the last few messages (a re-finalize, or an
            // agent that re-emits earlier text — e.g. its preamble after a tool).
            let recent_dup = self.messages.iter().rev().take(4).any(|m| m == &block);
            if !recent_dup {
                self.messages.push(block);
            }
        }
        self.streaming.clear();
        self.thinking.clear();
        self.rebuild_viewport();
    }

    fn finish(&mut self) {
        self.state = State::Idle;
        self.running_task = None;
        self.active_tools = 0;
        self.active_agents = 0;
        // Clear the parallel-subagent panel when the turn ends — it's a live
        // progress tracker, so leaving completed agents pinned at the bottom once
        // the work is done just clutters the idle screen.
        self.subagents.clear();
        self.ultracode_synthesis_inflight = false;
        self.relayout();
        self.stream_started = None;
        self.spinner.stop();
        self.rx = None;
        self.rebuild_viewport();
    }

    fn push_line(&mut self, line: &str) {
        self.messages.push(line.to_string());
        self.rebuild_viewport();
    }

    /// Open a OS viewUrl in the native `a3s-webview` window. Silent on success
    /// (the window appearing is feedback enough); only a missing helper binary
    /// leaves a transcript hint.
    fn open_remote_view(&mut self, spec: &remote_ui::ViewSpec) {
        if remote_ui::open_window(spec).is_err() {
            // No helper binary (not shipped on Linux/Windows, or not installed):
            // print the url so the user can open it in a browser themselves.
            self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                "  🔗 open in your browser: {} (install a3s-webview for an in-app window, macOS)",
                spec.url
            )));
        }
    }

    /// Skill dirs for the session: the discovered Claude/Codex dirs plus the
    /// login-gated built-in OS `a3s-os-capabilities` skill when signed in.
    pub(crate) fn skill_dirs(&self) -> Vec<std::path::PathBuf> {
        let mut dirs = agent_skill_dirs(&self.cwd);
        // Always-available built-in skills (the `okf` LLM-wiki / knowledge compiler).
        if let Some(d) = ensure_builtin_skills_dir() {
            dirs.push(d);
        }
        if self.os_session.is_some() {
            if let Some(cfg) = &self.os_config {
                if let Some(d) = crate::a3s_os::ensure_capability_skill_dir(cfg) {
                    dirs.push(d);
                }
            }
        }
        dirs
    }

    /// After an OS login/logout, rebuild the session so the login-gated
    /// skill loads/unloads immediately, and refresh the start-screen skill list.
    fn refresh_after_auth(&mut self) {
        if self.state == State::Idle {
            if let Ok((s, _)) = self.rebuild_session(self.model.as_deref()) {
                self.session = Arc::new(s);
            }
        }
        // Login/logout flips whether the A3S Runtime `runtime` tool is available.
        self.sync_runtime_tool();
        let dirs = self.skill_dirs();
        self.skill_count = count_skill_files(&dirs);
        self.skills = load_skills(&dirs);
    }

    /// Register the A3S Runtime `runtime` offload tool while signed in to OS,
    /// unregister it while signed out — so it only appears in the model's toolset
    /// after login. Called after every auth change (login/logout), once the
    /// session has been (re)built.
    fn sync_runtime_tool(&self) {
        match self.os_session.as_ref() {
            Some(s) => self.session.register_dynamic_tool(std::sync::Arc::new(
                crate::runtime_tool::RuntimeTool::new(s),
            )),
            None => self.session.unregister_dynamic_tool("runtime"),
        }
    }

    /// Open `path` directly in the built-in IDE editor (tree rooted at its
    /// directory, file loaded, editor focused). Used by `/config` + first launch.
    fn open_config_in_ide(&mut self, path: &std::path::Path) {
        let dir = path.parent().unwrap_or(std::path::Path::new("."));
        let lines: Vec<String> = std::fs::read_to_string(path)
            .unwrap_or_default()
            .replace('\t', "    ")
            .lines()
            .map(String::from)
            .collect();
        let mut ide = Ide::browse(ide_children(dir, 0), "config");
        ide.file = Some(IdeFile::new(path.to_path_buf(), lines, false, false));
        ide.focus_editor = true;
        self.ide = Some(ide);
    }

    /// Capture a `parallel_task`/`task` dispatch as a dynamic-workflow artifact:
    /// a readable plan of the fanned-out subtasks. Stored for `/workflow` and
    /// announced with a collapsed one-line message in the transcript.
    fn capture_workflow(&mut self, name: &str, args: Option<&serde_json::Value>) {
        let Some((doc, label)) = workflow_doc_for_tool(name, args) else {
            return;
        };
        self.last_workflow = Some(doc);
        // Collapsed indicator; the full artifact opens read-only via /workflow.
        self.push_line(&Style::new().fg(ACCENT).render(&format!("{label}")));
    }

    /// Open read-only text content in the built-in IDE (used by `/workflow` to
    /// show the dynamic-workflow artifact). Editor-focused for scroll/nav, but
    /// `readonly` blocks edits and Ctrl+S.
    fn open_readonly_in_ide(&mut self, title: &str, content: &str) {
        let lines: Vec<String> = content.lines().map(String::from).collect();
        let mut ide = Ide::browse(
            ide_children(std::path::Path::new(&self.cwd), 0),
            "workspace",
        );
        ide.file = Some(IdeFile::new(
            std::path::PathBuf::from(title),
            lines,
            false,
            true,
        ));
        ide.focus_editor = true;
        ide.flash = Some("read-only".to_string());
        self.ide = Some(ide);
    }

    /// Format every retained tool call for the `/output` viewer: a header line
    /// per call (index · name · status) followed by its args and output. Returns
    /// None when nothing has run yet.
    fn format_tool_log(&self) -> Option<String> {
        format_tool_log_records(&self.tool_log)
    }

    /// Move through prompt history and load the entry into the input. Going
    /// forward past the newest entry returns to a fresh, empty input.
    fn history_recall(&mut self, up: bool) {
        let pos = match (self.history_pos, up) {
            (None, true) => self.history.len().saturating_sub(1),
            (None, false) => return,
            (Some(i), true) => i.saturating_sub(1),
            (Some(i), false) => i + 1,
        };
        if pos >= self.history.len() {
            self.history_pos = None;
            self.textarea.clear();
        } else {
            self.history_pos = Some(pos);
            self.textarea.set_value(&self.history[pos]);
        }
    }

    fn update_viewport_with_stream(&mut self) {
        // Throttle this O(n) rebuild to ~30fps. A fast stream emits deltas far
        // faster than that; rebuilding the whole transcript each time starves
        // the animation ticks on the single-threaded loop (the "时快时慢" jitter).
        if let Some(t) = self.last_paint {
            if t.elapsed() < Duration::from_millis(33) {
                return;
            }
        }
        self.last_paint = Some(Instant::now());
        let mut blocks: Vec<String> = self.messages.clone();
        if !self.thinking.trim().is_empty() {
            // Lay out reasoning like every other message: pre-wrap to the content
            // width and put the margin + "💭" OUTSIDE the dim style, one styled
            // line at a time. The old `Style::render(&indent(…))` shoved the whole
            // paragraph in as one line whose leading spaces sat *inside* the ANSI
            // escape, so the viewport re-wrapped it to the screen edge (margins
            // didn't line up) with uneven spacing. "💭 " is 3 display columns;
            // continuation lines indent to match.
            let dim = Style::new().fg(TN_GRAY).italic();
            let margin = " ".repeat(PAD);
            let avail = (self.width as usize).saturating_sub(PAD + 3).max(8);
            let body = wrap_words(self.thinking.trim(), avail)
                .iter()
                .enumerate()
                .map(|(i, line)| {
                    let lead = if i == 0 { "💭 " } else { "   " };
                    format!("{margin}{}", dim.render(&format!("{lead}{line}")))
                })
                .collect::<Vec<_>>()
                .join("\n");
            blocks.push(body);
        }
        let rendered = self.streaming.view();
        if !rendered.is_empty() {
            blocks.push(gutter(TN_GREEN, &rendered));
        }
        // Currently-executing tool: "• Running <cmd>…" with a blinking bullet.
        if let Some(name) = &self.running_tool {
            let args: Option<serde_json::Value> = serde_json::from_str(&self.tool_args).ok();
            let verb = match name.as_str() {
                "bash" | "shell" | "run" | "exec" => "Running",
                _ => tool_verb(name),
            };
            let arg = args.as_ref().and_then(arg_summary).unwrap_or_default();
            let on = self.blink_tick % 8 < 4; // ~320ms on / 320ms off
            let dot = Style::new()
                .fg(if on { TN_YELLOW } else { TN_GRAY })
                .bold()
                .render("");
            let m = " ".repeat(PAD);
            blocks.push(if arg.is_empty() {
                format!("{m}{dot} {verb}")
            } else {
                format!("{m}{dot} {verb} {arg}")
            });
        }
        // Live stdout of the running tool — tail prefixed with "│" like Codex.
        if !self.tool_output.trim().is_empty() {
            let m = " ".repeat(PAD + 2);
            let bar = Style::new().fg(TN_GRAY).render("");
            let tail: Vec<&str> = self.tool_output.lines().rev().take(12).collect();
            let body = tail
                .into_iter()
                .rev()
                .map(|l| format!("{m}{bar} {}", Style::new().fg(TN_GRAY).render(l)))
                .collect::<Vec<_>>()
                .join("\n");
            blocks.push(body);
        }
        // Same "\n…\n" framing as rebuild_viewport so the transcript doesn't
        // jump a line when streaming starts/ends.
        self.viewport
            .set_content(&format!("\n{}\n", blocks.join("\n\n")));
    }

    fn rebuild_viewport(&mut self) {
        self.selection = None; // content changed → screen-coord selection is stale
        let full = self.messages.join("\n\n");
        self.viewport.set_content(&format!("\n{full}\n")); // top padding
    }

    /// Rows the input box needs — the textarea auto-grows its own height with
    /// embedded newlines (Shift+Enter), so the layout just mirrors it.
    pub(crate) fn input_height(&self) -> u16 {
        self.textarea.height()
    }

    /// Inline tool-approval keys (Codex-style): y/Enter allow, n/Esc deny,
    /// a = allow + enable auto-approve for the rest of the session.
    fn handle_approval_key(&mut self, key: &KeyEvent) -> Option<Cmd<Msg>> {
        match key.code {
            KeyCode::Up => {
                self.approval_sel = self.approval_sel.saturating_sub(1);
                None
            }
            KeyCode::Down => {
                self.approval_sel = (self.approval_sel + 1).min(2);
                None
            }
            // Enter selects the highlighted option (0 yes · 1 always · 2 no).
            KeyCode::Enter => Some(cmd::msg(self.apply_approval(self.approval_sel))),
            KeyCode::Char('y' | 'Y') => Some(cmd::msg(self.apply_approval(0))),
            KeyCode::Char('a' | 'A') => Some(cmd::msg(self.apply_approval(1))),
            KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(cmd::msg(self.apply_approval(2))),
            // Digit keys pick the numbered option directly (1 Yes · 2 Always · 3 No).
            KeyCode::Char(c @ '1'..='3') => {
                Some(cmd::msg(self.apply_approval(c as usize - '1' as usize)))
            }
            _ => None,
        }
    }

    fn apply_approval(&mut self, choice: usize) -> Msg {
        match choice {
            0 => Msg::ModalConfirm(0), // yes, once
            1 => {
                self.mode = Mode::Auto; // yes, and stop asking
                Msg::ModalConfirm(0)
            }
            _ => Msg::ModalConfirm(1), // no
        }
    }

    /// Tool-approval options panel (Claude-style numbered choices).
    fn overlay_approval(&self, composed: String) -> String {
        if self.state != State::Awaiting {
            return composed;
        }
        let Some((_, label)) = &self.pending_tool else {
            return composed;
        };
        let width = self.width as usize;
        let opts = ["Yes", "Yes, and don't ask again", "No"];
        let mut menu = vec![pad_to(
            &Style::new()
                .fg(TN_YELLOW)
                .bold()
                .render(&format!("  ⏵ Allow {label}?")),
            width,
        )];
        for (i, o) in opts.iter().enumerate() {
            let marker = if i == self.approval_sel { "" } else { " " };
            let raw = pad_to(&format!("  {marker} {}. {o}", i + 1), width);
            menu.push(if i == self.approval_sel {
                Style::new().fg(Color::BrightWhite).bg(ACCENT).render(&raw)
            } else {
                Style::new().fg(TN_FG).render(&raw)
            });
        }
        menu.push(pad_to(
            &Style::new()
                .fg(TN_GRAY)
                .render("  Enter select · ↑/↓ · 1–3 · Esc"),
            width,
        ));
        self.overlay_list(composed, &menu)
    }
}

/// Headless probe of the same `session.stream()` / `AgentEvent` path the TUI
/// uses, auto-approving tool calls. Drives the integration without a TTY.
async fn run_smoke(session: Arc<AgentSession>) -> anyhow::Result<()> {
    let prompt = std::env::var("A3S_CODE_TUI_PROMPT")
        .unwrap_or_else(|_| "Reply with exactly one short sentence: what is 2 + 2?".to_string());
    eprintln!("[smoke] prompt: {prompt}");
    let (mut rx, join) = session.stream(prompt.as_str(), None).await?;
    while let Some(event) = rx.recv().await {
        match event {
            AgentEvent::TextDelta { text } => print!("{text}"),
            AgentEvent::ToolStart { name, .. } => eprintln!("\n[tool start] {name}"),
            AgentEvent::ToolEnd {
                name,
                exit_code,
                output,
                ..
            } => eprintln!(
                "[tool end] {name} (exit {exit_code}): {}",
                output.lines().take(2).collect::<Vec<_>>().join(" | ")
            ),
            AgentEvent::ConfirmationRequired {
                tool_id, tool_name, ..
            } => {
                eprintln!("[confirm] auto-allowing {tool_name}");
                let _ = session.confirm_tool_use(&tool_id, true, None).await;
            }
            AgentEvent::End { .. } => eprintln!("\n[end]"),
            AgentEvent::Error { message } => eprintln!("\n[error] {message}"),
            _ => {}
        }
    }
    // Let the stream task finish (incl. auto-save/persist) before we exit.
    let _ = join.await;
    Ok(())
}

pub async fn run(args: Vec<String>) -> anyhow::Result<()> {
    // `a3s code resume [id]` continues a saved session (newest if no id given);
    // otherwise a fresh id. Existence is verified against the store below.
    let resuming = args.first().map(String::as_str) == Some("resume");
    let explicit_id = if resuming { args.get(1).cloned() } else { None };
    let mut session_id = explicit_id.clone().unwrap_or_else(new_session_id);
    // First launch: if there's no config, generate a starter template at
    // ~/.a3s/config.acl and open it in the built-in IDE (see `created_config`).
    let (config_path, created_config) = match find_config() {
        Some(p) => (p, false),
        None => {
            let p = default_config_path()
                .ok_or_else(|| anyhow::anyhow!("no HOME directory found for ~/.a3s/config.acl"))?;
            write_template_config(&p)
                .map_err(|e| anyhow::anyhow!("failed to write starter config {p:?}: {e}"))?;
            (p.to_string_lossy().into_owned(), true)
        }
    };
    let agent = Arc::new(
        Agent::new(config_path.clone())
            .await
            .map_err(|e| anyhow::anyhow!("failed to load agent from {config_path}: {e}"))?,
    );
    let workspace = std::env::current_dir()?.to_string_lossy().to_string();

    // Configured "provider/model" ids (+ context windows) + the default model.
    let mut models: Vec<String> = Vec::new();
    let mut model_ctx: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
    let mut default_model: Option<String> = None;
    let mut os_config: Option<OsConfig> = None;
    if let Ok(cfg) =
        a3s_code_core::config::CodeConfig::from_file(std::path::Path::new(&config_path))
    {
        for (p, m) in cfg.list_models() {
            let id = format!("{}/{}", p.name, m.id);
            model_ctx.insert(id.clone(), m.limit.context);
            models.push(id);
        }
        default_model = cfg.default_model.clone();
        os_config = cfg.os.clone();
    }
    let context_limit = resolve_ctx_limit(
        default_model
            .as_ref()
            .and_then(|m| model_ctx.get(m))
            .copied(),
    );

    // Persistent, resumable session: stored under <cwd>/.a3s/tui-sessions and
    // keyed by a fixed id, so relaunching in the same directory continues the
    // conversation. Falls back to a fresh session when none exists yet.
    let store_dir = std::path::Path::new(&workspace).join(".a3s/tui-sessions");

    // Resolve `resume`: verify the id exists (else show what's available), or
    // pick the most recent session when no id was given.
    if resuming {
        let mut saved: Vec<(String, std::time::SystemTime)> = std::fs::read_dir(&store_dir)
            .into_iter()
            .flatten()
            .flatten()
            .filter_map(|e| {
                let p = e.path();
                if p.extension().and_then(|x| x.to_str()) != Some("json") {
                    return None;
                }
                let id = p.file_stem()?.to_str()?.to_string();
                let mtime = e.metadata().ok()?.modified().ok()?;
                Some((id, mtime))
            })
            .collect();
        saved.sort_by_key(|e| std::cmp::Reverse(e.1)); // newest first
        match &explicit_id {
            Some(id) if !saved.iter().any(|(s, _)| s == id) => {
                eprintln!("a3s: session '{id}' not found in {}", store_dir.display());
                if saved.is_empty() {
                    eprintln!("  (no saved sessions in this directory)");
                } else {
                    eprintln!("  available sessions (newest first):");
                    for (s, _) in saved.iter().take(10) {
                        eprintln!("    a3s code resume {s}");
                    }
                }
                return Ok(());
            }
            None => match saved.first() {
                Some((s, _)) => session_id = s.clone(),
                None => {
                    eprintln!(
                        "a3s: no saved sessions to resume in {}",
                        store_dir.display()
                    );
                    return Ok(());
                }
            },
            _ => {}
        }
    }

    let store: Arc<dyn a3s_code_core::store::SessionStore> = Arc::new(
        a3s_code_core::store::FileSessionStore::new(&store_dir)
            .await
            .map_err(|e| anyhow::anyhow!("failed to open session store {store_dir:?}: {e}"))?,
    );
    // Enable HITL confirmation so file-modifying tools (write/edit/patch) can
    // run — they require a confirmation manager, otherwise they fail with
    // "requires confirmation but no HITL confirmation manager is configured".
    // The TUI is that manager (approve/deny modal, or /auto). Long timeout so
    // the modal never expires while the user reads it.
    let confirmation = a3s_code_core::hitl::ConfirmationPolicy::enabled()
        .with_timeout(3_600_000, TimeoutAction::Reject);
    // Claude Code compatibility: load Claude/plugin SKILL.md skills alongside
    // a3s's own (they share the markdown + YAML-frontmatter format).
    let mut claude_dirs = agent_skill_dirs(&workspace);
    // Restore the persisted OS login *before* building the session, so its
    // login-gated built-in `a3s-os-capabilities` skill is materialized and
    // loaded from the first turn (only when signed in).
    let os_session = os_config.as_ref().and_then(crate::a3s_os::current_session);
    if let Some(s) = &os_session {
        // Export endpoint + token so the agent's shell uses $A3S_OS_* directly
        // instead of re-reading ~/.a3s/os-auth.json every call.
        crate::a3s_os::export_os_env(s);
        if let Some(dir) = os_config
            .as_ref()
            .and_then(crate::a3s_os::ensure_capability_skill_dir)
        {
            claude_dirs.push(dir);
        }
    }
    // Claude Code compatibility: inject CLAUDE.md (AGENTS.md is auto-loaded by
    // the core) into the system prompt via prompt slots.
    let instructions = project_instructions(&workspace);
    // When a persisted login is restored on launch, inject the OS-platform
    // directive too (mirrors effort_session_opts) so the very first turn already
    // routes OS questions through the progressive-API skill.
    let os_address = os_session.as_ref().map(|s| s.address.clone());
    // Past-session recall: when the ctx CLI is installed, teach the agent to
    // search local agent history before re-deriving prior work.
    let ctx_ready = panels::ctx::ctx_available();
    let with_instr = |o: SessionOptions| {
        let mut parts: Vec<String> = Vec::new();
        if let Some(i) = &instructions {
            parts.push(i.clone());
        }
        if let Some(addr) = &os_address {
            parts.push(os_platform_guide(addr));
        }
        if ctx_ready {
            parts.push(panels::ctx::ctx_history_guide());
        }
        if parts.is_empty() {
            o
        } else {
            o.with_prompt_slots(SystemPromptSlots::default().with_extra(parts.join("\n\n")))
        }
    };
    let manifest_backend = ManifestWorkspaceBackend::new(std::path::PathBuf::from(&workspace));
    let workspace_manifest = manifest_backend.manifest();
    let initial_manifest = workspace_manifest.snapshot();
    let initial_files = initial_manifest.file_paths();
    let workspace_manifest_rx = Arc::new(Mutex::new(workspace_manifest.subscribe()));
    let workspace_services = WorkspaceServices::local_with_manifest_backend(manifest_backend);
    let session = match agent.resume_session(
        session_id.as_str(),
        with_instr(with_recent_workspace_context(
            SessionOptions::new()
                .with_session_store(store.clone())
                .with_confirmation_policy(confirmation.clone())
                .with_workspace_backend(workspace_services.clone())
                .with_skill_dirs(claude_dirs.clone())
                .with_auto_save(true)
                .with_auto_compact(true)
                // Scaled to the model's real window — the core triggers off a
                // fixed 200k, so a flat 0.85 would put the trigger past a
                // smaller window and auto-compact would never fire (see
                // `auto_compact_threshold_for`).
                .with_auto_compact_threshold(auto_compact_threshold_for(context_limit))
                .with_file_memory(memory_dir())
                .with_max_parallel_tasks(8)
                .with_auto_delegation_enabled(true)
                .with_auto_parallel_delegation(true)
                .with_manual_delegation_enabled(true),
            &workspace_manifest,
        )),
    ) {
        Ok(s) => s,
        Err(_) => agent.session(
            workspace.clone(),
            Some(with_instr(with_recent_workspace_context(
                SessionOptions::new()
                    .with_session_store(store.clone())
                    .with_session_id(session_id.as_str())
                    .with_confirmation_policy(confirmation.clone())
                    .with_workspace_backend(workspace_services.clone())
                    .with_skill_dirs(claude_dirs.clone())
                    .with_auto_save(true)
                    .with_auto_compact(true)
                    .with_auto_compact_threshold(auto_compact_threshold_for(context_limit))
                    .with_file_memory(memory_dir())
                    .with_max_parallel_tasks(8)
                    .with_auto_delegation_enabled(true)
                    .with_auto_parallel_delegation(true)
                    .with_manual_delegation_enabled(true),
                &workspace_manifest,
            ))),
        )?,
    };

    // A3S Runtime offload tool: registered only when signed in to OS, so the
    // model sees `runtime` after login and not before. Auth changes re-sync it via
    // `refresh_after_auth` → `sync_runtime_tool`.
    if let Some(os) = os_session.as_ref() {
        session.register_dynamic_tool(std::sync::Arc::new(crate::runtime_tool::RuntimeTool::new(
            os,
        )));
    }

    let (width, height) = a3s_tui::terminal::Terminal::size().unwrap_or((80, 24));

    // Seed the transcript with any resumed conversation (user + assistant text).
    let resumed = session.history();
    let mut initial_messages: Vec<String> = resumed
        .iter()
        .filter_map(|m| {
            let text = m.text();
            if text.trim().is_empty() {
                return None;
            }
            match m.role.as_str() {
                // Same gutter (● dot + indent) as live messages.
                "user" => Some(gutter(ACCENT, text.trim())),
                "assistant" => {
                    let mut md = StreamingMarkdown::new((width as usize).saturating_sub(PAD + 2));
                    md.push(&text);
                    Some(gutter(TN_GREEN, &md.view()))
                }
                _ => None,
            }
        })
        .collect();
    // Seed ↑/↓ input recall with the user's prior prompts so resuming a session
    // keeps its command history (tool-result `user` messages carry no text block,
    // so the non-empty filter excludes them).
    let history_seed: Vec<String> = resumed
        .iter()
        .filter(|m| m.role == "user")
        .map(|m| m.text().trim().to_string())
        .filter(|t| !t.is_empty())
        .collect();

    // Quiet confirmation that the persisted login was restored. Only when
    // RESUMING an existing conversation — on a fresh start, leaving the transcript
    // empty lets the welcome banner show (it notes the signed-in account itself);
    // inserting this line here is what was suppressing the banner after OS login.
    if let Some(s) = &os_session {
        if !initial_messages.is_empty() {
            initial_messages.insert(
                0,
                Style::new().fg(TN_GRAY).render(&format!(
                    "  ✓ signed in to OS as {} · capabilities skill active · /logout to sign out",
                    s.display_label()
                )),
            );
        }
    }

    let session = Arc::new(session);

    // Headless smoke mode: exercise the agent-stream integration (the hard part
    // the TUI depends on) without taking over the terminal. Useful for CI/probes
    // and for validating a model/config end-to-end.
    if std::env::var_os("A3S_CODE_TUI_SMOKE").is_some() {
        return run_smoke(session).await;
    }

    let keymap = Keymap::new()
        .bind(
            KeyBinding::new(KeyCode::PageUp),
            Action::ScrollUp,
            "Scroll up",
        )
        .bind(
            KeyBinding::new(KeyCode::PageDown),
            Action::ScrollDown,
            "Scroll down",
        )
        // NB: Ctrl+U / Ctrl+D are intentionally NOT bound to scroll — they shadow
        // readline line-editing (Ctrl+U = kill-to-start) in the input. PageUp/Down
        // and Ctrl+Home/End cover scrolling.
        .bind(
            KeyBinding::ctrl(KeyCode::Home),
            Action::ScrollTop,
            "Scroll to top",
        )
        .bind(
            KeyBinding::ctrl(KeyCode::End),
            Action::ScrollBottom,
            "Scroll to bottom",
        );

    let mut app = App {
        session,
        agent: agent.clone(),
        store: store.clone(),
        confirmation,
        session_id: session_id.clone(),
        models,
        relay: Vec::new(),
        relay_menu: None,
        relay_tab: 0,
        model_ctx,
        context_limit,
        last_prompt_tokens: 0,
        ctx_warned_tier: 0,
        model_menu: None,
        model_tab: 0,
        llm_override: None,
        os_config,
        os_session,
        os_refreshing: false,
        os_gateway_models: None,
        os_gateway_error: None,
        last_view: None,
        effort: 2, // high
        effort_panel: None,
        theme_panel: None,
        quit_armed: None,
        last_activity: Instant::now(),
        auto_reviewed: false,
        shell_mode: false,
        research_mode: false,
        review_mode: false,
        review_pending: false,
        sleep_pending: false,
        review: None,
        review_open: false,
        repo_picker: None,
        flow: None,
        autonomy_restore: None,
        evolve: None,
        evolve_mode: false,
        evolve_target: None,
        ctx_ready,
        ctx_hits: Vec::new(),
        pending_ctx: None,
        loop_continuation: false,
        turn_text: String::new(),
        selection: None,
        last_workflow: None,
        pending_images: Vec::new(),
        goal: None,
        goal_since: None,
        loop_remaining: 0,
        active_tools: 0,
        active_agents: 0,
        subagents: Vec::new(),
        turn_had_agent_activity: false,
        turn_text_after_activity: false,
        ultracode_synthesis_inflight: false,
        ultracode_synthesis_used: false,
        instructions,
        workspace_manifest,
        workspace_manifest_rx,
        workspace_services,
        rainbow_until: None,
        rainbow_frame: 0,
        effort_anim: None,
        compact_summary: None,
        btw: None,
        viewport: Viewport::new(width.saturating_sub(1), height.saturating_sub(7)),
        textarea: Textarea::new()
            .with_height(1)
            .with_auto_grow(8) // box grows with Shift+Enter newlines (no scroll)
            .with_width(width.saturating_sub((PAD + 2) as u16)) // PAD margin + "❯ "
            .with_submit_on_enter(true),
        spinner: Spinner::new().with_title(""),
        streaming: StreamingMarkdown::new((width as usize).saturating_sub(PAD + 2)),
        got_delta: false,
        compacting: None,
        updating: None,
        last_paint: None,
        thinking: String::new(),
        state: State::Idle,
        messages: initial_messages,
        rx: None,
        pending_tool: None,
        approval_sel: 0,
        history: history_seed,
        history_pos: None,
        model: default_model,
        output_tokens: 0,
        tool_args: String::new(),
        tool_output: String::new(),
        tool_log: Vec::new(),
        stream_started: None,
        running_tool: None,
        blink_tick: 0,
        anim: 0,
        mode: Mode::Default,
        queue: BinaryHeap::new(),
        seq: 0,
        running_task: None,
        plan: Vec::new(),
        top: None,
        top_scroll: 0,
        top_sel: 0,
        top_focus: None,
        top_kill: None,
        ide: None,
        chat: None,
        git: None,
        memory: None,
        help_open: false,
        completed: 0,
        branch: git_branch(&workspace),
        slash_sel: 0,
        files: initial_files,
        at_expanded: std::collections::HashSet::new(),
        file_sel: 0,
        skill_count: count_skill_files(&claude_dirs),
        skills: load_skills(&claude_dirs),
        disabled_skills: load_disabled_skills(),
        plugins_panel: None,
        update_available: None,
        cwd: workspace.clone(),
        width,
        height,
        keymap,
    };

    // First launch: drop the user straight into the editor on the new config.
    if created_config {
        app.messages.push(gutter(
            ACCENT,
            "Welcome to a3s code! Generated a starter ~/.a3s/config.acl — fill in your \
             provider apiKey/baseUrl + model, Ctrl+S to save, Esc to close, then restart \
             `a3s code` to load it.",
        ));
        app.open_config_in_ide(std::path::Path::new(&config_path));
        app.rebuild_viewport();
    }

    // Apply the current effort (default `high`) to the launch session so the
    // FIRST turn already runs at the chosen depth. The session built above is
    // effort-naive — the scaled tool-round budget and the depth guideline live
    // only in effort_session_opts (reached via rebuild_session, as every
    // /effort switch does). Best-effort: keep the launch session if it can't
    // rebuild. (Resumes the same id, so transcript history is preserved.)
    let launch_model = app.model.clone();
    if let Ok((s, _)) = app.rebuild_session(launch_model.as_deref()) {
        app.session = Arc::new(s);
    }

    ProgramBuilder::new(app)
        .with_alt_screen()
        // Capture the mouse so the wheel scrolls the transcript (alt-screen has no
        // terminal scrollback, so capture is the only way to get wheel events).
        // Copy is preserved: most terminals still do native selection on
        // Shift+drag (Fn/⌥ on macOS Terminal) even with capture on, plus `/copy`
        // yanks the last reply via OSC52, and `/mouse` drops capture entirely for
        // pure native selection.
        .with_mouse_support()
        .with_fps(30)
        .run()
        .await?;

    // `/update` found a newer version → upgrade via Homebrew in the (now
    // restored) shell so brew's own download progress shows, then re-exec the
    // freshly-installed binary. Use PATH `a3s` (brew repointed its symlink to
    // the new version); current_exe() is the OLD version's path.
    if UPGRADE_ON_EXIT.load(std::sync::atomic::Ordering::Relaxed) {
        let latest = LATEST
            .lock()
            .ok()
            .and_then(|g| g.clone())
            .unwrap_or_default();
        match crate::update::perform_upgrade(&latest) {
            Some(bin) => {
                let restart_args = ["code", "resume", session_id.as_str()];
                #[cfg(unix)]
                {
                    use std::os::unix::process::CommandExt;
                    // exec replaces this process; only returns on failure → fall back.
                    let _ = std::process::Command::new(&bin).args(restart_args).exec();
                    if let Ok(exe) = std::env::current_exe() {
                        let _ = std::process::Command::new(exe).args(restart_args).exec();
                    }
                }
                #[cfg(not(unix))]
                {
                    let _ = std::process::Command::new(&bin).args(restart_args).status();
                }
            }
            None => eprintln!(
                "\n✗ upgrade failed — get the latest from https://github.com/A3S-Lab/Cli/releases/latest\n"
            ),
        }
        return Ok(());
    }

    // Session is auto-saved under this directory; show how to come back.
    println!("\n  session saved · resume it with:  a3s code resume {session_id}\n");
    Ok(())
}

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

    #[test]
    fn effort_ladder_is_monotonic_and_well_formed() {
        // ULTRACODE indexes the last level, which is the ultracode profile.
        assert_eq!(ULTRACODE, EFFORT_LEVELS.len() - 1);
        assert_eq!(EFFORT_LEVELS[ULTRACODE].label, "ultracode");
        // Depth rises with effort: thinking budget and tool-round budget both
        // non-decreasing across low → max (so higher effort is never shallower).
        for w in EFFORT_LEVELS[..=ULTRACODE].windows(2) {
            assert!(
                w[1].thinking_budget >= w[0].thinking_budget,
                "thinking budget regressed"
            );
            assert!(
                w[1].max_tool_rounds >= w[0].max_tool_rounds,
                "tool-round budget regressed"
            );
            assert!(
                w[1].max_continuation_turns >= w[0].max_continuation_turns,
                "continuation budget regressed"
            );
        }
        // medium is the unsteered baseline; every other level carries a guideline
        // so effort is meaningful even on models with no thinking budget.
        assert!(
            EFFORT_LEVELS[1].guideline.is_none(),
            "medium should be the baseline"
        );
        for (i, p) in EFFORT_LEVELS.iter().enumerate() {
            if i != 1 {
                assert!(
                    p.guideline.is_some(),
                    "level {} has no depth steer",
                    p.label
                );
            }
        }
    }

    use a3s_code_core::llm::{
        ContentBlock, LlmClient, LlmResponse, Message, StreamEvent, TokenUsage, ToolDefinition,
    };
    use async_trait::async_trait;
    use std::collections::VecDeque;
    use std::sync::{Arc, Mutex};
    use tokio::sync::mpsc;
    use tokio_util::sync::CancellationToken;

    #[derive(Clone, Default)]
    struct CapturedLlmTurn {
        system: Option<String>,
        tools: Vec<String>,
    }

    struct CaptureLlmClient {
        turns: Mutex<Vec<CapturedLlmTurn>>,
        responses: Mutex<VecDeque<LlmResponse>>,
    }

    #[async_trait]
    impl LlmClient for CaptureLlmClient {
        async fn complete(
            &self,
            _messages: &[Message],
            system: Option<&str>,
            tools: &[ToolDefinition],
        ) -> anyhow::Result<LlmResponse> {
            self.record(system, tools);
            Ok(self.next_response())
        }

        async fn complete_streaming(
            &self,
            _messages: &[Message],
            system: Option<&str>,
            tools: &[ToolDefinition],
            _cancel_token: CancellationToken,
        ) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
            self.record(system, tools);
            let response = self.next_response();
            let (tx, rx) = mpsc::channel(2);
            tokio::spawn(async move {
                let _ = tx.send(StreamEvent::Done(response)).await;
            });
            Ok(rx)
        }
    }

    impl CaptureLlmClient {
        fn new(responses: Vec<LlmResponse>) -> Self {
            Self {
                turns: Mutex::new(Vec::new()),
                responses: Mutex::new(responses.into()),
            }
        }

        fn record(&self, system: Option<&str>, tools: &[ToolDefinition]) {
            self.turns.lock().unwrap().push(CapturedLlmTurn {
                system: system.map(str::to_string),
                tools: tools.iter().map(|tool| tool.name.clone()).collect(),
            });
        }

        fn next_response(&self) -> LlmResponse {
            self.responses
                .lock()
                .unwrap()
                .pop_front()
                .unwrap_or_else(done_response)
        }

        fn turns(&self) -> Vec<CapturedLlmTurn> {
            self.turns.lock().unwrap().clone()
        }
    }

    fn tool_call_response(name: &str, input: serde_json::Value) -> LlmResponse {
        LlmResponse {
            message: Message {
                role: "assistant".into(),
                content: vec![ContentBlock::ToolUse {
                    id: "toolu_test".into(),
                    name: name.into(),
                    input,
                }],
                reasoning_content: None,
            },
            usage: TokenUsage::default(),
            stop_reason: Some("tool_use".into()),
            meta: None,
        }
    }

    fn done_response() -> LlmResponse {
        LlmResponse {
            message: Message {
                role: "assistant".into(),
                content: vec![ContentBlock::Text {
                    text: "DONE".into(),
                }],
                reasoning_content: None,
            },
            usage: TokenUsage::default(),
            stop_reason: Some("stop".into()),
            meta: None,
        }
    }

    fn test_config(path: &std::path::Path) {
        std::fs::write(
            path,
            "default_model = \"openai/x\"\n\
             providers \"openai\" {\n  apiKey = \"x\"\n  baseUrl = \"http://127.0.0.1:1\"\n  \
             models \"x\" { name = \"x\" }\n}\n",
        )
        .unwrap();
    }

    /// Guard: the parallel/ultracode SessionOptions register `task` +
    /// `parallel_task` in the session tool surface (so fan-out has a tool to call).
    #[tokio::test]
    async fn parallel_opts_register_parallel_task() {
        let dir = std::env::temp_dir().join(format!("a3s-ptask-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let cfg = dir.join("config.acl");
        test_config(&cfg);
        let agent = a3s_code_core::Agent::new(cfg.to_string_lossy().to_string())
            .await
            .unwrap();
        // The FULL ultracode config (planning + goal + parallel fan-out).
        let opts = SessionOptions::new()
            .with_max_parallel_tasks(8)
            .with_auto_delegation_enabled(true)
            .with_auto_parallel_delegation(true)
            .with_manual_delegation_enabled(true)
            .with_planning_mode(a3s_code_core::PlanningMode::Enabled)
            .with_goal_tracking(true)
            .with_max_tool_rounds(200);
        let session = agent
            .session(dir.to_string_lossy().to_string(), Some(opts))
            .unwrap();
        let names = session.tool_names();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            names.contains(&"parallel_task".to_string()) && names.contains(&"task".to_string()),
            "parallel_task/task registered under the parallel opts; got {names:?}"
        );
    }

    // ── `/output` formatting ───────────────────────────────────────────────
    #[test]
    fn format_tool_log_empty_is_none() {
        assert!(format_tool_log_records(&[]).is_none());
    }

    #[test]
    fn format_tool_log_renders_header_args_and_output() {
        let recs = vec![
            ToolCallRecord {
                name: "read".into(),
                args: Some(serde_json::json!({"file_path": "/x"})),
                output: "hello\n".into(),
                exit_code: 0,
            },
            ToolCallRecord {
                name: "bash".into(),
                args: None,
                output: String::new(),
                exit_code: 2,
            },
        ];
        let out = format_tool_log_records(&recs).unwrap();
        assert!(out.contains("#1 · read · ok"), "{out}");
        assert!(out.contains("args: {\"file_path\":\"/x\"}"), "{out}");
        assert!(
            out.contains("    hello"),
            "output should be indented: {out}"
        );
        assert!(out.contains("#2 · bash · exit 2"), "{out}");
    }

    // ── `?` deep-research mode ─────────────────────────────────────────────
    #[test]
    fn deep_research_prompt_directs_research_and_keeps_query() {
        let p = deep_research_prompt("rust async runtimes");
        assert!(p.contains("rust async runtimes"), "{p}");
        let lo = p.to_lowercase();
        assert!(lo.contains("deep research"), "{p}");
        assert!(lo.contains("web search") && lo.contains("web_fetch"), "{p}");
        assert!(lo.contains("source"), "should ask to cite sources: {p}");
    }

    #[test]
    fn deep_research_goal_is_a_research_north_star_with_query() {
        let g = deep_research_goal("rust async runtimes");
        assert!(g.contains("rust async runtimes"), "{g}");
        assert!(g.to_lowercase().contains("research"), "{g}");
    }

    // ── scroll + copy ──────────────────────────────────────────────────────
    #[test]
    fn scrollbar_blank_when_content_fits() {
        let out = append_scrollbar("a\nb\nc", 5, 3, 100);
        assert_eq!(out.lines().count(), 3);
        for line in out.lines() {
            assert!(line.ends_with(' '), "no-overflow gutter blank: {line:?}");
            assert!(!line.contains('') && !line.contains(''));
        }
    }

    #[test]
    fn scrollbar_thumb_tracks_position() {
        let view = "r0\nr1\nr2\nr3"; // 4 visible rows, far more total
        let top = append_scrollbar(view, 4, 40, 0);
        assert!(top.lines().next().unwrap().contains(''), "thumb at top");
        let bottom = append_scrollbar(view, 4, 40, 100);
        assert!(
            bottom.lines().last().unwrap().contains(''),
            "thumb at bottom"
        );
        // every row carries the bar (thumb or track) once content overflows
        assert!(top.lines().all(|l| l.contains('') || l.contains('')));
    }

    #[test]
    fn osc52_wraps_base64_in_envelope() {
        let s = osc52_copy("hi");
        assert!(s.starts_with("\u{1b}]52;c;") && s.ends_with('\u{7}'));
        assert!(s.contains("aGk=")); // base64("hi")
    }

    #[test]
    fn slice_cols_handles_ascii_and_wide() {
        assert_eq!(slice_cols("hello", 1, 4), "ell");
        assert_eq!(slice_cols("hello", 0, 100), "hello");
        // CJK glyphs are width-2: "你好" spans columns 0..4.
        assert_eq!(slice_cols("你好", 0, 2), "");
        assert_eq!(slice_cols("你好", 2, 4), "");
    }

    #[test]
    fn selection_to_text_extracts_span_across_rows() {
        let view = "  hello world\n  second line\n  third";
        // row0 col2..end, through row1 col0..8 — trailing padding trimmed.
        let t = selection_to_text(view, 0, 2, 1, 8);
        assert_eq!(t, "hello world\n  second");
    }

    #[test]
    fn highlight_selection_touches_only_selected_rows() {
        let view = "row zero\nrow one\nrow two";
        let out = highlight_selection(view, 1, 0, 1, 7);
        let lines: Vec<&str> = out.split('\n').collect();
        assert_eq!(lines[0], "row zero"); // untouched
        assert_eq!(lines[2], "row two"); // untouched
        assert!(lines[1].contains("row one")); // selected text preserved
        assert!(lines[1].contains('\u{1b}')); // wrapped in a style escape
    }

    /// `?` deep research is only meaningful if the agent actually has the web
    /// tools to call — guard that they're registered in the session surface.
    #[tokio::test]
    async fn web_tools_registered_for_q_research_mode() {
        let dir = std::env::temp_dir().join(format!(
            "a3s-research-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let cfg = dir.join("config.acl");
        test_config(&cfg);
        let agent = a3s_code_core::Agent::new(cfg.to_string_lossy().to_string())
            .await
            .unwrap();
        let session = agent
            .session(dir.to_string_lossy().to_string(), None)
            .unwrap();
        let names = session.tool_names();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            names.contains(&"web_search".to_string()) && names.contains(&"web_fetch".to_string()),
            "the `?` deep-research mode relies on web_search + web_fetch; got {names:?}"
        );
    }

    #[tokio::test]
    async fn claude_session_surface_passes_system_tools_and_skills_to_llm() {
        let dir = std::env::temp_dir().join(format!(
            "a3s-claude-surface-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let cfg = dir.join("config.acl");
        test_config(&cfg);
        std::fs::write(
            dir.join("CLAUDE.md"),
            "Project rule: claude-session-surface-marker",
        )
        .unwrap();
        let skill_dir = dir.join(".claude/skills/inspect-surface");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: inspect-surface\n\
             description: Inspect the Claude session surface\n\
             kind: instruction\n\
             allowed-tools:\n  - Read\n---\n\
             Use this skill marker: inspect-surface-skill-marker\n",
        )
        .unwrap();

        let agent = a3s_code_core::Agent::new(cfg.to_string_lossy().to_string())
            .await
            .unwrap();
        let llm = Arc::new(CaptureLlmClient::new(vec![done_response()]));
        let opts = SessionOptions::new()
            .with_llm_client(llm.clone())
            .with_prompt_slots(
                SystemPromptSlots::default()
                    .with_extra(project_instructions(dir.to_str().unwrap()).unwrap()),
            )
            .with_skill_dirs(agent_skill_dirs(dir.to_str().unwrap()))
            .with_manual_delegation_enabled(true)
            .with_auto_delegation_enabled(false)
            .with_planning_mode(a3s_code_core::PlanningMode::Disabled);
        let session = agent
            .session(dir.to_string_lossy().to_string(), Some(opts))
            .unwrap();

        let (mut rx, join) = session
            .stream("Use available skills to inspect this project.", None)
            .await
            .unwrap();
        while let Some(event) = rx.recv().await {
            if matches!(event, a3s_code_core::AgentEvent::End { .. }) {
                break;
            }
        }
        join.await.unwrap();
        let turns = llm.turns();
        let captured = turns.first().unwrap();
        let system = captured.system.as_deref().unwrap();
        let _ = std::fs::remove_dir_all(&dir);

        assert!(
            system.contains("You are A3S Code"),
            "core system prompt should reach the LLM"
        );
        assert!(
            system.contains("claude-session-surface-marker"),
            "CLAUDE.md project instructions should reach the LLM"
        );
        assert!(
            system.contains("# Skills"),
            "skill catalog guidance should reach the LLM system prompt"
        );
        assert!(
            captured.tools.iter().any(|name| name == "read")
                && captured.tools.iter().any(|name| name == "Skill")
                && captured.tools.iter().any(|name| name == "search_skills")
                && captured.tools.iter().any(|name| name == "parallel_task"),
            "a3s tools and skill tools should be model-visible; got {:?}",
            captured.tools
        );
    }

    #[tokio::test]
    async fn claude_can_invoke_skill_and_child_run_receives_skill_prompt() {
        let dir = std::env::temp_dir().join(format!(
            "a3s-claude-skill-invoke-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let cfg = dir.join("config.acl");
        test_config(&cfg);
        let skill_dir = dir.join(".claude/skills/inspect-surface");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: inspect-surface\n\
             description: Inspect the Claude session surface\n\
             kind: instruction\n\
             allowed-tools:\n  - Read\n---\n\
             Use this skill marker: inspect-surface-skill-marker\n",
        )
        .unwrap();

        let agent = a3s_code_core::Agent::new(cfg.to_string_lossy().to_string())
            .await
            .unwrap();
        let llm = Arc::new(CaptureLlmClient::new(vec![
            tool_call_response(
                "Skill",
                serde_json::json!({
                    "skill_name": "inspect-surface",
                    "prompt": "Apply the inspect-surface skill."
                }),
            ),
            done_response(),
            done_response(),
        ]));
        let opts = SessionOptions::new()
            .with_llm_client(llm.clone())
            .with_skill_dirs(agent_skill_dirs(dir.to_str().unwrap()))
            .with_manual_delegation_enabled(true)
            .with_auto_delegation_enabled(false)
            .with_permission_policy(
                a3s_code_core::permissions::PermissionPolicy::new().allow("Skill(*)"),
            )
            .with_planning_mode(a3s_code_core::PlanningMode::Disabled)
            .with_max_tool_rounds(5);
        let session = agent
            .session(dir.to_string_lossy().to_string(), Some(opts))
            .unwrap();

        let result = session
            .send("Use the inspect-surface skill.", None)
            .await
            .unwrap();
        let turns = llm.turns();
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(result.text.trim(), "DONE");
        let system_snippets = turns
            .iter()
            .enumerate()
            .map(|(index, turn)| {
                format!(
                    "#{index}: {}",
                    turn.system
                        .as_deref()
                        .unwrap_or("<none>")
                        .chars()
                        .take(220)
                        .collect::<String>()
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            turns
                .iter()
                .any(|turn| turn.system.as_deref().is_some_and(|system| {
                    system.contains("You are executing the 'inspect-surface' skill")
                        && system.contains("inspect-surface-skill-marker")
                })),
            "Skill tool should start a child LLM run with the skill prompt; turns: {}",
            system_snippets
        );
    }

    #[test]
    fn workflow_doc_captures_single_task_dispatch() {
        let args = serde_json::json!({
            "agent": "plan",
            "description": "Design the rendering architecture",
            "prompt": "Plan a layered renderer."
        });
        let (doc, label) = workflow_doc_for_tool("task", Some(&args)).unwrap();

        assert!(label.contains("delegated task"), "{label}");
        assert!(doc.contains("Design the rendering architecture"));
        assert!(doc.contains("Agent: `plan`"));
        assert!(doc.contains("Plan a layered renderer."));
    }

    #[test]
    fn synthesis_requires_activity_without_followup_text() {
        // Fires when a turn had agent activity but produced no final text — in
        // ANY mode (no effort gate), so a high-effort fan-out that ends silently
        // still gets a synthesized answer.
        assert!(needs_synthesis(false, false, true, false));
        // No final answer needed if the turn already produced text after activity.
        assert!(!needs_synthesis(false, false, true, true));
        // At most once per turn.
        assert!(!needs_synthesis(false, true, true, false));
        // Nothing to synthesize if no work happened (e.g. a bare greeting).
        assert!(!needs_synthesis(false, false, false, false));
        // Never while a synthesis turn is itself in flight.
        assert!(!needs_synthesis(true, false, true, false));
    }

    #[test]
    fn estimate_tokens_counts_cjk_heavier_than_ascii() {
        assert_eq!(estimate_tokens("abcd"), 1); // ASCII ~4 chars/token
        assert_eq!(estimate_tokens("书安操作系统"), 6); // CJK ~1 token/char (chars/4 would say 1)
        assert_eq!(estimate_tokens("hi 书安"), 2); // mixed: 3 ASCII -> 0, 2 wide -> 2
        assert_eq!(estimate_tokens(""), 0);
    }

    #[test]
    fn ctx_limit_falls_back_when_undeclared() {
        assert_eq!(resolve_ctx_limit(Some(200_000)), 200_000); // declared wins
        assert_eq!(resolve_ctx_limit(Some(0)), DEFAULT_CONTEXT_LIMIT); // zero -> default
        assert_eq!(resolve_ctx_limit(None), DEFAULT_CONTEXT_LIMIT); // missing -> default
    }

    #[test]
    fn auto_compact_threshold_scales_to_real_window() {
        // 128k model: fire at 85% of 128k, i.e. 0.85*128/200 of the core's fixed 200k.
        assert!((auto_compact_threshold_for(128_000) - 0.544).abs() < 0.001);
        // 200k model == the core's own denominator: plain 0.85.
        assert!((auto_compact_threshold_for(200_000) - 0.85).abs() < 0.001);
        // Windows past ~235k clamp to 1.0 (trigger at the fixed 200k, never overflow).
        assert_eq!(auto_compact_threshold_for(1_000_000), 1.0);
        // Unknown window (0) falls back to the core default of 0.85.
        assert!((auto_compact_threshold_for(0) - 0.85).abs() < 0.001);
        // Small window: NOT floored past the window itself — 8k triggers at
        // 0.034 * 200k = 6.8k = 85% of 8k (the old 0.05 floor meant 10k > 8k,
        // i.e. compaction could never fire before overflow).
        assert!((auto_compact_threshold_for(8_000) - 0.034).abs() < 0.001);
    }

    #[test]
    fn ctx_warn_tier_latches_once_and_rearms_on_drop() {
        // Climb: 0 → warn at 70 tier → no re-warn inside the tier → warn at 85.
        assert_eq!(ctx_warn_tier(40, 0), (0, None));
        assert_eq!(ctx_warn_tier(72, 0), (70, Some(70)));
        assert_eq!(ctx_warn_tier(79, 70), (70, None)); // same tier: silent
        assert_eq!(ctx_warn_tier(91, 70), (85, Some(85)));
        assert_eq!(ctx_warn_tier(100, 85), (85, None));
        // Drop (compaction, /clear, wider model): latch re-arms.
        assert_eq!(ctx_warn_tier(30, 85), (0, None));
        assert_eq!(ctx_warn_tier(72, 0), (70, Some(70)));
        // Jump straight past both tiers warns the top one only.
        assert_eq!(ctx_warn_tier(90, 0), (85, Some(85)));
    }

    #[test]
    fn task_tool_empty_child_output_renders_useful_summary() {
        let args = serde_json::json!({
            "agent": "plan",
            "description": "Plan subsystem boundaries",
            "prompt": "Create the plan."
        });
        let meta = serde_json::json!({
            "task_id": "task-abc123",
            "session_id": "task-run-task-abc123",
            "agent": "plan",
            "success": true,
            "output_bytes": 0,
            "artifact_uri": "a3s://tasks/task-run-task-abc123/runs/task-abc123/output"
        });
        let output = "Task completed: task-abc123\n\
                      Agent: plan\n\
                      Session: task-run-task-abc123\n\
                      Task ID: task-abc123\n\
                      Artifact ID: task-output:task-abc123\n\
                      Artifact URI: a3s://tasks/task-run-task-abc123/runs/task-abc123/output\n\
                      Output:\n";
        let out = render_tool_end("task", 0, output, Some(&meta), Some(&args), 100);
        let plain = strip_ansi(&out);

        assert!(plain.contains("Explored"));
        assert!(plain.contains("Task completed · plan · task-abc123"));
        assert!(plain.contains("no child text output"));
        assert!(plain.contains("artifact: a3s://tasks/task-run-task-abc123"));
    }

    #[test]
    fn edit_metadata_renders_colored_diff() {
        let meta = serde_json::json!({
            "file_path": "src/x.rs",
            "before": "let a = 1;\nkeep;\n",
            "after": "let a = 2;\nkeep;\n",
        });
        let out = render_tool_end("edit", 0, "ok", Some(&meta), None, 80);
        // The diff code is syntax-highlighted (ANSI between tokens), so compare
        // against the ANSI-stripped text.
        let plain = strip_ansi(&out);
        assert!(plain.contains("src/x.rs"), "header has path");
        assert!(
            plain.contains("+1") && plain.contains("-1"),
            "add/del counts"
        );
        assert!(plain.contains("let a = 2;"), "shows inserted line");
        assert!(plain.contains("let a = 1;"), "shows deleted line");
        assert!(
            plain.contains("keep;"),
            "context lines are shown (unified diff)"
        );
        assert!(plain.contains("Edited src/x.rs"), "edit header with path");
    }

    /// Strip ANSI SGR sequences so tests can match the underlying text.
    fn strip_ansi(s: &str) -> String {
        let mut out = String::new();
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\x1b' {
                for c2 in chars.by_ref() {
                    if c2 == 'm' {
                        break;
                    }
                }
            } else {
                out.push(c);
            }
        }
        out
    }

    #[test]
    fn non_edit_tool_renders_status_line() {
        let out = render_tool_end("bash", 0, "hello\nworld", None, None, 80);
        // Action-verb header ("Ran") + the output; no diff marker.
        assert!(out.contains("Ran") && out.contains("hello"));
        assert!(!out.contains(''), "no diff marker for non-edit tools");
    }

    #[test]
    fn tool_end_shows_primary_arg_summary() {
        let args = serde_json::json!({ "command": "npm test", "timeout": 60 });
        let out = render_tool_end("bash", 0, "ok\n", None, Some(&args), 80);
        // Bash args are token-colored (program/flags/args), so check visible text.
        let plain = a3s_tui::style::strip_ansi(&out);
        assert!(plain.contains("Ran"), "action verb for bash");
        assert!(plain.contains("npm test"), "shows the command argument");
    }

    #[test]
    fn arg_summary_extracts_known_keys() {
        assert_eq!(
            arg_summary(&serde_json::json!({ "command": "ls -la" })),
            Some("ls -la".to_string())
        );
        assert_eq!(
            arg_summary(&serde_json::json!({ "pattern": "TODO" })),
            Some("TODO".to_string())
        );
        assert_eq!(arg_summary(&serde_json::json!({ "unknown": "x" })), None);
    }

    #[test]
    fn reload_is_idle_only_because_it_rebuilds_the_session() {
        assert!(IDLE_ONLY.contains(&"/reload"));
    }

    #[test]
    fn fork_is_idle_only_and_listed() {
        // /fork swaps the active session, so it must not run mid-stream…
        assert!(IDLE_ONLY.contains(&"/fork"));
        // …and it's offered in the slash menu.
        assert!(SLASH_COMMANDS.iter().any(|(name, _)| *name == "/fork"));
    }

    // ---- image preview (/ide + paste) ----

    #[test]
    fn image_path_detection() {
        assert!(is_image_path(std::path::Path::new("a.PNG")));
        assert!(is_image_path(std::path::Path::new("x/y.jpeg")));
        assert!(!is_image_path(std::path::Path::new("main.rs")));
        assert!(!is_image_path(std::path::Path::new("noext")));
    }

    #[test]
    fn half_block_render_packs_two_rows_and_colors() {
        // 6px tall image -> 3 half-block rows; each row is colored ▀ cells.
        let img = ::image::DynamicImage::ImageRgba8(::image::RgbaImage::from_pixel(
            4,
            6,
            ::image::Rgba([10, 20, 30, 255]),
        ));
        let lines = render_image_blocks(&img, 80, 40);
        assert_eq!(lines.len(), 3, "6px / 2 = 3 rows");
        assert!(lines[0].contains(''), "uses upper half-block");
        assert!(lines[0].contains("\x1b["), "carries ANSI color");
    }

    #[test]
    fn half_block_render_fits_within_bounds() {
        let img = ::image::DynamicImage::ImageRgba8(::image::RgbaImage::new(400, 400));
        let lines = render_image_blocks(&img, 20, 10);
        assert!(lines.len() <= 10, "never exceeds max_rows");
    }

    #[test]
    fn clipboard_helper_cleans_up_on_no_image() {
        // No way to guarantee an empty clipboard, but the helper must never
        // leave a stray empty file behind when it fails.
        let dest = std::env::temp_dir().join("a3s-test-noimg.png");
        let _ = std::fs::remove_file(&dest);
        let ok = clipboard_image_to(&dest);
        if !ok {
            assert!(!dest.exists(), "failed paste leaves no file");
        } else {
            let _ = std::fs::remove_file(&dest);
        }
    }

    // ---- /ide editor cursor math (multi-byte safe) ----

    #[test]
    fn char_byte_handles_ascii_and_cjk() {
        assert_eq!(char_byte("hello", 0), 0);
        assert_eq!(char_byte("hello", 3), 3);
        assert_eq!(char_byte("hello", 5), 5); // past end clamps to len
                                              // CJK chars are 3 bytes each in UTF-8; cursor index 1 -> byte 3.
        assert_eq!(char_byte("你好", 1), 3);
        assert_eq!(char_byte("你好", 2), 6);
    }

    #[test]
    fn char_byte_supports_inplace_edits() {
        // Mirrors the /ide insert path: insert a CJK char mid-string by char idx.
        let mut s = String::from("ab");
        let b = char_byte(&s, 1);
        s.insert(b, '');
        assert_eq!(s, "a中b");
    }

    // ---- config + skills ----

    #[test]
    fn starter_config_template_parses() {
        // First-launch generates this — it must be valid ACL with a usable model.
        let p = std::env::temp_dir().join("a3s-template-test.acl");
        std::fs::write(&p, config_template()).unwrap();
        let cfg = a3s_code_core::config::CodeConfig::from_file(&p)
            .expect("starter template must parse as valid ACL");
        let models: Vec<_> = cfg.list_models().into_iter().collect();
        assert!(!models.is_empty(), "template defines at least one model");
        let _ = std::fs::remove_file(&p);
    }

    #[test]
    fn counts_skill_dirs_and_flat_md() {
        let base = std::env::temp_dir().join("a3s-skillcount-test");
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(base.join("myskill")).unwrap();
        std::fs::write(base.join("myskill/SKILL.md"), "# skill").unwrap();
        std::fs::write(base.join("flat.md"), "# flat skill").unwrap();
        std::fs::write(base.join("notes.txt"), "ignored").unwrap();
        assert_eq!(count_skill_files(std::slice::from_ref(&base)), 2);
        let _ = std::fs::remove_dir_all(&base);
    }
}