a3s 0.7.4

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
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
//! 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, HashMap, HashSet, VecDeque};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

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, ToolCallResult,
};
use a3s_tui::cmd::{self, Cmd};
use a3s_tui::components::textarea::TextareaMsg;
use a3s_tui::components::viewport::ViewportMsg;
use a3s_tui::components::{
    Alert, AlertKind, ChoicePrompt, ChoicePromptMsg, InlineAction, Scrollbar, SessionStatusChip,
    Spinner, Textarea, Toast, ToastKind, ToolLogRecord as TuiToolLogRecord, ToolLogStatus,
    Viewport,
};
use a3s_tui::event::{KeyEvent, MouseEvent};
use a3s_tui::keymap::{KeyBinding, Keymap};
use a3s_tui::layout::{Constraint, Layout};
use a3s_tui::style::{Color, Style};
use a3s_tui::{
    AgentChrome, Event, KeyCode, KeyModifiers, Model, ProgramBuilder, Theme as TuiTheme,
};
use tokio::sync::{mpsc, Mutex};

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

// Team digital assets.
#[path = "assets/clone.rs"]
mod asset_clone;
#[path = "assets/lifecycle.rs"]
mod asset_lifecycle;
#[path = "assets/naming.rs"]
mod asset_naming;
#[path = "code_cli.rs"]
mod code_cli;
#[path = "code_serve.rs"]
mod code_serve;
pub(crate) use code_cli::{is_code_cli_command, run_code_cli};

// System configuration and integrations.
#[path = "system/config.rs"]
mod config;
#[path = "system/skills.rs"]
pub(crate) mod skills;
#[path = "system/update.rs"]
mod update;

// Local workspace.
#[path = "workspace/gitutil.rs"]
mod gitutil;

// Local and shared knowledge.
#[path = "knowledge/kbutil.rs"]
mod kbutil;

// Context and memory.
#[path = "context/memutil.rs"]
mod memutil;

// OS Runtime bridge.
#[path = "os/progressive.rs"]
mod os_progressive;
#[path = "os/remote_ui.rs"]
mod remote_ui;
#[path = "os/runtime_policy.rs"]
mod runtime_policy;
mod runtime_projection;

// Terminal UI support.
#[path = "ui/design_markdown.rs"]
mod design_markdown;
#[path = "ui/image.rs"]
mod image;
#[path = "ui/render.rs"]
mod render;
#[path = "ui/syntax.rs"]
mod syntax;
#[path = "ui/util.rs"]
mod util;

mod panels;
use asset_naming::*;
use config::*;
use design_markdown::StreamingMarkdown;
use gitutil::*;
use image::*;
use memutil::*;
use render::*;
use runtime_policy::RuntimePolicy;
use runtime_projection::{RuntimeProjection, ToolCallRecord};
use skills::*;
use syntax::*;
use update::*;
use util::*;

const HITL_CONFIRM_TIMEOUT_MS: u64 = 60 * 60 * 1000;
const BACKGROUND_CONFIRM_TIMEOUT_MS: u64 = 500;
const TOOL_EXEC_TIMEOUT_MS: u64 = 30 * 60 * 1000;

/// Terminal-safe mapping of the DESIGN.md Geist/Vercel palette.
const ACCENT: Color = Color::Rgb(0, 112, 243); // link / active / success
const TN_GREEN: Color = ACCENT; // compatibility alias: success maps to blue
const TN_YELLOW: Color = Color::Rgb(245, 166, 35); // warning
const TN_RED: Color = Color::Rgb(238, 0, 0); // error / destructive
const TN_CYAN: Color = Color::Rgb(80, 227, 194); // sparse accent
const TN_ORANGE: Color = Color::Rgb(249, 203, 40); // ship gradient amber
const TN_PURPLE: Color = Color::Rgb(151, 71, 255); // lifted preview violet
const TN_FG: Color = Color::Rgb(237, 237, 237); // primary text on dark terminals
const TN_GRAY: Color = Color::Rgb(143, 143, 143); // muted text
const SURFACE_SOFT: Color = Color::Rgb(31, 31, 31);
const SURFACE_SELECTED: Color = Color::Rgb(7, 49, 108);
const GRADIENT_DEVELOP_START: Color = Color::Rgb(0, 124, 240);
const GRADIENT_DEVELOP_END: Color = Color::Rgb(0, 223, 216);
const GRADIENT_PREVIEW_START: Color = TN_PURPLE;
const GRADIENT_PREVIEW_END: Color = Color::Rgb(255, 0, 128);
const GRADIENT_SHIP_START: Color = Color::Rgb(255, 77, 77);
const GRADIENT_SHIP_END: Color = Color::Rgb(249, 203, 40);
const BRAND_GRADIENT: [Color; 6] = [
    GRADIENT_DEVELOP_START,
    GRADIENT_DEVELOP_END,
    GRADIENT_PREVIEW_START,
    GRADIENT_PREVIEW_END,
    GRADIENT_SHIP_START,
    GRADIENT_SHIP_END,
];

fn agent_chrome_theme() -> TuiTheme {
    TuiTheme {
        primary: ACCENT,
        secondary: TN_CYAN,
        bg: Color::Black,
        fg: TN_FG,
        muted: TN_GRAY,
        border: TN_GRAY,
        success: TN_GREEN,
        warning: TN_ORANGE,
        error: TN_RED,
        info: TN_CYAN,
        surface: SURFACE_SOFT,
        highlight: SURFACE_SELECTED,
    }
}

fn agent_chrome(theme: &TuiTheme) -> AgentChrome<'_> {
    AgentChrome::new(theme)
}

/// 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 Open view button. \
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 `Open view` button that opens the authenticated progressive 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 (Geist Dark …)"),
    (
        "/flow",
        "select a workflow asset → OS Workflow as a Service designer (needs /login) · /flow <text> drafts one",
    ),
    (
        "/agent",
        "select an agent definition → local dev · Agent as a Service or Function as a Service by kind",
    ),
    (
        "/mcp",
        "select an MCP server asset → local dev · publish/debug/test via OS Function as a Service",
    ),
    (
        "/skill",
        "select a skill asset → local dev · publish/deploy via OS Function as a Service",
    ),
    (
        "/okf",
        "select an OKF package → local dev · publish/deploy via OS Knowledge service",
    ),
    (
        "/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", "inspect local agent process activity"),
    ("/ide", "superfile-style file browser + editor"),
    (
        "/memory",
        "browse memory as an event/entity graph with tiers and forget candidates",
    ),
    (
        "/kb",
        "open the local personal knowledge base · add/import/search/vault",
    ),
    (
        "/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",
        "engineered loop dashboard · agent-aware in /agent mode · /loop <task> quick loop",
    ),
    (
        "/sleep",
        "consolidate today's work into memory (experience · preferences · knowledge)",
    ),
    ("/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", "/reload", "/update", "/init",
    "/fork", "/sleep", "/flow", "/agent", "/mcp", "/skill", "/okf", "/kb",
];

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

fn slash_tail<'a>(input: &'a str, command: &str) -> Option<&'a str> {
    input
        .strip_prefix(command)
        .filter(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
}

fn os_asset_category_query(category: &str, query: &str) -> String {
    let query = query.trim();
    if query.is_empty() {
        format!("category:{category}")
    } else {
        format!("category:{category} {query}")
    }
}

fn runtime_asset_query(category: &str, asset_hint: &str, query: &str) -> String {
    let category = category.trim();
    let asset_hint = asset_hint.trim();
    let query = query.trim();
    let mut parts = Vec::new();
    if !category.is_empty() {
        parts.push(format!("category:{category}"));
    }
    if !asset_hint.is_empty() {
        parts.push(asset_hint.to_string());
    }
    if !query.is_empty() {
        parts.push(query.to_string());
    }
    parts.join(" ")
}

fn cancel_pending_picker<Panel, Pending>(
    picker: &mut Option<Panel>,
    pending: &mut Option<Pending>,
) {
    *picker = None;
    *pending = None;
}

fn os_required_message(cmd: &str, os_configured: bool) -> String {
    if os_configured {
        format!("  {cmd} needs OS — sign in with /login first")
    } else {
        format!("  {cmd} needs OS — configure `os = \"https://your-os-host\"` in config.acl, then /login")
    }
}

fn os_required_alert(cmd: &str, os_configured: bool) -> String {
    let body = os_required_message(cmd, os_configured)
        .trim_start()
        .to_string();
    format!(
        "  {}",
        Alert::new(AlertKind::Warning, body).color(TN_YELLOW).view()
    )
}

fn ide_flash_line(kind: ToastKind, message: impl Into<String>) -> String {
    let color = match kind {
        ToastKind::Info => TN_CYAN,
        ToastKind::Success => TN_GREEN,
        ToastKind::Warning => TN_YELLOW,
        ToastKind::Error => TN_RED,
    };
    Toast::new(kind, message).color(color).view()
}

/// 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 wide scripts are closer to ~1 token/char — so a flat `chars / 4`
/// under-counts them by 3-4x 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,
    }
}

fn ctx_limit_for_model(model_ctx: &std::collections::HashMap<String, u32>, model: &str) -> u32 {
    resolve_ctx_limit(
        model_ctx
            .get(model)
            .copied()
            .or_else(|| crate::codex::codex_model_context(model))
            .or_else(|| inferred_ctx_limit(model)),
    )
}

fn inferred_ctx_limit(model: &str) -> Option<u32> {
    let m = model.trim().to_ascii_lowercase();
    if let Some(limit) = context_suffix_limit(&m) {
        return Some(limit);
    }

    // Configured/gateway-reported limits win. These are only fallbacks for
    // account-backed picker models that do not come from config.acl.
    if m.contains("claude") {
        return Some(200_000);
    }
    if m.contains("gpt-5") || m.contains("gpt-4.1") {
        return Some(1_000_000);
    }
    if m.contains("o1") || m.contains("o3") || m.contains("o4") {
        return Some(200_000);
    }
    if m.contains("gpt-4o") || m.contains("gpt-4") || m.contains("glm") {
        return Some(DEFAULT_CONTEXT_LIMIT);
    }

    None
}

fn context_suffix_limit(model: &str) -> Option<u32> {
    if !model.ends_with(']') {
        return None;
    }
    let start = model.rfind('[')?;
    let suffix = model.get(start + 1..model.len().checked_sub(1)?)?;
    if suffix.is_empty() {
        return None;
    }
    let (number, scale) = suffix.split_at(suffix.len().saturating_sub(1));
    let base = number.parse::<u32>().ok()?;
    match scale {
        "k" => base.checked_mul(1_000),
        "m" => base.checked_mul(1_000_000),
        _ => suffix.parse::<u32>().ok(),
    }
}

/// 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 {
        "dynamic_workflow" => {
            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 captured".to_string(),
            ))
        }
        "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 captured".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 captured", tasks.len())
    } else {
        format!(
            "dynamic workflow · {} delegated task{} captured",
            tasks.len(),
            if tasks.len() == 1 { "" } else { "s" }
        )
    };
    Some((doc, label))
}

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

const TOP_HISTORY_LIMIT: usize = 32;

#[derive(Debug, Default)]
struct TopProcessHistory {
    samples: HashMap<u32, TopMetricHistory>,
}

impl TopProcessHistory {
    fn observe(&mut self, rows: &[ProcessRow]) {
        let live = rows.iter().map(|row| row.pid).collect::<HashSet<_>>();
        for row in rows {
            self.samples
                .entry(row.pid)
                .or_default()
                .push(row.cpu_pct, row.mem_pct);
        }
        self.samples.retain(|pid, _| live.contains(pid));
    }

    fn values(&self, pid: u32) -> (Vec<f32>, Vec<f32>) {
        self.samples
            .get(&pid)
            .map(TopMetricHistory::values)
            .unwrap_or_default()
    }

    fn clear(&mut self) {
        self.samples.clear();
    }
}

#[derive(Debug, Default)]
struct TopMetricHistory {
    cpu: VecDeque<f32>,
    mem: VecDeque<f32>,
}

impl TopMetricHistory {
    fn push(&mut self, cpu: f32, mem: f32) {
        push_top_history_value(&mut self.cpu, cpu);
        push_top_history_value(&mut self.mem, mem);
    }

    fn values(&self) -> (Vec<f32>, Vec<f32>) {
        (
            self.cpu.iter().copied().collect(),
            self.mem.iter().copied().collect(),
        )
    }
}

fn push_top_history_value(values: &mut VecDeque<f32>, value: f32) {
    values.push_back(value);
    while values.len() > TOP_HISTORY_LIMIT {
        values.pop_front();
    }
}

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

#[derive(Clone, PartialEq, Eq, Debug)]
enum IdePrompt {
    Search { forward: bool, text: String },
    Command(String),
}

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

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct PendingOp {
    op: char,
    count: usize,
}

#[derive(Clone, PartialEq, Eq, Debug)]
enum RepeatEdit {
    DeleteChar(usize),
    DeleteLine(usize),
    DeleteWord(usize),
    DeleteToEol,
    ChangeLine(usize),
    Replace(char),
    JoinLine(usize),
    ToggleCase(usize),
}

/// 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<PendingOp>,
    /// Normal-mode numeric prefix (`3j`, `5dd`, `2w`).
    count: Option<usize>,
    /// Undo snapshots (lines + cursor) for `u`; bounded — configs are small.
    undo: Vec<(Vec<String>, usize, usize)>,
    /// Redo snapshots for Ctrl+R.
    redo: Vec<(Vec<String>, usize, usize)>,
    /// Last repeatable Normal-mode change for `.`.
    last_change: Option<RepeatEdit>,
    /// Last search query and direction for `n` / `N`.
    search: Option<(String, bool)>,
    /// Visual Line anchor row (`V`).
    visual_line_anchor: Option<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,
            count: None,
            undo: Vec::new(),
            redo: Vec::new(),
            last_change: None,
            search: None,
            visual_line_anchor: None,
            clip: String::new(),
            clip_linewise: false,
        }
    }
}

/// Render the `/output` viewer body. It mirrors the main transcript's tool
/// vocabulary while staying plain-text for the read-only editor.
fn format_tool_log_records(records: &[ToolCallRecord], width: usize) -> Option<String> {
    if records.is_empty() {
        return None;
    }
    const OUTPUT_TAIL: usize = 24;

    let records = records
        .iter()
        .map(|rec| {
            let arg = rec
                .args
                .as_ref()
                .and_then(|args| arg_summary_for_tool(&rec.name, args))
                .unwrap_or_default();
            let action = if arg.is_empty() {
                tool_verb(&rec.name).to_string()
            } else {
                format!("{} {}", tool_verb(&rec.name), arg)
            };
            let status = if rec.exit_code == 0 {
                ToolLogStatus::Ok
            } else {
                ToolLogStatus::Exit(rec.exit_code)
            };
            let args = rec
                .args
                .as_ref()
                .map(serde_json::to_string)
                .transpose()
                .unwrap_or_default();
            let mut record = TuiToolLogRecord::new(action, status).output(rec.output.clone());
            if let Some(args) = args {
                record = record.args(args);
            }
            record
        })
        .collect::<Vec<_>>();

    let theme = agent_chrome_theme();
    let chrome = agent_chrome(&theme);
    Some(
        chrome
            .tool_log()
            .records(records)
            .max_output_lines_per_record(OUTPUT_TAIL)
            .view(width as u16, usize::MAX),
    )
}

/// PTC source used by the `?` deep-research workflow. The workflow function is
/// deterministic and only schedules work; side effects live in Flow steps.
fn deep_research_workflow_source() -> &'static str {
    r#"
async function run(ctx, inputs) {
  const input = inputs.input || {};
  const query = input.query || "";
  const tracks = Array.isArray(input.tracks) && input.tracks.length > 0
    ? input.tracks
    : [
        { title: "Facts and timeline", focus: "establish the current facts, dates, and key actors" },
        { title: "Primary sources", focus: "find official or primary-source evidence" },
        { title: "Independent analysis", focus: "compare reputable independent analysis and disagreements" },
        { title: "Risks and caveats", focus: "identify uncertainty, recency caveats, and weak claims" },
      ];
  const localTasks = () => tracks.map((track, index) => {
    const title = track.title || `Track ${index + 1}`;
    const focus = track.focus || String(track);
    return {
      agent: "general",
      description: `Research ${index + 1}: ${title}`,
      prompt: `Deep-research track for: ${query}\n\nFocus: ${focus}\n\nUse web_search and web_fetch. Return URLs, publication dates, key evidence, contradictions, and confidence notes.`
    };
  });

  if (inputs.kind === "workflow") {
    const runtimeResearch = inputs.step_outputs.runtime_research;
    const localResearch = inputs.step_outputs.local_research;
    const localFallback = inputs.step_outputs.local_fallback;

    if (localFallback) {
      return {
        type: "complete",
        output: {
          query,
          mode: "local_fallback",
          runtime_error: runtimeResearch && runtimeResearch.runtime_error,
          research: localFallback
        }
      };
    }

    if (localResearch) {
      return { type: "complete", output: { query, mode: "local_parallel_task", research: localResearch } };
    }

    if (runtimeResearch && !runtimeResearch.runtime_error) {
      return { type: "complete", output: { query, mode: "os_runtime", research: runtimeResearch } };
    }

    if (runtimeResearch && runtimeResearch.runtime_error) {
      return {
        type: "schedule_step",
        step_id: "local_fallback",
        step_name: "parallel_task",
        input: { tasks: localTasks() },
        retry: { max_attempts: 1, delay_ms: 0 },
      };
    }

    if (input.os_runtime) {
      return {
        type: "schedule_step",
        step_id: "runtime_research",
        step_name: "runtime_research",
        input: {
          query,
          worker: input.worker || "deep-research-worker",
          tracks,
        },
        retry: { max_attempts: 1, delay_ms: 0 },
      };
    }

    return {
      type: "schedule_step",
      step_id: "local_research",
      step_name: "parallel_task",
      input: { tasks: localTasks() },
      retry: { max_attempts: 1, delay_ms: 0 },
    };
  }

  if (inputs.kind === "step" && inputs.step_name === "runtime_research") {
    const result = await ctx.tool("runtime", {
      worker: inputs.input.worker,
      timeout_ms: 600000,
      tasks: inputs.input.tracks.map((track, index) => ({
        query: inputs.input.query,
        title: track.title || `Track ${index + 1}`,
        focus: track.focus || String(track),
        requirements: "Use web search and full-page reads. Return URLs, dates, key evidence, contradictions, and confidence notes."
      }))
    });
    if (!result || result.exitCode !== 0) {
      return {
        runtime_error: (result && result.output) || "runtime tool failed",
        runtime_result: result || null
      };
    }
    return { mode: "os_runtime", runtime: result };
  }

  return { error: `unknown dynamic workflow invocation: ${inputs.kind}/${inputs.step_name || ""}` };
}
"#
}

/// The directive sent to the agent for a `?` deep-research turn: decompose the
/// question, run the evidence fan-out through DynamicWorkflowRuntime, then
/// cross-check and synthesize a cited report. When OS is signed in, the Flow step
/// may call the login-gated A3S Runtime `runtime` tool and publish RemoteUI.
#[cfg(test)]
fn deep_research_prompt(query: &str, os_runtime: bool) -> String {
    let tracks_directive = if os_runtime {
        format!(
            "OS runtime is available. The DynamicWorkflowRuntime step may call \
         the login-gated `runtime` tool, so set `os_runtime: true` in the \
         workflow input and include `allowed_tools: [\"runtime\"]`. Split the \
         query into 4-8 independent research tracks before the call. Do not do \
         all source gathering serially. After merging the tracks, create both a \
         Markdown report and a standalone HTML page, then use the OS progressive \
         UI/RemoteUI path (shaped response with `.view`/`viewUrl`) so the TUI can \
         show the user a one-click view. Runtime evidence must include \
         `dynamic_workflow` and the report view. Do not print a raw authenticated \
         URL; summarize and let the host surface the RemoteUI view. {}",
            RuntimePolicy::Required.directive()
        )
    } else {
        "OS runtime is not available in this session. Set `os_runtime: false`; \
         the DynamicWorkflowRuntime script will schedule a host-side \
         `parallel_task` step for local subagent fan-out because PTC itself \
         cannot call `parallel_task`. Still create a Markdown report and \
         standalone HTML page under `.a3s/research/<slug>/`, and tell the user \
         the local paths. Do not claim a RemoteUI view was created without an OS \
         view response."
            .to_string()
    };
    let source = deep_research_workflow_source();
    format!(
        "Conduct deep research to answer the query below. Be thorough.\n\n\
         Required execution path:\n\
         1. First call `dynamic_workflow` with the JavaScript source below. \
         The workflow must gather evidence through Flow before final synthesis.\n\
         2. Provide `input.query` and 4-8 `input.tracks` with `title` and `focus`. \
         {tracks_directive}\n\
         3. After `dynamic_workflow` returns, read the evidence, cross-check \
         claims across independent sources, call out disagreements and recency \
         caveats, then synthesize a comprehensive answer with inline citations.\n\
         4. Produce a final \"Sources\" list of URLs used and clear links to \
         report artifacts/view.\n\n\
         Dynamic workflow source:\n\
         ```javascript\n{source}\n```\n\n\
         Query: {query}"
    )
}

fn deep_research_workflow_args(query: &str, os_runtime: bool) -> serde_json::Value {
    let allowed_tools = if os_runtime {
        serde_json::json!(["runtime"])
    } else {
        serde_json::json!([])
    };
    serde_json::json!({
        "source": deep_research_workflow_source(),
        "input": {
            "query": query,
            "os_runtime": os_runtime,
        },
        "allowed_tools": allowed_tools,
        "limits": {
            "timeoutMs": 900000,
            "maxToolCalls": 8,
            "maxOutputBytes": 262144
        }
    })
}

fn deep_research_synthesis_prompt(
    query: &str,
    os_runtime: bool,
    workflow_output: &str,
    workflow_metadata: Option<&serde_json::Value>,
) -> String {
    let remoteui_directive = if os_runtime {
        format!(
            "OS is signed in. Use the OS progressive UI/RemoteUI path with \
             shaped:true so the TUI can surface a `.view` or `viewUrl` for the \
             final report. {}",
            RuntimePolicy::Required.directive()
        )
    } else {
        "OS runtime is not available. Create a Markdown report and standalone HTML \
         page under `.a3s/research/<slug>/`, and provide local paths."
            .to_string()
    };
    let metadata = workflow_metadata
        .and_then(|metadata| serde_json::to_string_pretty(metadata).ok())
        .unwrap_or_else(|| "{}".to_string());
    format!(
        "Synthesize the deep-research answer for the query below.\n\n\
         A host-controlled DynamicWorkflowRuntime run has already gathered the \
         research evidence. Do not call `dynamic_workflow` again. Use the workflow \
         evidence below, cross-check claims, call out disagreements and recency \
         caveats, and write a comprehensive answer with inline citations and a \
         final Sources list. If the workflow output reports a `runtime_error` and \
         `mode: \"local_fallback\"`, clearly mention that OS Runtime was attempted \
         and local parallel research was used as the fallback.\n\n\
         {remoteui_directive}\n\n\
         Query:\n{query}\n\n\
         DynamicWorkflowRuntime output:\n```json\n{workflow_output}\n```\n\n\
         DynamicWorkflowRuntime metadata:\n```json\n{metadata}\n```"
    )
}

fn deep_research_recovery_prompt(
    query: &str,
    os_runtime: bool,
    workflow_error: &str,
    workflow_metadata: Option<&serde_json::Value>,
) -> String {
    let recovery_path = if os_runtime {
        format!(
            "OS is signed in. The host-controlled workflow already attempted the \
             runtime path and failed before usable evidence was gathered. Recover by \
             using the signed-in `runtime` tool directly if it is available; if the \
             runtime worker or endpoint is unavailable, fall back to local web_search \
             and web_fetch and explicitly explain the OS Runtime failure. {}",
            RuntimePolicy::Required.directive()
        )
    } else {
        "OS runtime is not available. Recover with local web_search/web_fetch and \
         local artifacts under `.a3s/research/<slug>/`."
            .to_string()
    };
    let metadata = workflow_metadata
        .and_then(|metadata| serde_json::to_string_pretty(metadata).ok())
        .unwrap_or_else(|| "{}".to_string());
    format!(
        "Recover and complete the deep-research task for the query below.\n\n\
         The host-controlled DynamicWorkflowRuntime preflight failed. Do not call \
         `dynamic_workflow` again in this recovery turn. {recovery_path}\n\n\
         Query:\n{query}\n\n\
         DynamicWorkflowRuntime error:\n```text\n{workflow_error}\n```\n\n\
         DynamicWorkflowRuntime metadata:\n```json\n{metadata}\n```\n\n\
         Deliver a comprehensive answer with inline citations, a final Sources \
         list, and report artifacts/view as appropriate."
    )
}

fn json_contains_tool_evidence(value: &serde_json::Value, tool: &str) -> bool {
    match value {
        serde_json::Value::Object(map) => map.iter().any(|(key, value)| {
            ((key == "name" || key == "tool" || key == "tool_name") && value.as_str() == Some(tool))
                || json_contains_tool_evidence(value, tool)
        }),
        serde_json::Value::Array(items) => items
            .iter()
            .any(|item| json_contains_tool_evidence(item, tool)),
        _ => false,
    }
}

/// 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 the shared one-column vertical scrollbar to the viewport's visible
/// rows. The viewport is sized to `inner_width` (= screen width - 1, see
/// `relayout`) so the bar never clips content, and the gutter stays blank when
/// nothing overflows the window.
fn append_scrollbar(view: &str, inner_width: usize, total: usize, scroll_percent: u8) -> String {
    let visible = view.split('\n').count();
    Scrollbar::from_scroll_percent(total, visible, scroll_percent)
        .track_color(TN_GRAY)
        .thumb_color(ACCENT)
        .hide_when_not_overflowing(true)
        .append_to_view(view, inner_width)
}

/// 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 styled button is still transcript
/// text, so ANSI stripping keeps this marker clickable.
const VIEW_BUTTON_MARKER: &str = "Open view";
const VIEW_BUTTON_CLICK_DRIFT_COLS: u16 = 2;

fn remote_view_button(detail: &str) -> String {
    InlineAction::new(VIEW_BUTTON_MARKER)
        .icon("")
        .colors(Color::BrightWhite, ACCENT)
        .detail_color(TN_GRAY)
        .detail(detail)
        .view()
}

/// 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 = SURFACE_SELECTED;

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

fn viewport_mouse_cell(
    row: u16,
    column: u16,
    viewport_rows: usize,
    max_col: u16,
) -> Option<(u16, u16)> {
    if viewport_rows == 0 || row as usize >= viewport_rows {
        None
    } else {
        Some((row, column.min(max_col)))
    }
}

fn viewport_mouse_cell_clamped(
    row: u16,
    column: u16,
    viewport_rows: usize,
    max_col: u16,
) -> Option<(u16, u16)> {
    if viewport_rows == 0 {
        None
    } else {
        Some((
            row.min(viewport_rows.saturating_sub(1) as u16),
            column.min(max_col),
        ))
    }
}

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

fn viewport_row_contains_view_button(view: &str, row: u16) -> bool {
    view.split('\n')
        .nth(row as usize)
        .map(a3s_tui::style::strip_ansi)
        .is_some_and(|line| line.to_ascii_lowercase().contains("open view"))
}

fn is_remote_view_click(view: &str, selection: Selection) -> bool {
    selection.anchor.0 == selection.head.0
        && selection.anchor.1.abs_diff(selection.head.1) <= VIEW_BUTTON_CLICK_DRIFT_COLS
        && viewport_row_contains_view_button(view, selection.anchor.0)
}

fn is_quit_key(key: &KeyEvent) -> bool {
    key.modifiers.contains(KeyModifiers::CONTROL)
        && matches!(key.code, KeyCode::Char(c) if c.eq_ignore_ascii_case(&'c'))
}

fn quit_is_confirmed(armed: Option<Instant>, now: Instant) -> bool {
    armed.is_some_and(|t| now.saturating_duration_since(t) < Duration::from_secs(2))
}

/// 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>)>,
    /// Active command prompt inside the editor footer (`/`, `?`, `:`).
    prompt: Option<IdePrompt>,
    /// `/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>,
    /// Selected action in the `/kb` delete confirmation row (`true` = delete).
    delete_confirm_yes: bool,
}

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,
            prompt: None,
            kb_root: None,
            armed_delete: None,
            delete_confirm_yes: true,
        }
    }
}

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

fn viewport_content_width_for(width: u16) -> usize {
    (width as usize).saturating_sub(1)
}

fn transcript_markdown_width_for(width: u16) -> usize {
    viewport_content_width_for(width).saturating_sub(PAD + 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 has DynamicWorkflowRuntime guidance; local fan-out
/// uses host-side `parallel_task` steps when the work truly splits.
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 choosing 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 A3S Flow records dynamic workflow progress and PTC steps.
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 needs a dynamic workflow, call the \
`dynamic_workflow` tool with one sandboxed JavaScript PTC workflow script. In \
that script, return A3S Flow commands for workflow replay. Use PTC `ctx` tools \
inside ordinary steps (`ctx.read`, `ctx.grep`, `ctx.tool(\"runtime\", ...)` when \
the login-gated runtime tool exists). For local parallel subagent fan-out, \
schedule a Flow step with `step_name: \"parallel_task\"`; do not call \
`parallel_task` from PTC. Keep child prompts bounded and evidence-oriented, then \
synthesize results before completing the workflow.";

/// 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,
    display: String,
    runtime_expectation: Option<RuntimeExpectation>,
    deep_research: Option<(String, bool)>,
}

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>>>;
type StreamJoin = tokio::task::JoinHandle<()>;

#[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, StreamJoin),
    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),
    /// Host-controlled `?` deep-research workflow finished; next step is synthesis.
    DeepResearchWorkflowCompleted {
        query: String,
        os_runtime: bool,
        args: serde_json::Value,
        result: Result<ToolCallResult, String>,
    },
    /// `/update` version check finished: the latest version tag, if reachable.
    UpdatePlan(Option<String>),
    /// `/update` found no binary upgrade was needed and repaired companion tools.
    UpdateRepair(Result<Vec<String>, 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,
    /// `/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>),
    /// `/memory` graph data loaded (timeline + details + derived graph).
    MemoryLoaded(MemPanelData),
    /// A `/memory` forget-candidate deletion finished, with fresh graph data.
    MemoryForgotten(Result<(String, MemPanelData), String>),
    /// Asset-scoped OS asset list loaded.
    AssetListLoaded(Result<panels::asset_resources::AssetListFetch, String>),
    /// Runtime activity rows loaded for an asset-scoped activity panel.
    RuntimeActivityLoaded(Result<panels::asset_resources::RuntimeActivityFetch, String>),
    /// `/kb import` 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` published/opened/inspected an OS Workflow as a Service asset.
    FlowOsCompleted(Result<panels::flow::FlowOsResult, String>),
    /// `/agent` published/opened an OS agent asset through Agent as a Service or Function as a Service.
    AgentOsCompleted(Result<panels::agent::AgentOsResult, String>),
    /// `/mcp` published/debugged/tested an OS Function as a Service MCP asset.
    McpOsCompleted(Result<panels::mcp::McpOsResult, String>),
    /// `/skill` published/deployed/inspected an OS Function as a Service skill asset.
    SkillOsCompleted(Result<panels::skill::SkillOsResult, String>),
    /// `/okf` published/deployed an OS Knowledge service package asset.
    OkfOsCompleted(Result<panels::okf::OkfOsResult, String>),
    /// Asset source was cloned into the local asset workspace.
    AssetCloned(Result<asset_clone::AssetCloneResult, 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 as a global graceful quit key.
        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)
}

fn resume_after_pending_confirmation_cmd(rx: Option<SharedRx>) -> Cmd<Msg> {
    let mut cmds = vec![spinner_tick()];
    if let Some(rx) = rx {
        cmds.push(pump(rx));
    }
    cmd::batch(cmds)
}

/// 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 tui_session_options(confirmation: a3s_code_core::hitl::ConfirmationPolicy) -> SessionOptions {
    SessionOptions::new()
        .with_confirmation_policy(confirmation)
        .with_permission_policy(tui_permission_policy())
        .with_tool_timeout(TOOL_EXEC_TIMEOUT_MS)
}

/// Core permission policy for the TUI: keep research/read tools unblocked even
/// when dynamic workflows or child runs bypass the UI auto-approval helper.
fn tui_permission_policy() -> a3s_code_core::permissions::PermissionPolicy {
    a3s_code_core::permissions::PermissionPolicy::new().allow_all(&[
        "Read(*)",
        "Grep(*)",
        "Glob(*)",
        "LS(*)",
        "read(*)",
        "grep(*)",
        "glob(*)",
        "ls(*)",
        "web_search(*)",
        "web_fetch(*)",
    ])
}

fn instant_from_epoch_ms(epoch_ms: u64) -> Instant {
    let now = Instant::now();
    if epoch_ms == 0 {
        return now;
    }
    let wall_now_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis() as u64)
        .unwrap_or(epoch_ms);
    let age_ms = wall_now_ms.saturating_sub(epoch_ms);
    now.checked_sub(Duration::from_millis(age_ms))
        .unwrap_or(now)
}

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

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RuntimeEvidenceMode {
    Any,
    ParallelReportView,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct RuntimeExpectation {
    label: String,
    policy: RuntimePolicy,
    evidence_mode: RuntimeEvidenceMode,
    runtime_tool: bool,
    parallel_work: bool,
    remote_view: bool,
    warned_missing: bool,
}

impl RuntimeExpectation {
    fn required(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            policy: RuntimePolicy::Required,
            evidence_mode: RuntimeEvidenceMode::Any,
            runtime_tool: false,
            parallel_work: false,
            remote_view: false,
            warned_missing: false,
        }
    }

    fn required_report_view(label: impl Into<String>) -> Self {
        Self {
            evidence_mode: RuntimeEvidenceMode::ParallelReportView,
            ..Self::required(label)
        }
    }

    fn record_tool(&mut self, name: &str) {
        match name {
            "runtime" => self.runtime_tool = true,
            "dynamic_workflow" | "parallel_task" | "task" => self.parallel_work = true,
            _ => {}
        }
    }

    fn record_parallel_work(&mut self) {
        self.parallel_work = true;
    }

    fn record_remote_view(&mut self) {
        self.remote_view = true;
    }

    fn has_parallel_evidence(&self) -> bool {
        self.runtime_tool || self.parallel_work
    }

    fn is_satisfied(&self) -> bool {
        match self.evidence_mode {
            RuntimeEvidenceMode::Any => self.has_parallel_evidence() || self.remote_view,
            RuntimeEvidenceMode::ParallelReportView => {
                self.has_parallel_evidence() && self.remote_view
            }
        }
    }

    fn missing_expectation(&self) -> String {
        match self.evidence_mode {
            RuntimeEvidenceMode::Any => {
                "expected `dynamic_workflow`, `runtime`, `parallel_task`, or an OS shaped `.view`/`viewUrl` response"
                    .to_string()
            }
            RuntimeEvidenceMode::ParallelReportView => match (self.has_parallel_evidence(), self.remote_view) {
                (false, false) => {
                    "expected `dynamic_workflow`/OS Runtime/`parallel_task` fan-out plus an OS shaped `.view`/`viewUrl` report response".to_string()
                }
                (false, true) => {
                    "expected `dynamic_workflow`/OS Runtime/`parallel_task` fan-out before the report view".to_string()
                }
                (true, false) => {
                    "expected an OS shaped `.view`/`viewUrl` response for the report".to_string()
                }
                (true, true) => unreachable!("satisfied expectations are filtered before warning"),
            },
        }
    }

    fn missing_warning(&mut self) -> Option<String> {
        if self.policy != RuntimePolicy::Required || self.is_satisfied() || self.warned_missing {
            return None;
        }
        self.warned_missing = true;
        Some(format!(
            "  Runtime evidence missing for {} - {} before the final answer",
            self.label,
            self.missing_expectation()
        ))
    }

    fn corrective_prompt(&self) -> Option<String> {
        if self.policy != RuntimePolicy::Required || self.is_satisfied() {
            return None;
        }
        Some(format!(
            "The previous turn ended without the required OS Runtime evidence for {}: {}. \
             Continue the same task, explicitly use `dynamic_workflow` first; inside it use \
             the signed-in `runtime` tool or a host-side `parallel_task` step as required, \
             create or surface the shaped OS `.view`/`viewUrl` report response when required, \
             and only then give the final answer. If the OS capability is unavailable, explain exactly \
             which OS endpoint or response field is missing and provide local report artifact paths.",
            self.label,
            self.missing_expectation()
        ))
    }
}

fn is_new_remote_view(last_view: Option<&remote_ui::ViewSpec>, spec: &remote_ui::ViewSpec) -> bool {
    last_view != Some(spec)
}

fn take_pending_tool_label(
    pending_tool: &mut Option<(String, String)>,
    tool_id: &str,
) -> Option<String> {
    if pending_tool
        .as_ref()
        .is_some_and(|(pending_id, _)| pending_id == tool_id)
    {
        pending_tool.take().map(|(_, label)| label)
    } else {
        None
    }
}

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. Generic tool views are opened by
    /// `/view` or clicking the inline "Open view" button; owned workflows like
    /// `/flow` may also open their prepared designer view directly.
    last_view: Option<remote_ui::ViewSpec>,
    /// Required Runtime use for the current autonomous workflow, plus observed
    /// evidence from tool/subagent/view events.
    runtime_expectation: Option<RuntimeExpectation>,
    /// 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>,
    /// 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,
    /// True from an asset-scoped review 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 asset-review report (issues + checkbox state). Survives the
    /// panel closing so a follow-up asset review can reopen it.
    review: Option<panels::review::ReviewState>,
    /// `/flow` DAG picker (login-gated); open when `Some`.
    flow: Option<panels::flow::FlowPanel>,
    /// A `/flow <action>` submitted before a flow was selected; run after selection.
    pending_flow_subcommand: Option<panels::flow::FlowSubcommand>,
    /// `/agent` definition picker; open when `Some`.
    agent_picker: Option<panels::agent::AgentPanel>,
    /// A `/agent <action>` submitted before an agent was active; run after selection.
    pending_agent_subcommand: Option<panels::agent::AgentSubcommand>,
    /// The local agent currently being developed by ordinary user turns.
    agent_dev: Option<panels::agent::AgentDevSession>,
    /// `/mcp` asset selector; open when `Some`.
    mcp_picker: Option<panels::mcp::McpPanel>,
    /// A `/mcp <action>` submitted before an MCP was active; run after selection.
    pending_mcp_subcommand: Option<panels::mcp::McpSubcommand>,
    /// The local MCP asset currently being developed by ordinary user turns.
    mcp_dev: Option<panels::mcp::McpDevSession>,
    /// `/skill` picker; open when `Some`.
    skill_picker: Option<panels::skill::SkillPanel>,
    /// A `/skill <action>` submitted before a skill was active; run after selection.
    pending_skill_subcommand: Option<panels::skill::SkillSubcommand>,
    /// The local skill currently being developed by ordinary user turns.
    skill_dev: Option<panels::skill::SkillDevSession>,
    /// `/okf` OKF package picker; open when `Some`.
    okf_picker: Option<panels::okf::OkfPackagePanel>,
    /// A `/okf <action>` submitted before an OKF package was active; run after selection.
    pending_okf_subcommand: Option<panels::okf::OkfCommand>,
    /// The local OKF package currently being developed by ordinary user turns.
    okf_dev: Option<panels::okf::OkfDevSession>,
    /// 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 dynamic workflow or task dispatch),
    /// retained for synthesis and shown collapsed in the transcript.
    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,
    /// ECS-style projection of live runtime entities (tools/subagents) plus
    /// completed tool-call records used by `/output`.
    runtime: RuntimeProjection,
    /// 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 brand-gradient flourish on the input border when ultracode is picked.
    gradient_until: Option<Instant>,
    gradient_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>,
    stream_join: Option<StreamJoin>,
    /// True while `rx` is carrying host-direct tool progress rather than an
    /// agent stream; channel close must not finish the turn.
    host_progress_inflight: bool,
    interrupting: bool,
    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,
    /// When the current run started, for the live elapsed-time indicator.
    stream_started: Option<Instant>,
    /// 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_history: TopProcessHistory,
    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>,
    /// `/ide` file-tree + viewer panel (Some when open).
    ide: Option<Ide>,
    /// `/memory` full-screen timeline panel (Some when open).
    memory: Option<MemPanel>,
    /// Asset-scoped OS digital-asset browser.
    asset_list: Option<panels::asset_resources::AssetListPanel>,
    /// Asset-scoped OS Runtime activity panel.
    runtime_activity: Option<panels::asset_resources::RuntimeActivityPanel>,
    /// `/kb` full-screen local personal knowledge-base panel (Some when open).
    kb: Option<panels::kb::KbPanel>,
    /// `/loop` engineered loop dashboard (Some when open).
    loop_panel: Option<panels::loop_engineering::LoopPanel>,
    /// `/help` overlay panel is showing.
    help_open: bool,
    /// Scroll offset inside the `/help` overlay.
    help_scroll: usize,
    /// 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 `/plugin` (persisted, hidden from `/`).
    disabled_skills: std::collections::HashSet<String>,
    /// `/plugin` 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);
    }

    pub(crate) fn viewport_content_width(&self) -> usize {
        viewport_content_width_for(self.width)
    }

    fn transcript_markdown_width(&self) -> usize {
        transcript_markdown_width_for(self.width)
    }
}

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(self.transcript_markdown_width());
                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();
                if self.ide.is_some() {
                    self.ide_paste_text(&text);
                    return None;
                }
                self.textarea.insert_str(&text);
                self.relayout();
            }

            Msg::Term(Event::Key(key)) => {
                self.last_activity = Instant::now();
                self.auto_reviewed = false;
                // Any keypress dismisses the copy highlight.
                self.selection = None;
                // Ctrl+C is a global quit key. Keep it before panels, approval
                // prompts, and streaming handlers so terminal variants cannot
                // route it into hidden input instead of exiting.
                if is_quit_key(&key) {
                    let now = Instant::now();
                    if quit_is_confirmed(self.quit_armed, now) {
                        return Some(cmd::quit());
                    }
                    self.quit_armed = Some(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 owns its own close + scroll keys.
                if self.help_open {
                    return self.handle_help_key(&key);
                }
                // /memory panel takes all keys while open.
                if self.memory.is_some() {
                    return self.memory_key(&key);
                }
                // Asset resource panels take all keys while open.
                if self.asset_list.is_some() {
                    return self.handle_asset_list_key(&key);
                }
                if self.runtime_activity.is_some() {
                    return self.handle_runtime_activity_key(&key);
                }
                // /kb panel takes all keys while open; an approval prompt
                // still overlays it and must get the keys first.
                if self.kb.is_some() {
                    if self.state == State::Awaiting {
                        return self.handle_approval_key(&key);
                    }
                    return self.handle_kb_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;
                }
                // /top panel takes keys while open.
                if self.top.is_some() {
                    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;
                                self.top_history.clear();
                            }
                        }
                        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;
                                }
                            }
                        }
                        _ => {}
                    }
                    // 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.confirm_effort_selection(sel);
                        }
                        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 => self.apply_theme_selection(sel),
                        KeyCode::Esc => self.theme_panel = None,
                        _ => {}
                    }
                    return None;
                }
                // /plugin 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(' ') => {
                            self.toggle_plugin_skill(sel.min(last));
                        }
                        KeyCode::Esc => self.plugins_panel = None,
                        _ => {}
                    }
                    return None;
                }
                // Asset review issue checklist: consume EVERY key while open.
                if self.review_open {
                    return self.handle_review_key(&key);
                }
                // `/flow` DAG picker: same.
                if self.flow.is_some() {
                    return self.handle_flow_key(&key);
                }
                // `/agent` definition picker: same.
                if self.agent_picker.is_some() {
                    return self.handle_agent_key(&key);
                }
                // `/mcp` asset selector: same.
                if self.mcp_picker.is_some() {
                    return self.handle_mcp_key(&key);
                }
                if self.skill_picker.is_some() {
                    return self.handle_skill_key(&key);
                }
                if self.okf_picker.is_some() {
                    return self.handle_okf_package_key(&key);
                }
                // `/loop` engineered-loop dashboard: same.
                if self.loop_panel.is_some() {
                    return self.handle_loop_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 mode first (discarding the
                // partial input), taking priority over the streaming interrupt
                // below.
                if (self.shell_mode || self.research_mode) && key.code == KeyCode::Esc {
                    self.shell_mode = false;
                    self.research_mode = false;
                    self.textarea.clear();
                    return None;
                }
                // Esc interrupts the in-progress run (input stays usable otherwise).
                if self.state == State::Streaming && key.code == KeyCode::Esc {
                    if self.interrupting {
                        return None;
                    }
                    self.interrupting = true;
                    self.push_line(&Style::new().fg(TN_YELLOW).render("  ⎋ interrupting…"));
                    let session = self.session.clone();
                    let join = self.stream_join.take();
                    return Some(cmd::cmd(move || async move {
                        session.cancel().await;
                        if let Some(join) = join {
                            let _ = join.await;
                        }
                        Msg::Interrupted
                    }));
                }
                if self.state == State::Idle && self.agent_dev.is_some() && key.code == KeyCode::Esc
                {
                    self.exit_agent_dev();
                    return None;
                }
                if self.state == State::Idle && self.mcp_dev.is_some() && key.code == KeyCode::Esc {
                    self.exit_mcp_dev();
                    return None;
                }
                if self.state == State::Idle && self.skill_dev.is_some() && key.code == KeyCode::Esc
                {
                    self.exit_skill_dev();
                    return None;
                }
                if self.state == State::Idle && self.okf_dev.is_some() && key.code == KeyCode::Esc {
                    self.exit_okf_dev();
                    return None;
                }
                // 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 and a leading `?` enters
                // deep-research mode. Each stays on until Esc or submit.
                let val = self.textarea.value();
                if !self.shell_mode && !self.research_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);
                    }
                }
            }

            Msg::Term(Event::Mouse(m)) => {
                use a3s_tui::event::{MouseButton, MouseEventKind};
                if self.state == State::Awaiting {
                    return self.handle_approval_mouse(&m);
                }
                if self.model_menu.is_some() {
                    self.handle_model_mouse(&m);
                    return None;
                }
                if self.effort_panel.is_some() {
                    self.handle_effort_mouse(&m);
                    return None;
                }
                if self.theme_panel.is_some() {
                    self.handle_theme_mouse(&m);
                    return None;
                }
                if self.file_menu_open() {
                    self.handle_file_mouse(&m);
                    return None;
                }
                if self.plugins_panel.is_some() {
                    self.handle_plugins_mouse(&m);
                    return None;
                }
                if self.slash_menu_open() {
                    return self.handle_slash_mouse(&m);
                }
                if self.flow.is_some() {
                    return self.handle_flow_mouse(&m);
                }
                if self.agent_picker.is_some() {
                    return self.handle_agent_mouse(&m);
                }
                if self.mcp_picker.is_some() {
                    return self.handle_mcp_mouse(&m);
                }
                if self.skill_picker.is_some() {
                    return self.handle_skill_mouse(&m);
                }
                if self.okf_picker.is_some() {
                    return self.handle_okf_package_mouse(&m);
                }
                if self.top.is_some() {
                    return self.handle_top_mouse(&m);
                }
                if self.help_open {
                    match m.kind {
                        MouseEventKind::ScrollUp => self.scroll_help_by(-3),
                        MouseEventKind::ScrollDown => self.scroll_help_by(3),
                        _ => {}
                    }
                    return None;
                }
                // 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()
                    || self.kb.is_some()
                    || self.asset_list.is_some()
                    || self.runtime_activity.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 = viewport_mouse_cell(m.row, m.column, vp_rows, max_col)
                            .map(|p| Selection { anchor: p, head: p });
                    }
                    MouseEventKind::Drag(MouseButton::Left) => {
                        if let Some(s) = self.selection.as_mut() {
                            if let Some(p) =
                                viewport_mouse_cell_clamped(m.row, m.column, vp_rows, max_col)
                            {
                                s.head = p;
                            }
                        }
                    }
                    MouseEventKind::Up(MouseButton::Left) => {
                        if let Some(mut s) = self.selection {
                            if let Some(p) =
                                viewport_mouse_cell_clamped(m.row, m.column, vp_rows, max_col)
                            {
                                s.head = p;
                            }
                            let view = self.viewport.view();
                            if is_remote_view_click(&view, s) {
                                self.selection = None;
                                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 is available for this Open view marker yet",
                                    ));
                                }
                            } else if s.is_empty() {
                                self.selection = None;
                            } else {
                                let (r1, c1, r2, c2) = s.ordered();
                                let text = selection_to_text(&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, join) => {
                self.rx = Some(rx.clone());
                self.stream_join = Some(join);
                self.host_progress_inflight = false;
                self.interrupting = false;
                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. The cancel command awaited the
                // stream join first, so core has committed the interrupted
                // history before any queued continuation starts.
                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 an asset 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 => {
                if self.host_progress_inflight {
                    self.rx = None;
                    return None;
                }
                if self.interrupting || self.state != State::Streaming {
                    return None;
                }
                // Channel closed without a normal End event (abnormal close).
                self.finalize_streaming();
                // An asset-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.memory.is_none()
                    && !self.help_open
                {
                    self.anim = self.anim.wrapping_add(1);
                    self.viewport.set_content(&self.banner());
                }
                // Advance the ultracode brand-gradient flourish.
                if self.gradient_until.is_some() || self.effort_anim.is_some() {
                    self.gradient_frame = self.gradient_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(BACKGROUND_CONFIRM_TIMEOUT_MS, 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(tui_session_options(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.replace_session(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 current = crate::update::current_version();
                let newer = latest
                    .as_deref()
                    .is_some_and(|l| !crate::update::version_ge(&current, 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::DeepResearchWorkflowCompleted {
                query,
                os_runtime,
                args,
                result,
            } => return self.on_deep_research_workflow_completed(query, os_runtime, args, result),

            Msg::UpdatePlan(latest) => {
                self.updating = None;
                self.relayout();
                let current = crate::update::current_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})")),
                        );
                        self.push_line(
                            &Style::new()
                                .fg(TN_GRAY)
                                .render("  checking companion tools…"),
                        );
                        self.updating = Some(Instant::now());
                        self.relayout();
                        return Some(cmd::cmd(|| async {
                            let result =
                                tokio::task::spawn_blocking(crate::update::repair_installation)
                                    .await
                                    .map_err(|e| format!("repair task failed: {e}"))
                                    .and_then(|r| r);
                            Msg::UpdateRepair(result)
                        }));
                    }
                    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::UpdateRepair(result) => {
                self.updating = None;
                self.relayout();
                match result {
                    Ok(items) if items.is_empty() => self.push_line(
                        &Style::new()
                            .fg(TN_GREEN)
                            .render("  ✓ installation looks healthy"),
                    ),
                    Ok(items) => {
                        for item in items {
                            self.push_line(
                                &Style::new().fg(TN_GREEN).render(&format!("{item}")),
                            );
                        }
                    }
                    Err(error) => self.push_line(
                        &Style::new()
                            .fg(TN_RED)
                            .render(&format!("  install repair failed: {error}")),
                    ),
                }
            }

            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!("  ✓ local SSH public key registered with OS ({fp}) · git clone(ssh) ready"),
                    )),
                    SshKeyOutcome::AlreadyRegistered => self.push_line(
                        &Style::new()
                            .fg(TN_GRAY)
                            .render("  · SSH public key already registered with OS; skipping"),
                    ),
                    SshKeyOutcome::NoLocalKey => self.push_line(&Style::new().fg(TN_YELLOW).render(
                        "  · no local SSH public key found; create one and run /login again to register it automatically: ssh-keygen -t ed25519",
                    )),
                    SshKeyOutcome::Failed(e) => self.push_line(
                        &Style::new()
                            .fg(TN_GRAY)
                            .render(&format!("  · SSH key sync skipped: {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. Re-sync the
                        // runtime tool too because it owns a token snapshot.
                        crate::a3s_os::export_os_env(&session);
                        self.os_session = Some(session);
                        self.sync_runtime_tool();
                    }
                    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_history.observe(&rows);
                    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::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.replace_session(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::MemoryLoaded(data) => {
                if let Some(m) = &mut self.memory {
                    let source = if data.loaded_from_session {
                        "session fallback · "
                    } else {
                        ""
                    };
                    m.note = format!(
                        "{source}{} memories · {} entities · {} relations",
                        data.entries.len(),
                        data.graph.stats.entities,
                        data.graph.stats.relations
                    );
                    m.sel = 0;
                    m.apply_data(data);
                }
            }
            Msg::MemoryForgotten(result) => {
                if let Some(m) = &mut self.memory {
                    match result {
                        Ok((id, data)) => {
                            m.note = format!(
                                "forgot {id} · {} memories · {} candidates",
                                data.entries.len(),
                                data.graph.stats.forget_candidates
                            );
                            m.apply_data(data);
                        }
                        Err(error) => {
                            m.note = format!("forget failed: {error}");
                        }
                    }
                }
            }
            Msg::AssetListLoaded(result) => self.on_asset_list(result),
            Msg::RuntimeActivityLoaded(result) => self.on_runtime_activity(result),
            Msg::KbAdded(summary) => {
                let color = if summary.starts_with('') {
                    TN_RED
                } else {
                    TN_GRAY
                };
                self.push_line(&Style::new().fg(color).render(&format!("  {summary}")));
                if self.kb.is_some() {
                    self.open_kb_home(Some(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::FlowOsCompleted(res) => self.on_flow_os_completed(res),
            Msg::AgentOsCompleted(res) => self.on_agent_os_completed(res),
            Msg::McpOsCompleted(res) => self.on_mcp_os_completed(res),
            Msg::SkillOsCompleted(res) => self.on_skill_os_completed(res),
            Msg::OkfOsCompleted(res) => self.on_okf_os_completed(res),
            Msg::AssetCloned(res) => match res {
                Ok(result) => self.on_asset_cloned(result),
                Err(error) => self.push_line(
                    &Style::new()
                        .fg(TN_RED)
                        .render(&format!("  clone failed: {error}")),
                ),
            },
            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(m) = &self.memory {
            return self.render_memory(m);
        }
        if let Some(panel) = &self.asset_list {
            return self.render_asset_list(panel);
        }
        if let Some(panel) = &self.runtime_activity {
            return self.render_runtime_activity(panel);
        }
        if let Some(kb) = &self.kb {
            let page = self.render_kb(kb);
            return self.overlay_approval(page);
        }
        if let Some(panel) = &self.loop_panel {
            return self.render_loop_panel(panel);
        }
        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 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), `/agent` dev = local agent development (green), `/mcp` dev =
        // local MCP development (cyan), `/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 {
            ("!", GRADIENT_PREVIEW_END, GRADIENT_PREVIEW_END)
        } else if self.research_mode {
            ("?", TN_CYAN, TN_CYAN)
        } else if self.agent_dev.is_some() {
            ("", TN_GREEN, TN_GREEN)
        } else if self.mcp_dev.is_some() {
            ("", TN_CYAN, TN_CYAN)
        } else if self.skill_dev.is_some() {
            ("", TN_CYAN, TN_CYAN)
        } else if self.okf_dev.is_some() {
            ("", TN_CYAN, TN_CYAN)
        } else if inp.starts_with("/btw") {
            ("", TN_YELLOW, TN_YELLOW)
        } else {
            ("", ACCENT, TN_GRAY)
        };
        // Brief brand-gradient ribbon on both input borders after picking
        // ultracode; otherwise plain bottom + effort-chip top.
        let gradient = self
            .gradient_until
            .is_some_and(|t| t.elapsed() < Duration::from_millis(1600));
        let separator = if gradient {
            input_gradient_rule(width, &BRAND_GRADIENT, self.gradient_frame + 3)
        } else {
            input_rule(width, border)
        };
        let top_separator = if gradient {
            input_gradient_rule(width, &BRAND_GRADIENT, self.gradient_frame)
        } 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()
            };
            input_status_rule(width, border, &ctxlabel, &elabel)
        };

        // 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 {
            compact_progress_line(t0.elapsed(), width)
        } 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 typed = self.textarea.view();
        let tint_input = sym == "!"
            || sym == "?"
            || sym == ""
            || sym == ""
            || sym == ""
            || inp.starts_with("/btw");
        let input_view = input_prompt_line(sym, icolor, &typed, tint_input, width);

        // 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 status1 = self.session_status_line(width);
        let status2 = render_mode_status_line(self.mode, 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 {
            jump_to_latest_hint(width)
        };
        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_review_menu(composed);
        let composed = self.overlay_flow_menu(composed);
        let composed = self.overlay_agent_menu(composed);
        let composed = self.overlay_mcp_menu(composed);
        let composed = self.overlay_skill_menu(composed);
        let composed = self.overlay_okf_package_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.memory.is_some()
            || self.asset_list.is_some()
            || self.runtime_activity.is_some()
            || self.kb.is_some()
            || self.loop_panel.is_some()
            || self.flow.is_some()
            || self.agent_picker.is_some()
            || self.mcp_picker.is_some()
            || self.skill_picker.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))
    }
}

#[allow(clippy::too_many_arguments)]
fn render_session_status_line(
    cwd: &str,
    branch: Option<&str>,
    model: Option<&str>,
    context_limit: u32,
    last_prompt_tokens: usize,
    output_tokens: usize,
    chips: impl IntoIterator<Item = SessionStatusChip>,
    width: usize,
) -> String {
    if width == 0 {
        return String::new();
    }

    let theme = agent_chrome_theme();
    let chrome = agent_chrome(&theme);
    let mut status = chrome
        .session_status(cwd)
        .branch_color(TN_YELLOW)
        .threshold_colors(TN_YELLOW, TN_RED)
        .margin(2);

    if let Some(branch) = branch {
        status = status.branch(branch);
    }
    if let Some(model) = model {
        status = status.model(model);
    }
    if context_limit > 0 {
        status = status.context(last_prompt_tokens, context_limit as usize);
    } else if output_tokens > 0 {
        status = status.output_tokens(output_tokens);
    }
    for chip in chips {
        status = status.status_chip(chip);
    }

    status.view(width.min(u16::MAX as usize) as u16)
}

fn render_mode_status_line(mode: Mode, width: usize) -> String {
    if width == 0 {
        return String::new();
    }

    let theme = agent_chrome_theme();
    let chrome = agent_chrome(&theme);
    chrome
        .mode_line(mode.name())
        .glyph(mode.glyph())
        .hints("(shift+tab to cycle) · /help · ↑↓ history · esc")
        .mode_color(mode.color())
        .view(width.min(u16::MAX as usize) as u16)
}

fn jump_to_latest_hint(width: usize) -> String {
    if width == 0 {
        return String::new();
    }

    let label = InlineAction::new("more below · Shift+End to jump to latest")
        .icon("")
        .colors(Color::BrightWhite, ACCENT)
        .view_with_width(width.min(u16::MAX as usize) as u16);
    let pad = width.saturating_sub(a3s_tui::style::visible_len(&label)) / 2;
    format!("{}{}", " ".repeat(pad), label)
}

impl App {
    fn session_status_line(&self, width: usize) -> String {
        render_session_status_line(
            &self.cwd,
            self.branch.as_deref(),
            self.model.as_deref(),
            self.context_limit,
            self.last_prompt_tokens,
            self.output_tokens,
            self.session_status_chips(),
            width,
        )
    }

    fn session_status_chips(&self) -> Vec<SessionStatusChip> {
        let mut chips = Vec::new();

        if self.goal.is_some() {
            let elapsed = self
                .goal_since
                .map(|t| format!(" ({})", fmt_elapsed(t.elapsed())))
                .unwrap_or_default();
            chips.push(
                SessionStatusChip::new("🎯", format!("Pursuing goal{elapsed}")).color(TN_CYAN),
            );
        }
        if let Some(dev) = &self.agent_dev {
            chips.push(
                SessionStatusChip::new(
                    "",
                    format!("agent:{} · Esc /agent off", truncate(&dev.name, 24)),
                )
                .color(TN_GREEN),
            );
        }
        if let Some(dev) = &self.mcp_dev {
            chips.push(
                SessionStatusChip::new(
                    "",
                    format!("mcp:{} · Esc /mcp off", truncate(&dev.name, 24)),
                )
                .color(TN_CYAN),
            );
        }
        if let Some(dev) = &self.skill_dev {
            chips.push(
                SessionStatusChip::new(
                    "",
                    format!("skill:{} · Esc /skill off", truncate(&dev.name, 24)),
                )
                .color(TN_CYAN),
            );
        }
        if let Some(dev) = &self.okf_dev {
            chips.push(
                SessionStatusChip::new(
                    "",
                    format!("okf:{} · Esc /okf off", truncate(&dev.name, 24)),
                )
                .color(TN_CYAN),
            );
        }
        if self.loop_remaining > 0 {
            chips.push(SessionStatusChip::new("", self.loop_remaining.to_string()).color(TN_GRAY));
        }
        let active_subagents = self.runtime.active_subagent_count();
        if active_subagents > 0 {
            chips.push(
                SessionStatusChip::new("", format!("{active_subagents} agents")).color(TN_GRAY),
            );
        }
        let active_tools = self.runtime.active_tool_count();
        if active_tools > 0 {
            chips.push(
                SessionStatusChip::new("", format!("{active_tools} running")).color(TN_GRAY),
            );
        }
        if let Some(version) = self.update_available.as_deref() {
            chips.push(SessionStatusChip::new("", version).color(TN_YELLOW));
        }

        chips
    }

    fn clone_asset_command(
        &mut self,
        family: &'static str,
        url: String,
        root: std::path::PathBuf,
    ) -> Option<Cmd<Msg>> {
        self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
            "  cloning {family} asset from {url}{}",
            root.display()
        )));
        Some(cmd::cmd(move || async move {
            Msg::AssetCloned(asset_clone::clone_asset_source(family, url, root).await)
        }))
    }

    fn on_asset_cloned(&mut self, result: asset_clone::AssetCloneResult) {
        self.push_line(&Style::new().fg(TN_GREEN).render(&format!(
            "  cloned {} asset → {}",
            result.family,
            result.path.display()
        )));
        match result.family {
            "agent" => self.open_agent_panel_focused(&result.path),
            "mcp" => self.open_mcp_panel_focused(&result.path),
            "skill" => self.open_skill_panel_focused(&result.path),
            "okf" | "knowledge" => self.open_okf_package_panel_focused(&result.path),
            "workflow" => self.open_flow_panel_focused(&result.path),
            _ => self.push_line(
                &Style::new()
                    .fg(TN_GRAY)
                    .render("  run the asset command again to select or operate on it"),
            ),
        }
    }

    fn path_is_within(path: &std::path::Path, root: &std::path::Path) -> bool {
        path == root || path.starts_with(root)
    }

    fn open_agent_panel_focused(&mut self, cloned_path: &std::path::Path) {
        let root = agent_dir();
        let agents = panels::agent::list_agents(&root);
        let Some(sel) = agents
            .iter()
            .position(|agent| Self::path_is_within(&agent.path, cloned_path))
        else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  cloned source does not contain a recognized agent definition yet"),
            );
            return;
        };
        self.agent_picker = Some(panels::agent::AgentPanel { root, agents, sel });
        self.push_line(
            &Style::new()
                .fg(TN_GRAY)
                .render("  selected cloned agent asset · Enter develops locally"),
        );
    }

    fn open_mcp_panel_focused(&mut self, cloned_path: &std::path::Path) {
        let root = mcp_dir();
        let projects = panels::mcp::list_mcp_projects(&root);
        let Some(sel) = projects
            .iter()
            .position(|project| Self::path_is_within(&project.path, cloned_path))
        else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  cloned source does not contain a recognized MCP asset yet"),
            );
            return;
        };
        self.mcp_picker = Some(panels::mcp::McpPanel {
            root,
            projects,
            sel,
        });
        self.push_line(
            &Style::new()
                .fg(TN_GRAY)
                .render("  selected cloned MCP asset · Enter develops locally"),
        );
    }

    fn open_skill_panel_focused(&mut self, cloned_path: &std::path::Path) {
        let root = skill_dir();
        let skills = panels::skill::list_skill_assets(&root);
        let Some(sel) = skills
            .iter()
            .position(|skill| Self::path_is_within(&skill.path, cloned_path))
        else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  cloned source does not contain a recognized skill asset yet"),
            );
            return;
        };
        self.skill_picker = Some(panels::skill::SkillPanel { root, skills, sel });
        self.push_line(
            &Style::new()
                .fg(TN_GRAY)
                .render("  selected cloned skill asset · Enter develops locally"),
        );
    }

    fn open_okf_package_panel_focused(&mut self, cloned_path: &std::path::Path) {
        let root = panels::okf::okf_package_dir(&self.cwd);
        let packages = panels::okf::list_okf_packages(&root);
        let Some(sel) = packages
            .iter()
            .position(|package| Self::path_is_within(&package.path, cloned_path))
        else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  cloned source does not contain a recognized OKF package yet"),
            );
            return;
        };
        self.okf_picker = Some(panels::okf::OkfPackagePanel {
            root,
            packages,
            sel,
        });
        self.push_line(
            &Style::new()
                .fg(TN_GRAY)
                .render("  selected cloned OKF package · Enter develops locally"),
        );
    }

    fn open_flow_panel_focused(&mut self, cloned_path: &std::path::Path) {
        let root = flow_dir();
        let flows = panels::flow::list_flows(&root);
        let Some(sel) = flows
            .iter()
            .position(|flow| Self::path_is_within(&root.join(flow), cloned_path))
        else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  cloned source does not contain a recognized workflow design yet"),
            );
            return;
        };
        self.flow = Some(panels::flow::FlowPanel { root, flows, sel });
        self.push_line(
            &Style::new()
                .fg(TN_GRAY)
                .render("  selected cloned workflow asset · Enter opens the OS designer"),
        );
    }

    fn execute_agent_subcommand(
        &mut self,
        subcommand: panels::agent::AgentSubcommand,
    ) -> Option<Cmd<Msg>> {
        match subcommand {
            panels::agent::AgentSubcommand::Exit => {
                self.exit_agent_dev();
                None
            }
            panels::agent::AgentSubcommand::Clone(url) => {
                self.clone_asset_command("agent", url, agent_dir())
            }
            panels::agent::AgentSubcommand::List(query) => {
                self.open_asset_list_panel(os_asset_category_query("agent", &query))
            }
            panels::agent::AgentSubcommand::Activity(query) => {
                let Some(agent_dev) = self.agent_dev.clone() else {
                    self.pending_agent_subcommand =
                        Some(panels::agent::AgentSubcommand::Activity(query));
                    self.open_agent_panel();
                    return None;
                };
                self.open_runtime_activity_panel(runtime_asset_query(
                    "agent",
                    &agent_dev.name,
                    &query,
                ))
            }
            panels::agent::AgentSubcommand::Review => {
                let Some(agent_dev) = self.agent_dev.clone() else {
                    self.pending_agent_subcommand = Some(panels::agent::AgentSubcommand::Review);
                    self.open_agent_panel();
                    return None;
                };
                self.messages
                    .push(user_bubble("/agent review", self.viewport_content_width()));
                self.engage_autonomy(4);
                self.review_pending = true;
                let prompt = panels::agent::agent_review_prompt(&agent_dev);
                let display = format!("{} review", agent_dev.name);
                self.start_stream_inner(prompt, display, true, true, false)
            }
            other => {
                let Some(agent_dev) = self.agent_dev.clone() else {
                    self.pending_agent_subcommand = Some(other);
                    self.open_agent_panel();
                    return None;
                };
                let Some(session) = self.os_session.clone() else {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  /agent OS actions need /login first"),
                    );
                    return None;
                };
                let action = match other {
                    panels::agent::AgentSubcommand::Publish(kind) => {
                        panels::agent::AgentOsAction::Publish(kind)
                    }
                    panels::agent::AgentSubcommand::Run => panels::agent::AgentOsAction::Run,
                    panels::agent::AgentSubcommand::Deploy => panels::agent::AgentOsAction::Deploy,
                    panels::agent::AgentSubcommand::Open(kind) => {
                        panels::agent::AgentOsAction::Open(kind)
                    }
                    panels::agent::AgentSubcommand::Logs(kind) => {
                        panels::agent::AgentOsAction::Logs(kind)
                    }
                    panels::agent::AgentSubcommand::Status(kind) => {
                        panels::agent::AgentOsAction::Status(kind)
                    }
                    panels::agent::AgentSubcommand::Exit
                    | panels::agent::AgentSubcommand::Clone(_)
                    | panels::agent::AgentSubcommand::List(_)
                    | panels::agent::AgentSubcommand::Activity(_)
                    | panels::agent::AgentSubcommand::Review => unreachable!(),
                };
                let kind = action.target_kind();
                self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                    "{} → OS {} {}",
                    agent_dev.name,
                    kind.label(),
                    kind.service_label()
                )));
                Some(cmd::cmd(move || async move {
                    let result =
                        panels::agent::publish_agent_to_os(session, agent_dev, action).await;
                    Msg::AgentOsCompleted(result)
                }))
            }
        }
    }

    fn execute_mcp_subcommand(
        &mut self,
        subcommand: panels::mcp::McpSubcommand,
    ) -> Option<Cmd<Msg>> {
        match subcommand {
            panels::mcp::McpSubcommand::Exit => {
                self.exit_mcp_dev();
                None
            }
            panels::mcp::McpSubcommand::Clone(url) => {
                self.clone_asset_command("mcp", url, mcp_dir())
            }
            panels::mcp::McpSubcommand::List(query) => {
                self.open_asset_list_panel(os_asset_category_query("mcp", &query))
            }
            panels::mcp::McpSubcommand::Activity(query) => {
                let Some(mcp_dev) = self.mcp_dev.clone() else {
                    self.pending_mcp_subcommand = Some(panels::mcp::McpSubcommand::Activity(query));
                    self.open_mcp_panel();
                    return None;
                };
                self.open_runtime_activity_panel(runtime_asset_query("mcp", &mcp_dev.name, &query))
            }
            panels::mcp::McpSubcommand::Review => {
                let Some(mcp_dev) = self.mcp_dev.clone() else {
                    self.pending_mcp_subcommand = Some(panels::mcp::McpSubcommand::Review);
                    self.open_mcp_panel();
                    return None;
                };
                self.messages
                    .push(user_bubble("/mcp review", self.viewport_content_width()));
                self.engage_autonomy(4);
                self.review_pending = true;
                let prompt = panels::mcp::mcp_review_prompt(&mcp_dev);
                let display = format!("{} review", mcp_dev.name);
                self.start_stream_inner(prompt, display, true, true, false)
            }
            other => {
                let Some(action) = other.os_action() else {
                    unreachable!("local MCP actions handled above")
                };
                let Some(mcp_dev) = self.mcp_dev.clone() else {
                    self.pending_mcp_subcommand = Some(other);
                    self.open_mcp_panel();
                    return None;
                };
                let Some(session) = self.os_session.clone() else {
                    self.push_line(
                        &Style::new()
                            .fg(TN_YELLOW)
                            .render("  /mcp OS actions need /login first"),
                    );
                    return None;
                };
                self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                    "{} → OS MCP Function as a Service {}",
                    mcp_dev.name,
                    action.label()
                )));
                Some(cmd::cmd(move || async move {
                    let result = panels::mcp::publish_mcp_to_os(session, mcp_dev, action).await;
                    Msg::McpOsCompleted(result)
                }))
            }
        }
    }

    fn execute_skill_subcommand(
        &mut self,
        subcommand: panels::skill::SkillSubcommand,
    ) -> Option<Cmd<Msg>> {
        match subcommand {
            panels::skill::SkillSubcommand::Exit => {
                self.exit_skill_dev();
                None
            }
            panels::skill::SkillSubcommand::Clone(url) => {
                self.clone_asset_command("skill", url, skill_dir())
            }
            panels::skill::SkillSubcommand::List(query) => {
                self.open_asset_list_panel(os_asset_category_query("skill", &query))
            }
            panels::skill::SkillSubcommand::Activity(query) => {
                let Some(skill_dev) = self.skill_dev.clone() else {
                    self.pending_skill_subcommand =
                        Some(panels::skill::SkillSubcommand::Activity(query));
                    self.open_skill_panel();
                    return None;
                };
                self.open_runtime_activity_panel(runtime_asset_query(
                    "skill",
                    &skill_dev.name,
                    &query,
                ))
            }
            panels::skill::SkillSubcommand::Review => {
                if self.skill_dev.is_none() {
                    self.pending_skill_subcommand = Some(panels::skill::SkillSubcommand::Review);
                    self.open_skill_panel();
                    return None;
                }
                let skill = self.skill_dev.clone().expect("checked above");
                let body = match std::fs::read_to_string(&skill.path) {
                    Ok(body) => body,
                    Err(error) => {
                        self.push_line(&Style::new().fg(TN_RED).render(&format!(
                            "  could not read {}: {error}",
                            skill.path.display()
                        )));
                        return None;
                    }
                };
                self.messages
                    .push(user_bubble("/skill review", self.viewport_content_width()));
                self.engage_autonomy(4);
                self.review_pending = true;
                let prompt = panels::skill::skill_review_prompt(&skill.path, &body);
                let display = format!("{} review", skill.name);
                self.start_stream_inner(prompt, display, true, true, false)
            }
            panels::skill::SkillSubcommand::Publish => {
                self.execute_skill_os_action(panels::skill::SkillOsAction::Publish)
            }
            panels::skill::SkillSubcommand::Deploy => {
                if self.skill_dev.is_none() {
                    self.pending_skill_subcommand = Some(panels::skill::SkillSubcommand::Deploy);
                    self.open_skill_panel();
                    return None;
                }
                self.execute_skill_os_action(panels::skill::SkillOsAction::Deploy)
            }
            panels::skill::SkillSubcommand::Open => {
                self.execute_skill_os_action(panels::skill::SkillOsAction::Open)
            }
            panels::skill::SkillSubcommand::Status => {
                self.execute_skill_os_action(panels::skill::SkillOsAction::Status)
            }
        }
    }

    fn execute_skill_os_action(
        &mut self,
        action: panels::skill::SkillOsAction,
    ) -> Option<Cmd<Msg>> {
        let Some(skill_dev) = self.skill_dev.clone() else {
            self.pending_skill_subcommand = Some(match action {
                panels::skill::SkillOsAction::Publish => panels::skill::SkillSubcommand::Publish,
                panels::skill::SkillOsAction::Deploy => panels::skill::SkillSubcommand::Deploy,
                panels::skill::SkillOsAction::Open => panels::skill::SkillSubcommand::Open,
                panels::skill::SkillOsAction::Status => panels::skill::SkillSubcommand::Status,
            });
            self.open_skill_panel();
            return None;
        };
        let Some(session) = self.os_session.clone() else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  /skill OS actions need /login first"),
            );
            return None;
        };
        self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
            "{} → OS skill Function as a Service {}",
            skill_dev.name,
            action.label()
        )));
        Some(cmd::cmd(move || async move {
            let result = panels::skill::publish_skill_to_os(session, skill_dev, action).await;
            Msg::SkillOsCompleted(result)
        }))
    }

    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;
        }
        // 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(
                GRADIENT_PREVIEW_END,
                &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 host-orchestrated for stability: the TUI
        // first executes DynamicWorkflowRuntime directly to gather evidence through
        // OS Runtime (when signed in) or local parallel_task fallback, then starts
        // one synthesis turn over the gathered evidence.
        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}")),
            ));
            let runtime_hint = if self.os_session.is_some() {
                "  🎯 goal set · OS A3S Runtime parallel research · report + RemoteUI view (Esc stops)"
            } else {
                "  🎯 goal set · local deep research · report + HTML artifacts (Esc stops)"
            };
            self.push_line(&Style::new().fg(TN_GRAY).render(runtime_hint));
            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);
            let os_runtime = self.os_session.is_some();
            let runtime_expectation = self
                .os_session
                .is_some()
                .then(|| RuntimeExpectation::required_report_view("deep research"));
            if self.state == State::Idle {
                return self.start_deep_research_workflow(query, os_runtime, runtime_expectation);
            }
            self.seq += 1;
            self.queue.push(Queued {
                prio: 1,
                seq: self.seq,
                text: String::new(),
                display,
                runtime_expectation,
                deep_research: Some((query, os_runtime)),
            });
            self.push_line(&Style::new().fg(TN_GRAY).render("    ⋯ queued"));
            self.relayout();
            return None;
        }
        // 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) = slash_tail(trimmed, "/login") {
            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.asset_list = None;
                    self.runtime_activity = None;
                    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.asset_list = None;
                    self.runtime_activity = None;
                    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` opens the local personal knowledge-base panel. Notes/imports/search are
        // explicit subcommands so a mistyped path no longer becomes a note.
        // `/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) = slash_tail(trimmed, "/ctx") {
            return self.handle_ctx_command(rest);
        }
        if let Some(rest) = slash_tail(trimmed, "/okf") {
            return self.handle_okf_command(rest);
        }
        if let Some(rest) = slash_tail(trimmed, "/kb") {
            return self.handle_kb_command(rest);
        }
        // `/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) = slash_tail(trimmed, "/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(BACKGROUND_CONFIRM_TIMEOUT_MS, TimeoutAction::Reject);
                let sess = match agent.session(workspace, Some(tui_session_options(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) = slash_tail(trimmed, "/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 {
                if let Some(dev) = self.agent_dev.clone() {
                    let scoped = panels::agent::agent_goal_label(&dev, g);
                    self.goal = Some(scoped.clone());
                    self.goal_since = Some(Instant::now());
                    self.push_line(&gutter(
                        TN_CYAN,
                        &format!("🎯 agent goal set: {} · {g}", dev.name),
                    ));
                    let prompt = panels::agent::agent_dev_prompt(&dev, g);
                    let display = format!("{} goal: {}", dev.name, truncate(g, 54));
                    return self.start_stream_inner(prompt, display, true, true, false);
                }
                // 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` — engineered loop dashboard + subcommands; unknown tails keep
        // the quick-loop contract (`/loop <task>`).
        if let Some(rest) = slash_tail(trimmed, "/loop") {
            return self.handle_loop_command(rest);
        }
        // `/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) = slash_tail(trimmed, "/sleep") {
            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 asset reviews: 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` — select a local DAG JSON and open it in the OS workflow
        // designer (login-gated); `/flow <description>` 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) = slash_tail(trimmed, "/flow") {
            let description = rest.trim().to_string();
            self.textarea.clear();
            if let Some(parsed) = panels::flow::parse_flow_subcommand(&description) {
                match parsed {
                    Ok(panels::flow::FlowSubcommand::Clone(url)) => {
                        return self.clone_asset_command("workflow", url, flow_dir());
                    }
                    Ok(panels::flow::FlowSubcommand::List(query)) => {
                        return self
                            .open_asset_list_panel(os_asset_category_query("workflow", &query));
                    }
                    Ok(panels::flow::FlowSubcommand::Activity(query)) => {
                        if self.os_session.is_none() {
                            self.push_line(&os_required_alert(
                                "workflow runtime activity",
                                self.os_config.is_some(),
                            ));
                        } else {
                            self.pending_flow_subcommand =
                                Some(panels::flow::FlowSubcommand::Activity(query));
                            self.open_flow_panel();
                        }
                        return None;
                    }
                    Ok(panels::flow::FlowSubcommand::Review(target)) => {
                        let root = flow_dir();
                        let flows = panels::flow::list_flows(&root);
                        let picked = match target {
                            Some(target) => flows
                                .into_iter()
                                .find(|flow| flow == &target || flow.ends_with(&target)),
                            None if flows.len() == 1 => flows.into_iter().next(),
                            None => None,
                        };
                        let Some(file) = picked else {
                            self.pending_flow_subcommand =
                                Some(panels::flow::FlowSubcommand::Review(None));
                            self.open_flow_panel();
                            return None;
                        };
                        let path = root.join(&file);
                        let design = match std::fs::read_to_string(&path) {
                            Ok(value) => value,
                            Err(error) => {
                                self.push_line(&Style::new().fg(TN_RED).render(&format!(
                                    "  could not read {}: {error}",
                                    path.display()
                                )));
                                return None;
                            }
                        };
                        if serde_json::from_str::<serde_json::Value>(&design).is_err() {
                            self.push_line(
                                &Style::new()
                                    .fg(TN_RED)
                                    .render(&format!("  {} is not valid JSON", file)),
                            );
                            return None;
                        }
                        self.messages.push(user_bubble(
                            &format!("/flow review {file}"),
                            self.viewport_content_width(),
                        ));
                        self.engage_autonomy(4);
                        self.review_pending = true;
                        let prompt = panels::flow::flow_review_prompt(&path, &design);
                        let display = format!("⧉ flow review: {}", truncate(&file, 48));
                        return self.start_stream_inner(prompt, display, true, true, false);
                    }
                    Ok(action @ panels::flow::FlowSubcommand::Publish)
                    | Ok(action @ panels::flow::FlowSubcommand::Run)
                    | Ok(action @ panels::flow::FlowSubcommand::Deploy)
                    | Ok(action @ panels::flow::FlowSubcommand::Open)
                    | Ok(action @ panels::flow::FlowSubcommand::Logs)
                    | Ok(action @ panels::flow::FlowSubcommand::Status) => {
                        if self.os_session.is_none() {
                            self.push_line(
                                &Style::new().fg(TN_YELLOW).render(
                                    "  /flow publish/run/deploy/open/logs/status needs OS — sign in with /login first",
                                ),
                            );
                        } else {
                            self.pending_flow_subcommand = Some(action);
                            self.open_flow_panel();
                        }
                        return None;
                    }
                    Err(e) => {
                        self.push_line(&Style::new().fg(TN_RED).render(&format!("  {e}")));
                        return None;
                    }
                }
            }
            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);
        }
        // `/agent` — select a local a3s-code agent definition and enter local
        // multi-turn development mode; `/agent <description>` drafts a local Markdown
        // agent definition; OS subcommands publish/run/deploy the active local
        // definition through Agent as a Service or Function as a Service according to the kind.
        if let Some(rest) = slash_tail(trimmed, "/agent") {
            let description = rest.trim().to_string();
            self.textarea.clear();
            if let Some(parsed) = panels::agent::parse_agent_subcommand(&description) {
                return match parsed {
                    Ok(subcommand) => self.execute_agent_subcommand(subcommand),
                    Err(e) => {
                        self.push_line(&Style::new().fg(TN_RED).render(&format!("  {e}")));
                        None
                    }
                };
            }
            if description.is_empty() {
                self.open_agent_panel();
                return None;
            }
            let dir = agent_dir();
            self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                "  ◇ drafting an agent definition → {} (then /agent starts local dev)",
                dir.display()
            )));
            self.engage_autonomy(8);
            let prompt = panels::agent::agent_gen_prompt(&description, &dir.to_string_lossy());
            let display = format!("◇ agent: {}", truncate(&description, 60));
            return self.start_stream_inner(prompt, display, true, true, false);
        }
        // `/mcp` — select a local MCP server asset and enter local multi-turn
        // development mode; `/mcp <description>` drafts a local MCP asset.
        // OS publish/debug/test will map MCP tool calls to Function as a Service.
        if let Some(rest) = slash_tail(trimmed, "/mcp") {
            let description = rest.trim().to_string();
            self.textarea.clear();
            if let Some(parsed) = panels::mcp::parse_mcp_subcommand(&description) {
                return match parsed {
                    Ok(subcommand) => self.execute_mcp_subcommand(subcommand),
                    Err(e) => {
                        self.push_line(&Style::new().fg(TN_RED).render(&format!("  {e}")));
                        None
                    }
                };
            }
            if description.is_empty() {
                self.open_mcp_panel();
                return None;
            }
            let dir = mcp_dir();
            self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                "  ◆ drafting an MCP server asset → {} (then /mcp starts local dev)",
                dir.display()
            )));
            self.engage_autonomy(8);
            let prompt = panels::mcp::mcp_gen_prompt(&description, &dir.to_string_lossy());
            let display = format!("◆ mcp: {}", truncate(&description, 60));
            return self.start_stream_inner(prompt, display, true, true, false);
        }
        // `/skill` — select a local skill asset and enter local multi-turn
        // development mode; `/skill <description>` drafts a local skill asset.
        if let Some(rest) = slash_tail(trimmed, "/skill") {
            let description = rest.trim().to_string();
            self.textarea.clear();
            if let Some(parsed) = panels::skill::parse_skill_subcommand(&description) {
                return match parsed {
                    Ok(subcommand) => self.execute_skill_subcommand(subcommand),
                    Err(e) => {
                        self.push_line(&Style::new().fg(TN_RED).render(&format!("  {e}")));
                        None
                    }
                };
            }
            if description.is_empty() {
                self.open_skill_panel();
                return None;
            }
            let dir = skill_dir();
            self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                "  ✦ drafting a skill asset → {} (then /skill starts local dev)",
                dir.display()
            )));
            self.engage_autonomy(8);
            let prompt = panels::skill::skill_gen_prompt(&description, &dir.to_string_lossy());
            let display = format!("✦ skill: {}", truncate(&description, 60));
            return self.start_stream_inner(prompt, display, true, true, false);
        }
        // Slash commands run inline in any state.
        match trimmed {
            "/exit" => 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.runtime.clear_turn_entities();
                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();
                self.agent_dev = None;
                self.pending_flow_subcommand = None;
                self.pending_agent_subcommand = None;
                self.mcp_dev = None;
                self.pending_mcp_subcommand = None;
                self.skill_dev = None;
                self.pending_skill_subcommand = None;
                self.okf_picker = None;
                self.pending_okf_subcommand = None;
                self.okf_dev = None;
                self.asset_list = None;
                self.runtime_activity = None;
                self.kb = None;
                // 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.replace_session(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 workspace 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.viewport_content_width(),
                ));
                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 workspace, 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(BACKGROUND_CONFIRM_TIMEOUT_MS, TimeoutAction::Reject);
                    let mut summary = String::new();
                    if let Ok(sess) = agent.session(workspace, Some(tui_session_options(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;
                self.help_scroll = 0;
                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_history.clear();
                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" => {
                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;
            }
            "/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.replace_session(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)
                }));
            }
            "/memory" => {
                self.textarea.clear();
                // Open immediately ("loading…"); load the file snapshot off the
                // UI thread, with live session memory as a fallback.
                let dir = memory_dir();
                self.memory = Some(MemPanel {
                    entries: Vec::new(),
                    sel: 0,
                    details: std::collections::BTreeMap::new(),
                    graph: MemoryGraph::default(),
                    loaded_from_session: false,
                    detail: memutil::MemDetail::default(),
                    detail_scroll: 0,
                    dir: dir.clone(),
                    note: "loading…".into(),
                });
                return Some(self.load_memory_panel(dir));
            }
            _ => {}
        }

        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.viewport_content_width()));
        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(),
        };
        let (prompt, display) = match &self.agent_dev {
            Some(dev) => (
                panels::agent::agent_dev_prompt(dev, &prompt),
                format!("{}: {}", dev.name, truncate(trimmed, 60)),
            ),
            None => match &self.mcp_dev {
                Some(dev) => (
                    panels::mcp::mcp_dev_prompt(dev, &prompt),
                    format!("{}: {}", dev.name, truncate(trimmed, 60)),
                ),
                None => match &self.skill_dev {
                    Some(dev) => (
                        panels::skill::skill_dev_prompt(dev, &prompt),
                        format!("{}: {}", dev.name, truncate(trimmed, 60)),
                    ),
                    None => match &self.okf_dev {
                        Some(dev) => (
                            panels::okf::okf_dev_prompt(dev, &prompt),
                            format!("{}: {}", dev.name, truncate(trimmed, 60)),
                        ),
                        None => (prompt, trimmed.to_string()),
                    },
                },
            },
        };
        if self.state == State::Idle {
            self.start_stream_inner(prompt, display, true, true, false)
        } else {
            self.seq += 1;
            self.queue.push(Queued {
                prio: 1,
                seq: self.seq,
                text: prompt,
                display,
                runtime_expectation: None,
                deep_research: None,
            });
            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.transcript_markdown_width().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_deep_research_workflow(
        &mut self,
        query: String,
        os_runtime: bool,
        runtime_expectation: Option<RuntimeExpectation>,
    ) -> Option<Cmd<Msg>> {
        self.streaming.clear();
        self.got_delta = false;
        self.turn_text.clear();
        self.turn_had_agent_activity = false;
        self.turn_text_after_activity = false;
        if let Some(expectation) = runtime_expectation {
            self.runtime_expectation = Some(expectation);
        }
        self.ultracode_synthesis_inflight = false;
        self.ultracode_synthesis_used = false;
        self.last_paint = None;
        self.viewport.set_auto_scroll(true);
        self.plan.clear();
        self.runtime.clear_turn_entities();
        self.running_task = Some(format!("🔬 {query}"));
        self.state = State::Streaming;
        self.relayout();
        self.stream_started = Some(Instant::now());
        self.spinner.start();
        self.push_line(
            &Style::new()
                .fg(TN_GRAY)
                .render("  ⇉ gathering evidence with DynamicWorkflowRuntime…"),
        );
        self.rebuild_viewport();

        let args = deep_research_workflow_args(&query, os_runtime);
        let (progress_rx, workflow_join) = self
            .session
            .tool_with_events("dynamic_workflow", args.clone());
        let progress_rx = Arc::new(Mutex::new(progress_rx));
        self.rx = Some(progress_rx.clone());
        self.stream_join = None;
        self.host_progress_inflight = true;
        self.interrupting = false;
        Some(cmd::batch(vec![
            cmd::cmd(move || async move {
                let result = match workflow_join.await {
                    Ok(result) => result.map_err(|err| err.to_string()),
                    Err(err) => Err(err.to_string()),
                };
                Msg::DeepResearchWorkflowCompleted {
                    query,
                    os_runtime,
                    args,
                    result,
                }
            }),
            pump(progress_rx),
            spinner_tick(),
        ]))
    }

    fn on_deep_research_workflow_completed(
        &mut self,
        query: String,
        os_runtime: bool,
        args: serde_json::Value,
        result: Result<ToolCallResult, String>,
    ) -> Option<Cmd<Msg>> {
        if self.state != State::Streaming {
            return None;
        }
        self.host_progress_inflight = false;
        self.rx = None;

        let (output, exit_code, metadata) = match result {
            Ok(result) => (result.output, result.exit_code, result.metadata),
            Err(error) => (error, 1, None),
        };
        let tool_id = format!("host-dynamic-workflow-{}", self.seq);
        self.runtime
            .start_tool(tool_id.clone(), "dynamic_workflow".to_string());
        self.runtime
            .push_tool_input(&serde_json::to_string(&args).unwrap_or_default());
        let completed = self.runtime.end_tool(
            &tool_id,
            "dynamic_workflow".to_string(),
            output.clone(),
            exit_code,
        );
        self.push_line(&render_tool_end(
            "dynamic_workflow",
            exit_code,
            &output,
            metadata.as_ref(),
            completed.args.as_ref(),
            self.viewport_content_width(),
        ));
        self.record_runtime_tool_evidence("dynamic_workflow");
        if metadata
            .as_ref()
            .is_some_and(|value| json_contains_tool_evidence(value, "runtime"))
        {
            self.record_runtime_tool_evidence("runtime");
        }
        if metadata
            .as_ref()
            .is_some_and(|value| json_contains_tool_evidence(value, "parallel_task"))
        {
            self.record_runtime_parallel_evidence();
        }
        self.capture_workflow("dynamic_workflow", completed.args.as_ref());
        if let Some(spec) = self.find_remote_view_spec(&output) {
            self.remember_remote_view(spec);
        }

        let prompt = if exit_code == 0 {
            deep_research_synthesis_prompt(&query, os_runtime, &output, metadata.as_ref())
        } else {
            self.push_line(
                &Style::new()
                    .fg(TN_YELLOW)
                    .render("  ⚠ dynamic workflow failed; starting recovery synthesis…"),
            );
            deep_research_recovery_prompt(&query, os_runtime, &output, metadata.as_ref())
        };
        self.start_stream_inner_with_runtime(
            prompt,
            format!("🔬 synthesize {query}"),
            false,
            false,
            false,
            None,
        )
    }

    fn start_stream_inner(
        &mut self,
        prompt: String,
        display_task: String,
        clear_turn_artifacts: bool,
        include_attachments: bool,
        synthesis: bool,
    ) -> Option<Cmd<Msg>> {
        self.start_stream_inner_with_runtime(
            prompt,
            display_task,
            clear_turn_artifacts,
            include_attachments,
            synthesis,
            None,
        )
    }

    fn start_stream_inner_with_runtime(
        &mut self,
        prompt: String,
        display_task: String,
        clear_turn_artifacts: bool,
        include_attachments: bool,
        synthesis: bool,
        runtime_expectation: Option<RuntimeExpectation>,
    ) -> 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;
        if let Some(expectation) = runtime_expectation {
            self.runtime_expectation = Some(expectation);
        }
        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
                               // Keep completed agents visible until the next user turn; a fresh
                               // user turn starts a fresh runtime-entity projection.
            self.runtime.clear_turn_entities();
        } else {
            self.runtime.clear_live_tools();
        }
        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`,
        // asset review, `?`, 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)), join),
                    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()?;
        if let Some((query, os_runtime)) = next.deep_research {
            return self.start_deep_research_workflow(query, os_runtime, next.runtime_expectation);
        }
        self.start_stream_inner_with_runtime(
            next.text,
            next.display,
            true,
            true,
            false,
            next.runtime_expectation,
        )
    }

    /// 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;
        }
        self.warn_missing_runtime_evidence();
        let synthesis = self.prepare_ultracode_synthesis();
        self.finish();
        if let Some((prompt, display_task)) = synthesis {
            return self.start_ultracode_synthesis(prompt, display_task);
        }
        // Required OS Runtime evidence is a deliverable, not just a warning. In
        // autonomous runs, spend the next loop turn on a targeted correction
        // before falling back to the generic "Continue" prompt.
        if self.loop_remaining > 0 && self.queue.is_empty() {
            if let Some(prompt) = self
                .runtime_expectation
                .as_ref()
                .and_then(RuntimeExpectation::corrective_prompt)
            {
                self.loop_remaining -= 1;
                let n = self.loop_remaining;
                self.push_line(&Style::new().fg(TN_GRAY).render(&format!(
                    "  ↻ runtime evidence retry ({n} left · Esc to stop)"
                )));
                self.loop_continuation = true;
                return Some(cmd::msg(Msg::Submit(prompt)));
            }
        }
        // /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()
    }

    fn resume_after_pending_confirmation(&self) -> Cmd<Msg> {
        resume_after_pending_confirmation_cmd(self.rx.clone())
    }

    /// An autonomous directive run is starting (/sleep, asset reviews,
    /// asset run/deploy, /flow drafts, /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)",
            ));
        }
    }

    fn record_runtime_tool_evidence(&mut self, name: &str) {
        if let Some(expectation) = &mut self.runtime_expectation {
            expectation.record_tool(name);
        }
    }

    fn record_runtime_parallel_evidence(&mut self) {
        if let Some(expectation) = &mut self.runtime_expectation {
            expectation.record_parallel_work();
        }
    }

    fn record_runtime_view_evidence(&mut self) {
        if let Some(expectation) = &mut self.runtime_expectation {
            expectation.record_remote_view();
        }
    }

    fn warn_missing_runtime_evidence(&mut self) {
        let warning = self
            .runtime_expectation
            .as_mut()
            .and_then(RuntimeExpectation::missing_warning);
        if let Some(warning) = warning {
            self.push_line(&Style::new().fg(TN_YELLOW).render(&warning));
        }
    }

    /// Restore the pre-autonomy mode (no-op when nothing was auto-switched).
    fn restore_autonomy(&mut self) {
        self.runtime_expectation = None;
        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 { id, 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.runtime.start_tool(id, name);
            }
            AgentEvent::ToolInputDelta { delta } => {
                self.runtime.push_tool_input(&delta);
            }
            AgentEvent::ToolOutputDelta { id, name, delta } => {
                self.runtime.push_tool_output(id, name, &delta);
                if let Some(output) = self
                    .runtime
                    .live_tool()
                    .map(|tool| tool.output().to_string())
                {
                    if let Some(spec) = self.find_remote_view_spec(&output) {
                        self.remember_remote_view(spec);
                    }
                }
                self.update_viewport_with_stream();
            }
            AgentEvent::ToolEnd {
                id,
                name,
                output,
                exit_code,
                metadata,
                ..
            } => {
                self.mark_agent_activity();
                let completed = self
                    .runtime
                    .end_tool(&id, name.clone(), output.clone(), exit_code);
                self.push_line(&render_tool_end(
                    &name,
                    exit_code,
                    &output,
                    metadata.as_ref(),
                    completed.args.as_ref(),
                    self.viewport_content_width(),
                ));
                self.record_runtime_tool_evidence(&name);
                self.capture_workflow(&name, completed.args.as_ref());
                if let Some(spec) = self.find_remote_view_spec(&output) {
                    self.remember_remote_view(spec);
                }
            }
            // Parallel/child task lifecycle (parallel_task, task) — show each
            // sub-task starting, its progress, and how it finished.
            AgentEvent::SubagentStart {
                task_id,
                agent,
                description,
                started_ms,
                ..
            } => {
                self.mark_agent_activity();
                self.finalize_streaming();
                self.record_runtime_parallel_evidence();
                // Track it in the live bottom panel instead of a transcript line.
                self.runtime.start_subagent(
                    task_id,
                    agent,
                    description,
                    instant_from_epoch_ms(started_ms),
                );
                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(t) = toks {
                    self.runtime.add_subagent_tokens(&task_id, t);
                }
            }
            AgentEvent::SubagentEnd {
                task_id,
                agent,
                output,
                success,
                finished_ms,
                ..
            } => {
                self.mark_agent_activity();
                self.runtime.end_subagent(
                    task_id,
                    agent.clone(),
                    success,
                    instant_from_epoch_ms(finished_ms),
                );
                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 / slow-down cadence.
                    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.runtime.remove_tool(&tool_id);
                self.approval_sel = 0;
                let label = tool_label(&tool_name, Some(&args));
                self.pending_tool = Some((tool_id, label));
                // Keep one pump parked on the event stream while awaiting input:
                // the confirmation can also resolve by timeout or an external
                // provider, and those events must clear the overlay.
                return self.rx.clone().map(pump);
            }
            AgentEvent::ConfirmationReceived {
                tool_id,
                approved,
                reason,
            } => {
                if let Some(label) = take_pending_tool_label(&mut self.pending_tool, &tool_id) {
                    self.state = State::Streaming;
                    if !approved {
                        let suffix = reason
                            .filter(|value| !value.trim().is_empty())
                            .map(|value| format!(" · {value}"))
                            .unwrap_or_default();
                        self.push_line(
                            &Style::new()
                                .fg(TN_RED)
                                .render(&format!("  ⎿ denied {label}{suffix}")),
                        );
                    }
                    return Some(self.resume_after_pending_confirmation());
                }
            }
            AgentEvent::ConfirmationTimeout {
                tool_id,
                action_taken,
            } => {
                if let Some(label) = take_pending_tool_label(&mut self.pending_tool, &tool_id) {
                    self.state = State::Streaming;
                    let (color, note) = if action_taken == "auto_approved" {
                        (
                            TN_YELLOW,
                            format!("  ⎿ confirmation timed out · auto-approved {label}"),
                        )
                    } else {
                        (
                            TN_RED,
                            format!("  ⎿ confirmation timed out · denied {label}"),
                        )
                    };
                    self.push_line(&Style::new().fg(color).render(&note));
                    return Some(self.resume_after_pending_confirmation());
                }
            }
            AgentEvent::PermissionDenied { tool_id, .. } => {
                self.runtime.remove_tool(&tool_id);
            }
            // 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 end 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;
                    }
                }
                // Asset 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();
                // Asset 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 an asset 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"));
            }
        }

        let subagents = self.runtime.subagents();
        if !subagents.is_empty() {
            prompt.push_str("\nSubagents:\n");
            for agent in 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;
        // 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.runtime.clear_turn_entities();
        self.ultracode_synthesis_inflight = false;
        self.relayout();
        self.stream_started = None;
        self.spinner.stop();
        self.rx = None;
        self.stream_join = None;
        self.host_progress_inflight = false;
        self.interrupting = false;
        self.rebuild_viewport();
    }

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

    /// Open an OS viewUrl in the native `a3s-webview` window. If the helper is
    /// not installed, fall back to the system browser and leave a transcript
    /// hint so the click never feels like a no-op.
    fn open_remote_view(&mut self, spec: &remote_ui::ViewSpec) {
        match remote_ui::open_window(spec) {
            Ok(remote_ui::OpenedWith::Webview) => {}
            Ok(remote_ui::OpenedWith::Browser) => {
                let helper = remote_ui::webview_helper_path()
                    .map(|path| path.display().to_string())
                    .unwrap_or_else(|| {
                        "missing; install a3s-webview or set A3S_WEBVIEW_BIN".to_string()
                    });
                self.push_line(&Style::new().fg(TN_YELLOW).render(&format!(
                    "  ↗ opened URL in browser: {} · authenticated RemoteUI popup helper: {helper}",
                    spec.url
                )));
            }
            Err(err) => {
                self.push_line(
                    &Style::new()
                        .fg(TN_GRAY)
                        .render(&format!("  🔗 open in your browser: {} ({err})", spec.url)),
                );
            }
        }
    }

    fn find_remote_view_spec(&self, output: &str) -> Option<remote_ui::ViewSpec> {
        // 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));
        remote_ui::find_view_url(output, os_origin.as_deref())
    }

    fn remember_remote_view(&mut self, spec: remote_ui::ViewSpec) {
        // Remember the view for `/view`, and surface a clickable "Open view"
        // line ourselves (deterministic) rather than trusting the model to
        // print the marker — weaker models often forget it or jq the `.view`
        // object away.
        let is_new = is_new_remote_view(self.last_view.as_ref(), &spec);
        self.last_view = Some(spec.clone());
        self.record_runtime_view_evidence();
        if is_new {
            self.push_line(&gutter(
                ACCENT,
                &remote_view_button("click or /view to open"),
            ));
        }
    }

    /// 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.replace_session(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 replace_session(&mut self, session: AgentSession) {
        self.session = Arc::new(session);
        self.session.register_dynamic_workflow_runtime();
        self.sync_runtime_tool();
    }

    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 dynamic workflow or `parallel_task`/`task` dispatch as a
    /// readable artifact for synthesis and a collapsed transcript marker.
    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);
        self.push_line(&Style::new().fg(ACCENT).render(&format!("{label}")));
    }

    /// Open read-only text content in the built-in IDE. 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(ide_flash_line(ToastKind::Warning, "read-only"));
        self.ide = Some(ide);
    }

    /// Format every retained tool call for the `/output` viewer.
    fn format_tool_log(&self) -> Option<String> {
        format_tool_log_records(self.runtime.tool_log(), self.viewport_content_width())
    }

    /// 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 (uneven cadence 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();
        let body = thinking_block(&self.thinking, self.viewport_content_width());
        if !body.is_empty() {
            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(tool) = self.runtime.live_tool() {
            let on = self.blink_tick % 8 < 4; // ~320ms on / 320ms off
            blocks.push(render_live_tool_activity(
                &tool.name,
                tool.args().as_ref(),
                tool.output(),
                self.viewport_content_width(),
                on,
            ));
        }
        // 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 handle_approval_mouse(&mut self, mouse: &MouseEvent) -> Option<Cmd<Msg>> {
        if self.state != State::Awaiting {
            return None;
        }
        let Some((_, label)) = &self.pending_tool else {
            return None;
        };
        let width = (self.width as usize).min(u16::MAX as usize);
        if width == 0 {
            return None;
        }
        let mut prompt = approval_prompt(label, self.approval_sel);
        let row_count = prompt.lines(width as u16, APPROVAL_PANEL_HEIGHT).len();
        if row_count == 0 {
            return None;
        }
        let y_offset = approval_overlay_y_offset(self.height as usize, row_count);
        let row = mouse.row as usize;
        let start = y_offset as usize;
        if row < start || row >= start.saturating_add(row_count) {
            return None;
        }
        prompt.set_y_offset(y_offset);
        let before = prompt.selected_index();

        match prompt.handle_mouse(mouse) {
            Some(ChoicePromptMsg::Selected(index)) => Some(cmd::msg(self.apply_approval(index))),
            Some(ChoicePromptMsg::Cancelled) => Some(cmd::msg(self.apply_approval(2))),
            None => {
                let after = prompt.selected_index().min(2);
                if after != before {
                    self.approval_sel = after;
                }
                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 menu = approval_menu_lines(label, self.approval_sel, self.width as usize);
        self.overlay_list(composed, &menu)
    }
}

fn approval_menu_lines(label: &str, selected: usize, width: usize) -> Vec<String> {
    approval_prompt(label, selected).lines(width as u16, APPROVAL_PANEL_HEIGHT)
}

const APPROVAL_OVERLAY_ROWS_BELOW: usize = 5;
const APPROVAL_PANEL_HEIGHT: usize = 5;

fn approval_prompt(label: &str, selected: usize) -> ChoicePrompt {
    ChoicePrompt::approval(format!("⏵ Allow {label}?"))
        .selected(selected)
        .indent(2)
        .marker("")
        .title_color(TN_YELLOW)
        .text_color(TN_FG)
        .muted_color(TN_GRAY)
        .danger_color(TN_RED)
        .selected_colors(Color::BrightWhite, ACCENT)
        .hint("Enter select · ↑/↓ · 1–3 · Esc")
}

fn approval_overlay_y_offset(screen_height: usize, row_count: usize) -> u16 {
    screen_height
        .saturating_sub(APPROVAL_OVERLAY_ROWS_BELOW)
        .saturating_sub(row_count)
        .min(u16::MAX as usize) as u16
}

/// 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 = default_model
        .as_ref()
        .map(|m| ctx_limit_for_model(&model_ctx, m))
        .unwrap_or_else(|| resolve_ctx_limit(None));

    // 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). Keep the human
    // confirmation wait separate from the tool execution timeout: reading and
    // deciding must not consume the tool's runtime budget.
    let confirmation = a3s_code_core::hitl::ConfirmationPolicy::enabled()
        .with_timeout(HITL_CONFIRM_TIMEOUT_MS, 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(
            tui_session_options(confirmation.clone())
                .with_session_store(store.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(
                tui_session_options(confirmation.clone())
                    .with_session_store(store.clone())
                    .with_session_id(session_id.as_str())
                    .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,
            ))),
        )?,
    };

    // DynamicWorkflowRuntime is always available in the TUI because built-in
    // `?` deep research and ultracode dynamic workflows both route through it.
    session.register_dynamic_workflow_runtime();

    // 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(transcript_markdown_width_for(width));
                    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 = delete-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",
        );

    remote_ui::prime_webview_lookup();

    let mut app = App {
        session,
        agent: agent.clone(),
        store: store.clone(),
        confirmation,
        session_id: session_id.clone(),
        models,
        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,
        runtime_expectation: 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_pending: false,
        sleep_pending: false,
        review: None,
        review_open: false,
        flow: None,
        pending_flow_subcommand: None,
        agent_picker: None,
        pending_agent_subcommand: None,
        agent_dev: None,
        mcp_picker: None,
        pending_mcp_subcommand: None,
        mcp_dev: None,
        skill_picker: None,
        pending_skill_subcommand: None,
        skill_dev: None,
        okf_picker: None,
        pending_okf_subcommand: None,
        okf_dev: None,
        autonomy_restore: 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,
        runtime: RuntimeProjection::default(),
        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,
        gradient_until: None,
        gradient_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(transcript_markdown_width_for(width)),
        got_delta: false,
        compacting: None,
        updating: None,
        last_paint: None,
        thinking: String::new(),
        state: State::Idle,
        messages: initial_messages,
        rx: None,
        stream_join: None,
        host_progress_inflight: false,
        interrupting: false,
        pending_tool: None,
        approval_sel: 0,
        history: history_seed,
        history_pos: None,
        model: default_model,
        output_tokens: 0,
        stream_started: None,
        blink_tick: 0,
        anim: 0,
        mode: Mode::Default,
        queue: BinaryHeap::new(),
        seq: 0,
        running_task: None,
        plan: Vec::new(),
        top: None,
        top_history: TopProcessHistory::default(),
        top_scroll: 0,
        top_sel: 0,
        top_focus: None,
        ide: None,
        memory: None,
        asset_list: None,
        runtime_activity: None,
        kb: None,
        loop_panel: None,
        help_open: false,
        help_scroll: 0,
        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.replace_session(s);
    }

    ProgramBuilder::new(app)
        .with_alt_screen()
        // Capture mouse input so wheel/trackpad scrolling works in the alternate
        // screen. Drag-copy is app-owned: on release we write the selected text to
        // the clipboard, so scroll and copy can coexist.
        .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) {
            Ok(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 err = std::process::Command::new(&bin).args(restart_args).exec();
                    eprintln!(
                        "\n⚠  updated, but restart via {} failed: {err}",
                        bin.display()
                    );
                    if let Ok(exe) = std::env::current_exe() {
                        let err = std::process::Command::new(&exe).args(restart_args).exec();
                        eprintln!("⚠  fallback restart via {} failed: {err}", exe.display());
                    }
                    eprintln!(
                        "✓ updated to a3s {latest}; resume manually with: a3s code resume {session_id}\n"
                    );
                }
                #[cfg(not(unix))]
                {
                    match std::process::Command::new(&bin).args(restart_args).status() {
                        Ok(status) if status.success() => {}
                        Ok(status) => eprintln!(
                            "\n⚠  updated, but restart exited with status {status}; resume manually with: a3s code resume {session_id}\n"
                        ),
                        Err(err) => eprintln!(
                            "\n⚠  updated, but restart failed: {err}; resume manually with: a3s code resume {session_id}\n"
                        ),
                    }
                }
            }
            Err(error) => {
                eprintln!("\n✗ upgrade failed: {error}");
                eprintln!("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::*;

    fn rgb(color: Color) -> (u8, u8, u8) {
        match color {
            Color::Rgb(r, g, b) => (r, g, b),
            other => panic!("expected RGB color, got {other:?}"),
        }
    }

    fn contains_cjk(s: &str) -> bool {
        s.chars().any(|ch| {
            ('\u{3400}'..='\u{4dbf}').contains(&ch)
                || ('\u{4e00}'..='\u{9fff}').contains(&ch)
                || ('\u{f900}'..='\u{faff}').contains(&ch)
        })
    }

    #[test]
    fn tui_palette_tracks_design_tokens() {
        assert_eq!(rgb(ACCENT), (0, 112, 243));
        assert_eq!(TN_GREEN, ACCENT);
        assert_eq!(rgb(TN_YELLOW), (245, 166, 35));
        assert_eq!(rgb(TN_RED), (238, 0, 0));
        assert_eq!(rgb(TN_CYAN), (80, 227, 194));
        assert_eq!(rgb(TN_FG), (237, 237, 237));
        assert_eq!(rgb(TN_GRAY), (143, 143, 143));
        assert_eq!(
            BRAND_GRADIENT,
            [
                Color::Rgb(0, 124, 240),
                Color::Rgb(0, 223, 216),
                TN_PURPLE,
                Color::Rgb(255, 0, 128),
                Color::Rgb(255, 77, 77),
                Color::Rgb(249, 203, 40),
            ]
        );
    }

    #[test]
    fn agent_chrome_theme_maps_tui_roles_to_code_palette() {
        let theme = agent_chrome_theme();
        assert_eq!(theme.primary, ACCENT);
        assert_eq!(theme.fg, TN_FG);
        assert_eq!(theme.muted, TN_GRAY);
        assert_eq!(theme.border, TN_GRAY);
        assert_eq!(theme.success, TN_GREEN);
        assert_eq!(theme.warning, TN_ORANGE);
        assert_eq!(theme.error, TN_RED);
        assert_eq!(theme.surface, SURFACE_SOFT);
        assert_eq!(theme.highlight, SURFACE_SELECTED);

        let chrome = agent_chrome(&theme);
        let rendered = chrome.tool_status("Running").view(24);
        assert!(
            rendered.contains(&ACCENT.fg_ansi()),
            "agent chrome should render code primary color: {rendered:?}"
        );
    }

    #[test]
    fn remote_view_button_is_styled_but_clickable_by_marker() {
        let rendered = remote_view_button("click or /view to open");
        let plain = a3s_tui::style::strip_ansi(&rendered);
        assert!(plain.contains(VIEW_BUTTON_MARKER), "{plain}");
        assert!(plain.contains("click or /view to open"), "{plain}");
        assert!(
            rendered.contains("\x1b["),
            "button should carry ANSI styling"
        );
    }

    #[test]
    fn remote_view_click_tolerates_small_terminal_mouse_drift() {
        let rendered = remote_view_button("click or /view to open");
        let view = format!("plain transcript\n{rendered}\nnext line");

        assert!(is_remote_view_click(
            &view,
            Selection {
                anchor: (1, 4),
                head: (1, 6),
            }
        ));
        assert!(!is_remote_view_click(
            &view,
            Selection {
                anchor: (1, 4),
                head: (1, 12),
            }
        ));
        assert!(!is_remote_view_click(
            &view,
            Selection {
                anchor: (1, 4),
                head: (2, 4),
            }
        ));
        assert!(!is_remote_view_click(
            &view,
            Selection {
                anchor: (0, 4),
                head: (0, 4),
            }
        ));
    }

    #[test]
    fn remote_view_click_marker_is_case_insensitive_after_ansi_strip() {
        let view = format!(
            "  {}\n",
            Style::new()
                .fg(Color::BrightWhite)
                .bg(ACCENT)
                .render(" ↗ Open View ")
        );

        assert!(is_remote_view_click(
            &view,
            Selection {
                anchor: (0, 3),
                head: (0, 3),
            }
        ));
    }

    #[test]
    fn quit_key_accepts_control_c_terminal_variants() {
        let key = |code, modifiers| KeyEvent { code, modifiers };

        assert!(is_quit_key(&key(KeyCode::Char('c'), KeyModifiers::CONTROL)));
        assert!(is_quit_key(&key(
            KeyCode::Char('C'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT
        )));
        assert!(!is_quit_key(&key(KeyCode::Char('c'), KeyModifiers::NONE)));
        assert!(!is_quit_key(&key(
            KeyCode::Char('v'),
            KeyModifiers::CONTROL
        )));
    }

    #[test]
    fn quit_confirmation_requires_second_press_inside_window() {
        let now = Instant::now();

        assert!(!quit_is_confirmed(None, now));
        if let Some(recent) = now.checked_sub(Duration::from_millis(500)) {
            assert!(quit_is_confirmed(Some(recent), now));
        }
        if let Some(stale) = now.checked_sub(Duration::from_secs(3)) {
            assert!(!quit_is_confirmed(Some(stale), now));
        }
    }

    #[test]
    fn footer_uses_shared_status_components() {
        let status = render_session_status_line(
            "/Users/roylin/code/a3s",
            Some("main"),
            Some("openai/gpt-5"),
            128_000,
            90_000,
            0,
            [SessionStatusChip::new("", "1 running").color(TN_GRAY)],
            72,
        );
        let status_plain = a3s_tui::style::strip_ansi(&status);

        assert_eq!(a3s_tui::style::visible_len(&status), 72);
        assert!(status_plain.contains("a3s git:(main)"), "{status_plain}");
        assert!(
            status_plain.contains("gpt-5 (128k context)"),
            "{status_plain}"
        );
        assert!(status_plain.contains("ctx:70%"), "{status_plain}");
        assert!(status_plain.contains("⚙ 1 running"), "{status_plain}");
        assert!(status.contains("\x1b["), "status should be styled");

        let mode = render_mode_status_line(Mode::Auto, 48);
        let mode_plain = a3s_tui::style::strip_ansi(&mode);
        assert_eq!(a3s_tui::style::visible_len(&mode), 48);
        assert!(mode_plain.starts_with("  ⏵⏵ auto mode on"), "{mode_plain}");
        assert!(mode_plain.contains("/help"), "{mode_plain}");
        assert!(mode.contains("\x1b["), "mode line should be styled");
    }

    #[test]
    fn jump_to_latest_hint_uses_shared_inline_action() {
        let hint = jump_to_latest_hint(48);
        let plain = a3s_tui::style::strip_ansi(&hint);

        assert_eq!(a3s_tui::style::visible_len(&hint), 48);
        assert!(plain.contains("↓ more below"), "{plain}");
        assert!(plain.contains("Shift+End"), "{plain}");
        assert!(hint.contains("\x1b["), "hint should be styled");
        assert_eq!(jump_to_latest_hint(0), "");
    }

    #[test]
    fn tui_session_options_sets_separate_tool_timeout() {
        let confirmation = a3s_code_core::hitl::ConfirmationPolicy::enabled()
            .with_timeout(HITL_CONFIRM_TIMEOUT_MS, TimeoutAction::Reject);
        let opts = tui_session_options(confirmation);
        let dbg = format!("{opts:?}");

        assert_ne!(HITL_CONFIRM_TIMEOUT_MS, TOOL_EXEC_TIMEOUT_MS);
        assert!(
            dbg.contains(&format!("tool_timeout_ms: Some({TOOL_EXEC_TIMEOUT_MS})")),
            "{dbg}"
        );
    }

    #[test]
    fn approval_menu_uses_shared_choice_prompt() {
        let lines = approval_menu_lines(
            "Bash(cargo test very-long-filter-name-that-should-not-overflow)",
            1,
            42,
        );
        let plain = lines
            .iter()
            .map(|line| a3s_tui::style::strip_ansi(line))
            .collect::<Vec<_>>();

        assert_eq!(plain.len(), 5);
        assert!(plain[0].contains("Allow"), "{plain:?}");
        assert!(plain[1].contains("1. Yes"), "{plain:?}");
        assert!(plain[2].contains("2. Yes, and"), "{plain:?}");
        assert!(plain[3].contains("3. No"), "{plain:?}");
        assert!(plain[4].contains("Enter select"), "{plain:?}");
        assert!(
            lines
                .iter()
                .all(|line| a3s_tui::style::visible_len(line) <= 42),
            "{plain:?}"
        );
        assert!(lines[2].contains("\x1b["), "selected row is styled");
    }

    #[test]
    fn approval_prompt_mouse_wheel_moves_selection_at_overlay_offset() {
        use a3s_tui::event::{MouseEvent, MouseEventKind};

        let width = 42;
        let lines = approval_menu_lines("Bash(cargo test)", 0, width);
        let y_offset = approval_overlay_y_offset(18, lines.len());
        let mut prompt = approval_prompt("Bash(cargo test)", 0);
        prompt.set_y_offset(y_offset);

        let msg = prompt.handle_mouse(&MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 0,
            row: y_offset + 1,
            modifiers: KeyModifiers::NONE,
        });

        assert_eq!(msg, None);
        assert_eq!(prompt.selected_index(), 1);
    }

    #[test]
    fn approval_prompt_click_selects_choice_at_overlay_offset() {
        use a3s_tui::event::{MouseButton, MouseEvent, MouseEventKind};

        let width = 42;
        let lines = approval_menu_lines("Bash(cargo test)", 0, width);
        let y_offset = approval_overlay_y_offset(18, lines.len());
        let mut prompt = approval_prompt("Bash(cargo test)", 0);
        prompt.set_y_offset(y_offset);

        let msg = prompt.handle_mouse(&MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 2,
            row: y_offset + 2,
            modifiers: KeyModifiers::NONE,
        });

        assert_eq!(msg, Some(ChoicePromptMsg::Selected(1)));
    }

    #[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()),
            token_logprobs: Vec::new(),
            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()),
            token_logprobs: Vec::new(),
            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: ultracode registers A3S Flow plus `task`/`parallel_task` in the
    /// session tool surface (so dynamic workflows and fan-out have tools 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();
        session.register_dynamic_workflow_runtime();
        let names = session.tool_names();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            names.contains(&"dynamic_workflow".to_string()),
            "dynamic_workflow registered; got {names:?}"
        );
        assert!(
            names.contains(&"parallel_task".to_string()),
            "parallel_task registered; got {names:?}"
        );
        assert!(
            names.contains(&"task".to_string()),
            "task registered; got {names:?}"
        );
    }

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

    #[test]
    fn format_tool_log_renders_bounded_headers_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, 48).unwrap();
        let plain = a3s_tui::style::strip_ansi(&out);
        assert!(plain.contains("#1 · Read /x · ok"), "{plain}");
        assert!(plain.contains("args: {\"file_path\":\"/x\"}"), "{plain}");
        assert!(
            plain.contains("    hello"),
            "output should be indented: {plain}"
        );
        assert!(plain.contains("#2 · Ran · exit 2"), "{plain}");
        for line in out.lines() {
            assert!(
                a3s_tui::style::visible_len(line) <= 48,
                "log line should be bounded: {line:?}"
            );
        }
    }

    #[test]
    fn format_tool_log_tails_long_output() {
        let recs = vec![ToolCallRecord {
            name: "bash".into(),
            args: Some(serde_json::json!({
                "command": "cargo test a-very-long-filter-that-must-not-overflow -- --nocapture"
            })),
            output: (0..30)
                .map(|i| format!("line-{i}-with-a-long-payload-that-must-stay-inside-the-editor"))
                .collect::<Vec<_>>()
                .join("\n"),
            exit_code: 0,
        }];
        let out = format_tool_log_records(&recs, 52).unwrap();
        let plain = a3s_tui::style::strip_ansi(&out);

        assert!(plain.contains("... +6 earlier lines"), "{plain}");
        assert!(!plain.contains("line-0-with"), "{plain}");
        assert!(plain.contains("line-6-with"), "{plain}");
        for line in out.lines() {
            assert!(
                a3s_tui::style::visible_len(line) <= 52,
                "log line should be bounded: {line:?}"
            );
        }
    }

    #[test]
    fn format_tool_log_respects_narrow_editor_width() {
        let recs = vec![ToolCallRecord {
            name: "bash".into(),
            args: Some(serde_json::json!({
                "command": "printf a-very-long-line-that-used-to-force-a-minimum-width"
            })),
            output: "a-very-long-output-line-that-must-be-clipped\n".into(),
            exit_code: 0,
        }];
        let out = format_tool_log_records(&recs, 16).unwrap();

        for line in out.lines() {
            assert!(
                a3s_tui::style::visible_len(line) <= 16,
                "log line should respect narrow width: {line:?}"
            );
        }
    }

    #[test]
    fn pending_tool_label_is_taken_only_for_matching_tool_id() {
        let mut pending = Some(("tool-a".to_string(), "edit file".to_string()));

        assert!(take_pending_tool_label(&mut pending, "tool-b").is_none());
        assert_eq!(
            pending,
            Some(("tool-a".to_string(), "edit file".to_string()))
        );

        assert_eq!(
            take_pending_tool_label(&mut pending, "tool-a"),
            Some("edit file".to_string())
        );
        assert!(pending.is_none());
    }

    #[tokio::test]
    async fn confirmation_resume_rearms_spinner_and_stream_pump() {
        let cmd = resume_after_pending_confirmation_cmd(None);
        match cmd.await {
            a3s_tui::cmd::CmdResult::Batch(cmds) => {
                assert_eq!(cmds.len(), 1, "spinner should resume without an rx");
            }
            _ => panic!("expected batched resume command"),
        }

        let (_tx, rx) = mpsc::channel::<AgentEvent>(1);
        let cmd = resume_after_pending_confirmation_cmd(Some(std::sync::Arc::new(
            tokio::sync::Mutex::new(rx),
        )));
        match cmd.await {
            a3s_tui::cmd::CmdResult::Batch(cmds) => {
                assert_eq!(cmds.len(), 2, "spinner and stream pump should resume");
            }
            _ => panic!("expected batched resume command"),
        }
    }

    // ── `?` deep-research mode ─────────────────────────────────────────────
    #[test]
    fn deep_research_prompt_directs_research_and_keeps_query() {
        let p = deep_research_prompt("rust async runtimes", false);
        assert!(p.contains("rust async runtimes"), "{p}");
        let lo = p.to_lowercase();
        assert!(lo.contains("deep research"), "{p}");
        assert!(p.contains("dynamic_workflow"), "{p}");
        assert!(lo.contains("web search") && lo.contains("web_fetch"), "{p}");
        assert!(lo.contains("source"), "should ask to cite sources: {p}");
        assert!(
            p.contains("step_name: \"parallel_task\"") || p.contains("parallel_task"),
            "{p}"
        );
        assert!(p.contains(".a3s/research/<slug>/"), "{p}");
        assert!(p.contains("standalone HTML"), "{p}");
    }

    #[test]
    fn deep_research_prompt_uses_os_runtime_and_remoteui_when_available() {
        let p = deep_research_prompt("rust async runtimes", true);
        assert!(p.contains("rust async runtimes"), "{p}");
        assert!(p.contains("dynamic_workflow"), "{p}");
        assert!(p.contains("OS A3S Runtime") && p.contains("runtime"), "{p}");
        assert!(p.contains("Runtime evidence is required"), "{p}");
        assert!(p.contains("`runtime`"), "{p}");
        assert!(p.contains("allowed_tools: [\"runtime\"]"), "{p}");
        assert!(p.contains("result.exitCode !== 0"), "{p}");
        assert!(p.contains("runtime tool failed"), "{p}");
        assert!(p.contains("shaped:true"), "{p}");
        assert!(p.contains("RemoteUI"), "{p}");
        assert!(p.contains(".view") && p.contains("viewUrl"), "{p}");
        assert!(p.contains("must include `dynamic_workflow`"), "{p}");
        assert!(
            p.contains("Markdown report") && p.contains("HTML page"),
            "{p}"
        );
    }

    #[test]
    fn deep_research_workflow_args_use_runtime_then_local_fallback() {
        let args = deep_research_workflow_args("rust async runtimes", true);
        let source = args["source"].as_str().unwrap();

        assert_eq!(args["input"]["query"], "rust async runtimes");
        assert_eq!(args["input"]["os_runtime"], true);
        assert_eq!(args["allowed_tools"], serde_json::json!(["runtime"]));
        assert!(source.contains("ctx.tool(\"runtime\""), "{source}");
        assert!(source.contains("runtime_error"), "{source}");
        assert!(source.contains("local_fallback"), "{source}");
        assert!(source.contains("step_name: \"parallel_task\""), "{source}");
        assert!(source.contains("agent: \"general\""), "{source}");
        assert!(!source.contains("agent: \"explore\""), "{source}");
    }

    #[test]
    fn deep_research_synthesis_prompt_uses_host_workflow_evidence() {
        let prompt = deep_research_synthesis_prompt(
            "rust async runtimes",
            true,
            r#"{"mode":"os_runtime"}"#,
            Some(&serde_json::json!({
                "dynamic_workflow": {
                    "snapshot": {
                        "steps": {
                            "runtime_research": {
                                "output": { "name": "runtime" }
                            }
                        }
                    }
                }
            })),
        );

        assert!(
            prompt.contains("Do not call `dynamic_workflow` again"),
            "{prompt}"
        );
        assert!(prompt.contains("rust async runtimes"), "{prompt}");
        assert!(prompt.contains("mode\":\"os_runtime"), "{prompt}");
        assert!(prompt.contains("shaped:true"), "{prompt}");
    }

    #[test]
    fn deep_research_metadata_detects_runtime_and_local_parallel_evidence() {
        let metadata = serde_json::json!({
            "dynamic_workflow": {
                "snapshot": {
                    "steps": {
                        "runtime_research": {
                            "output": { "name": "runtime" }
                        },
                        "local_fallback": {
                            "output": { "tool": "parallel_task" }
                        }
                    }
                }
            }
        });

        assert!(json_contains_tool_evidence(&metadata, "runtime"));
        assert!(json_contains_tool_evidence(&metadata, "parallel_task"));
        assert!(!json_contains_tool_evidence(&metadata, "program"));
    }

    #[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");
        // Wide 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 mouse_selection_uses_release_position_clamped_to_viewport() {
        assert_eq!(viewport_mouse_cell(2, 40, 4, 20), Some((2, 20)));
        assert_eq!(viewport_mouse_cell(4, 2, 4, 20), None);
        assert_eq!(viewport_mouse_cell_clamped(9, 40, 4, 20), Some((3, 20)));
        assert_eq!(viewport_mouse_cell_clamped(0, 1, 0, 20), None);
    }

    #[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:?}"
        );
    }

    #[test]
    fn tui_default_policy_allows_readonly_research_tools() {
        use a3s_code_core::permissions::PermissionDecision;

        let policy = tui_permission_policy();

        assert_eq!(
            policy.check(
                "web_fetch",
                &serde_json::json!({"url": "https://example.com"})
            ),
            PermissionDecision::Allow
        );
        assert_eq!(
            policy.check("web_search", &serde_json::json!({"query": "a3s"})),
            PermissionDecision::Allow
        );
        assert_eq!(
            policy.check("read", &serde_json::json!({"file_path": "README.md"})),
            PermissionDecision::Allow
        );
        assert_eq!(
            policy.check(
                "write",
                &serde_json::json!({"file_path": "x", "content": "y"})
            ),
            PermissionDecision::Ask,
            "mutating tools must still go through TUI confirmation"
        );
    }

    #[tokio::test]
    async fn tui_session_policy_does_not_block_web_fetch() {
        let dir = std::env::temp_dir().join(format!(
            "a3s-web-fetch-policy-{}-{}",
            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 llm = Arc::new(CaptureLlmClient::new(vec![
            tool_call_response("web_fetch", serde_json::json!({"url": "not-a-url"})),
            done_response(),
        ]));
        let confirmation = a3s_code_core::hitl::ConfirmationPolicy::enabled()
            .with_timeout(300, TimeoutAction::Reject);
        let opts = tui_session_options(confirmation)
            .with_llm_client(llm)
            .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("Fetch a URL for research.", None)
            .await
            .unwrap();
        let mut saw_fetch_end = None;
        while let Some(event) = rx.recv().await {
            match event {
                a3s_code_core::AgentEvent::ToolEnd {
                    name,
                    output,
                    exit_code,
                    ..
                } if name == "web_fetch" => {
                    saw_fetch_end = Some((output, exit_code));
                }
                a3s_code_core::AgentEvent::PermissionDenied {
                    tool_name, reason, ..
                } => panic!("{tool_name} was denied: {reason}"),
                a3s_code_core::AgentEvent::End { .. } => break,
                a3s_code_core::AgentEvent::Error { message } => panic!("{message}"),
                _ => {}
            }
        }
        join.await.unwrap();
        let _ = std::fs::remove_dir_all(&dir);

        let (output, exit_code) = saw_fetch_end.expect("web_fetch should run");
        assert_ne!(exit_code, 0, "invalid URL should fail validation");
        assert!(
            !output.contains("Permission denied"),
            "web_fetch should not be blocked by permission policy: {output}"
        );
    }

    #[tokio::test]
    async fn hitl_wait_does_not_consume_tool_timeout_budget() {
        let dir = std::env::temp_dir().join(format!(
            "a3s-hitl-timeout-{}-{}",
            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("sample.txt"), "timeout sentinel").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("read", serde_json::json!({"file_path": "sample.txt"})),
            done_response(),
        ]));
        let confirmation = a3s_code_core::hitl::ConfirmationPolicy::enabled()
            .with_timeout(5_000, TimeoutAction::Reject);
        let opts = tui_session_options(confirmation)
            .with_tool_timeout(300)
            .with_llm_client(llm)
            .with_permission_policy(a3s_code_core::permissions::PermissionPolicy::new())
            .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("Read sample.txt.", None).await.unwrap();
        let mut saw_confirmation = false;
        let mut tool_output = None;
        while let Some(event) = rx.recv().await {
            match event {
                a3s_code_core::AgentEvent::ConfirmationRequired { tool_id, .. } => {
                    saw_confirmation = true;
                    tokio::time::sleep(Duration::from_millis(500)).await;
                    assert!(session
                        .confirm_tool_use(&tool_id, true, None)
                        .await
                        .unwrap());
                }
                a3s_code_core::AgentEvent::ToolEnd {
                    output, exit_code, ..
                } => {
                    assert_eq!(exit_code, 0, "{output}");
                    assert!(!output.contains("timed out"), "{output}");
                    tool_output = Some(output);
                }
                a3s_code_core::AgentEvent::End { .. } => break,
                a3s_code_core::AgentEvent::Error { message } => panic!("{message}"),
                _ => {}
            }
        }
        join.await.unwrap();
        let _ = std::fs::remove_dir_all(&dir);

        assert!(saw_confirmation, "the tool call should require HITL");
        assert!(
            tool_output
                .as_deref()
                .is_some_and(|output| output.contains("timeout sentinel")),
            "tool output should come from read, got {tool_output:?}"
        );
    }

    #[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 workflow_doc_captures_dynamic_workflow_tool_without_flow_command() {
        let args = serde_json::json!({
            "source": "async function run(ctx, inputs) { return { type: 'complete', output: inputs }; }"
        });
        let (doc, label) = workflow_doc_for_tool("dynamic_workflow", Some(&args)).unwrap();

        assert!(
            label.contains("dynamic workflow script captured"),
            "{label}"
        );
        assert!(!label.contains("/flow"), "{label}");
        assert!(doc.contains("async function run"));
    }

    #[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_wide_unicode_heavier_than_ascii() {
        assert_eq!(estimate_tokens("abcd"), 1); // ASCII ~4 chars/token
        assert_eq!(estimate_tokens("かなテストあ"), 6); // wide text ~1 token/char
        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 ctx_limit_prefers_declared_then_infers_account_models() {
        let mut ctx = std::collections::HashMap::new();
        ctx.insert("openai/gpt-5".to_string(), 256_000);

        assert_eq!(ctx_limit_for_model(&ctx, "openai/gpt-5"), 256_000);
        assert_eq!(inferred_ctx_limit("claude-sonnet-4-6"), Some(200_000));
        assert_eq!(inferred_ctx_limit("claude-opus-4-8[1m]"), Some(1_000_000));
        assert_eq!(inferred_ctx_limit("gpt-4.1"), Some(1_000_000));
        assert_eq!(inferred_ctx_limit("glm-5.1"), Some(DEFAULT_CONTEXT_LIMIT));
        assert_eq!(
            ctx_limit_for_model(&ctx, "unknown-model"),
            DEFAULT_CONTEXT_LIMIT
        );
    }

    #[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 slash_tail_requires_a_token_boundary() {
        let parameterized = [
            "/login", "/ctx", "/kb", "/okf", "/btw", "/goal", "/loop", "/sleep", "/flow", "/agent",
            "/mcp", "/skill",
        ];

        for cmd in parameterized {
            assert_eq!(slash_tail(cmd, cmd), Some(""), "{cmd} accepts bare form");
            assert_eq!(
                slash_tail(&format!("{cmd} argument"), cmd),
                Some(" argument"),
                "{cmd} accepts whitespace-delimited arguments"
            );
            assert_eq!(
                slash_tail(&format!("{cmd}x"), cmd),
                None,
                "{cmd}x must remain a normal message, not {cmd}"
            );
            assert_eq!(
                slash_tail(&format!("{cmd}-token"), cmd),
                None,
                "{cmd}-token must remain a normal message, not {cmd}"
            );
        }
    }

    #[test]
    fn cloned_asset_focus_matches_only_paths_inside_the_clone_root() {
        let clone_root = std::path::Path::new("/tmp/a3s-assets/weather-agent");
        assert!(App::path_is_within(clone_root, clone_root));
        assert!(App::path_is_within(
            std::path::Path::new("/tmp/a3s-assets/weather-agent/agent.md"),
            clone_root
        ));
        assert!(App::path_is_within(
            std::path::Path::new("/tmp/a3s-assets/weather-agent/nested/asset.json"),
            clone_root
        ));
        assert!(!App::path_is_within(
            std::path::Path::new("/tmp/a3s-assets/weather-agent-2/agent.md"),
            clone_root
        ));
    }

    #[test]
    fn runtime_asset_query_carries_asset_category_and_terms() {
        assert_eq!(
            runtime_asset_query("mcp", "Calc Tools", "failed calls"),
            "category:mcp Calc Tools failed calls"
        );
        assert_eq!(
            runtime_asset_query("workflow", "daily-flow", ""),
            "category:workflow daily-flow"
        );
        assert_eq!(runtime_asset_query("", "", "stale"), "stale");
    }

    #[test]
    fn slash_command_registry_is_unique_english_and_idle_safe() {
        let mut seen = HashSet::new();
        for (cmd, desc) in SLASH_COMMANDS {
            assert!(cmd.starts_with('/'), "{cmd} should be a slash command");
            assert!(
                !cmd.contains(char::is_whitespace),
                "{cmd} should be the bare command token"
            );
            assert!(seen.insert(*cmd), "{cmd} should not be registered twice");
            assert!(
                !desc.trim().is_empty(),
                "{cmd} should have a menu description"
            );
            assert!(
                !contains_cjk(desc),
                "{cmd} description should stay English-only: {desc}"
            );
            assert!(
                !desc.to_ascii_lowercase().contains("repo"),
                "{cmd} slash-menu copy should not expose asset-workspace management: {desc}"
            );
        }

        for cmd in IDLE_ONLY {
            assert!(
                SLASH_COMMANDS
                    .iter()
                    .any(|(registered, _)| registered == cmd),
                "{cmd} is idle-only but missing from the slash registry"
            );
        }

        let removed_commands = [
            "im", "run", "deploy", "review", "list", "ps", "workflow", "repo", "git", "relay",
        ]
        .into_iter()
        .map(|name| format!("/{name}"))
        .chain([
            format!("/{}{}", "evo", "lve"),
            format!("/{}{}", "evo", "love"),
        ]);
        for removed in removed_commands {
            assert!(
                !SLASH_COMMANDS
                    .iter()
                    .any(|(cmd, _)| *cmd == removed.as_str()),
                "{removed} should stay removed from the slash registry"
            );
        }
    }

    #[test]
    fn asset_root_commands_are_backed_by_lifecycle_services() {
        let asset_commands: HashSet<&str> = asset_lifecycle::ASSET_LIFECYCLES
            .iter()
            .map(|lifecycle| lifecycle.command)
            .collect();
        assert_eq!(
            asset_commands,
            HashSet::from(["/agent", "/mcp", "/skill", "/okf", "/flow"])
        );

        for command in asset_commands {
            let menu_desc = SLASH_COMMANDS
                .iter()
                .find_map(|(cmd, desc)| (*cmd == command).then_some(*desc))
                .unwrap_or_else(|| panic!("{command} should be registered in the slash menu"));
            let services: HashSet<&str> = asset_lifecycle::ASSET_LIFECYCLES
                .iter()
                .filter(|lifecycle| lifecycle.command == command)
                .map(|lifecycle| asset_lifecycle::service_label(lifecycle.service))
                .collect();

            for service in services {
                assert!(
                    menu_desc.contains(service),
                    "{command} slash-menu copy should name {service}: {menu_desc}"
                );
            }
            assert!(
                !menu_desc.contains("lifecycle"),
                "{command} slash-menu copy should name concrete OS services, not generic lifecycle wording: {menu_desc}"
            );
        }
    }

    #[test]
    fn cancel_pending_picker_clears_panel_and_deferred_asset_command() {
        let mut picker = Some("agent selector");
        let mut pending = Some("review");

        cancel_pending_picker(&mut picker, &mut pending);

        assert!(picker.is_none());
        assert!(pending.is_none());
    }

    #[test]
    fn registered_slash_commands_have_declared_handler_paths() {
        let parameterized = HashSet::from([
            "/login", "/ctx", "/kb", "/okf", "/btw", "/goal", "/loop", "/sleep", "/flow", "/agent",
            "/mcp", "/skill",
        ]);
        let exact = HashSet::from([
            "/logout", "/exit", "/fork", "/clear", "/init", "/compact", "/help", "/view", "/auto",
            "/config", "/model", "/effort", "/top", "/ide", "/plugin", "/theme", "/output",
            "/reload", "/update", "/memory",
        ]);

        for (cmd, _) in SLASH_COMMANDS {
            assert!(
                parameterized.contains(cmd) || exact.contains(cmd),
                "{cmd} is registered but not mapped to a handler category"
            );
        }
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum SlashHandlerKind {
        Exact,
        Parameterized,
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum SlashRuntimeScope {
        Local,
        OsAccount,
        RuntimeConditional,
    }

    #[derive(Clone, Copy, Debug)]
    struct SlashAuditRow {
        command: &'static str,
        handler: SlashHandlerKind,
        idle_only: bool,
        scope: SlashRuntimeScope,
    }

    fn slash_audit_rows() -> Vec<SlashAuditRow> {
        use SlashHandlerKind::{Exact, Parameterized};
        use SlashRuntimeScope::{Local, OsAccount, RuntimeConditional};

        vec![
            SlashAuditRow {
                command: "/model",
                handler: Exact,
                idle_only: true,
                scope: OsAccount,
            },
            SlashAuditRow {
                command: "/init",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/config",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/theme",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/flow",
                handler: Parameterized,
                idle_only: true,
                scope: OsAccount,
            },
            SlashAuditRow {
                command: "/agent",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/mcp",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/skill",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/okf",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/output",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/login",
                handler: Parameterized,
                idle_only: false,
                scope: OsAccount,
            },
            SlashAuditRow {
                command: "/logout",
                handler: Exact,
                idle_only: false,
                scope: OsAccount,
            },
            SlashAuditRow {
                command: "/view",
                handler: Exact,
                idle_only: false,
                scope: OsAccount,
            },
            SlashAuditRow {
                command: "/plugin",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/reload",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/update",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/btw",
                handler: Parameterized,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/top",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/ide",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/memory",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/kb",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/ctx",
                handler: Parameterized,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/effort",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/compact",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/goal",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/loop",
                handler: Parameterized,
                idle_only: true,
                scope: RuntimeConditional,
            },
            SlashAuditRow {
                command: "/sleep",
                handler: Parameterized,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/help",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/fork",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/clear",
                handler: Exact,
                idle_only: true,
                scope: Local,
            },
            SlashAuditRow {
                command: "/auto",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
            SlashAuditRow {
                command: "/exit",
                handler: Exact,
                idle_only: false,
                scope: Local,
            },
        ]
    }

    #[test]
    fn slash_command_audit_matrix_matches_registry_and_policies() {
        let rows = slash_audit_rows();
        let registered = SLASH_COMMANDS
            .iter()
            .map(|(cmd, _)| *cmd)
            .collect::<HashSet<_>>();
        let audited = rows.iter().map(|row| row.command).collect::<HashSet<_>>();

        assert_eq!(
            registered, audited,
            "every registered command must have explicit audit metadata"
        );

        let idle_from_rows = rows
            .iter()
            .filter(|row| row.idle_only)
            .map(|row| row.command)
            .collect::<HashSet<_>>();
        let idle_from_const = IDLE_ONLY.iter().copied().collect::<HashSet<_>>();
        assert_eq!(
            idle_from_rows, idle_from_const,
            "idle-only policy should stay in sync with the audit matrix"
        );

        let parameterized_names = HashSet::from([
            "/login", "/ctx", "/kb", "/okf", "/btw", "/goal", "/loop", "/sleep", "/flow", "/agent",
            "/mcp", "/skill",
        ]);
        for row in &rows {
            match row.handler {
                SlashHandlerKind::Parameterized => {
                    assert!(
                        parameterized_names.contains(row.command),
                        "{} should be in the token-boundary handler set",
                        row.command
                    );
                    assert!(
                        slash_tail(row.command, row.command).is_some(),
                        "{} should be token-boundary parsed",
                        row.command
                    );
                }
                SlashHandlerKind::Exact => {
                    assert!(
                        !parameterized_names.contains(row.command),
                        "{} exact command should not be in the token-boundary handler set",
                        row.command
                    );
                }
            }
        }

        let loop_row = rows.iter().find(|row| row.command == "/loop").unwrap();
        assert_eq!(loop_row.scope, SlashRuntimeScope::RuntimeConditional);
        for cmd in ["/agent", "/mcp", "/skill", "/okf", "/kb", "/ctx"] {
            let row = rows.iter().find(|row| row.command == cmd).unwrap();
            assert_eq!(row.scope, SlashRuntimeScope::Local);
        }
    }

    #[test]
    fn removed_top_level_aliases_stay_unregistered() {
        let removed = [
            "/mouse".to_string(),
            "/plugins".to_string(),
            "/quit".to_string(),
            format!("/{}{}", "re", "po"),
            format!("/{}{}", "re", "lay"),
        ];
        for alias in removed {
            assert!(
                !SLASH_COMMANDS.iter().any(|(cmd, _)| *cmd == alias.as_str()),
                "{alias} should stay removed from the slash registry"
            );
        }
    }

    #[test]
    fn ampersand_clone_review_syntax_stays_removed() {
        assert!(
            slash_candidates("&").is_empty(),
            "asset clone shortcuts must not return to the slash menu"
        );
        assert!(
            !SLASH_COMMANDS.iter().any(|(cmd, _)| cmd.starts_with('&')),
            "asset clone/review flows must stay under typed asset subcommands"
        );
    }

    #[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"));
    }

    #[test]
    fn asset_workflow_commands_are_idle_only_and_listed() {
        for cmd in ["/flow", "/agent", "/mcp", "/skill", "/okf"] {
            assert!(
                IDLE_ONLY.contains(&cmd),
                "{cmd} must not arm asset workflows while another turn is running"
            );
            assert!(
                SLASH_COMMANDS.iter().any(|(name, _)| *name == cmd),
                "{cmd} should be visible in the slash menu while idle"
            );
        }
    }

    #[test]
    fn runtime_activity_are_asset_scoped_not_top_level() {
        let top_level_ps = format!("/{}", "ps");
        assert!(
            !SLASH_COMMANDS
                .iter()
                .any(|(name, _)| *name == top_level_ps.as_str()),
            "runtime activity browsing should stay asset-scoped"
        );
        assert!(matches!(
            panels::agent::parse_agent_subcommand("activity")
                .unwrap()
                .unwrap(),
            panels::agent::AgentSubcommand::Activity(_)
        ));
        assert!(panels::agent::parse_agent_subcommand("ps")
            .unwrap()
            .is_err());
        assert!(matches!(
            panels::mcp::parse_mcp_subcommand("activity")
                .unwrap()
                .unwrap(),
            panels::mcp::McpSubcommand::Activity(_)
        ));
        assert!(panels::mcp::parse_mcp_subcommand("ps").unwrap().is_err());
        assert!(matches!(
            panels::flow::parse_flow_subcommand("activity")
                .unwrap()
                .unwrap(),
            panels::flow::FlowSubcommand::Activity(_)
        ));
        assert!(panels::flow::parse_flow_subcommand("ps").unwrap().is_err());
        assert!(matches!(
            panels::skill::parse_skill_subcommand("activity")
                .unwrap()
                .unwrap(),
            panels::skill::SkillSubcommand::Activity(_)
        ));
        assert!(panels::skill::parse_skill_subcommand("ps")
            .unwrap()
            .is_err());
        assert!(matches!(
            panels::okf::parse_okf_command("activity"),
            panels::okf::OkfCommand::Activity(_)
        ));
        assert!(matches!(
            panels::okf::parse_okf_command("ps"),
            panels::okf::OkfCommand::Usage(_)
        ));
    }

    #[test]
    fn runtime_expectation_warns_once_until_evidence_arrives() {
        let mut missing = RuntimeExpectation::required("deep research");
        let warning = missing.missing_warning().unwrap();
        assert!(warning.contains("Runtime evidence missing"), "{warning}");
        assert!(missing.missing_warning().is_none());

        let mut via_runtime = RuntimeExpectation::required("run");
        via_runtime.record_tool("runtime");
        assert!(via_runtime.is_satisfied());
        assert!(via_runtime.missing_warning().is_none());

        let mut via_parallel = RuntimeExpectation::required("review");
        via_parallel.record_tool("parallel_task");
        assert!(via_parallel.is_satisfied());

        let mut via_dynamic_workflow = RuntimeExpectation::required("research");
        via_dynamic_workflow.record_tool("dynamic_workflow");
        assert!(via_dynamic_workflow.is_satisfied());

        let mut via_view = RuntimeExpectation::required("deploy");
        via_view.record_remote_view();
        assert!(via_view.is_satisfied());

        let mut report_only_runtime = RuntimeExpectation::required_report_view("deep research");
        report_only_runtime.record_tool("runtime");
        assert!(!report_only_runtime.is_satisfied());
        let warning = report_only_runtime.missing_warning().unwrap();
        assert!(warning.contains("report"), "{warning}");
        assert!(warning.contains(".view"), "{warning}");
        let correction = report_only_runtime.corrective_prompt().unwrap();
        assert!(correction.contains("deep research"), "{correction}");
        assert!(correction.contains("dynamic_workflow"), "{correction}");
        assert!(correction.contains("OS Runtime"), "{correction}");
        assert!(correction.contains(".view"), "{correction}");
        assert!(correction.contains("viewUrl"), "{correction}");

        let mut report_only_view = RuntimeExpectation::required_report_view("loop daily-triage");
        report_only_view.record_remote_view();
        assert!(!report_only_view.is_satisfied());
        let warning = report_only_view.missing_warning().unwrap();
        assert!(warning.contains("fan-out"), "{warning}");
        let correction = report_only_view.corrective_prompt().unwrap();
        assert!(correction.contains("fan-out"), "{correction}");

        let mut full_report = RuntimeExpectation::required_report_view("deep research");
        full_report.record_tool("dynamic_workflow");
        full_report.record_remote_view();
        assert!(full_report.is_satisfied());
        assert!(full_report.missing_warning().is_none());
        assert!(full_report.corrective_prompt().is_none());
    }

    #[test]
    fn remote_view_detection_only_marks_new_specs() {
        let spec = remote_ui::ViewSpec {
            url: "https://os.example.com/admin/runtime/jobs/1?embed=1".into(),
            width: Some(1200),
            height: Some(800),
            embeddable: true,
        };

        assert!(is_new_remote_view(None, &spec));
        assert!(!is_new_remote_view(Some(&spec), &spec));
    }

    #[test]
    fn os_required_message_distinguishes_missing_config_from_missing_login() {
        let configured = os_required_message("/agent run", true);
        assert!(configured.contains("/login"));
        assert!(!configured.contains("configure `os"));

        let missing = os_required_message("/agent deploy", false);
        assert!(missing.contains("configure `os"));
        assert!(missing.contains("/login"));
    }

    #[test]
    fn os_required_alert_uses_shared_warning_line() {
        let rendered = os_required_alert("/agent run", true);

        assert_eq!(
            a3s_tui::style::strip_ansi(&rendered),
            "  ⚠ /agent run needs OS — sign in with /login first"
        );
        assert!(rendered.contains("\x1b[38;2;245;166;35m"));
    }

    #[test]
    fn ide_flash_line_uses_shared_toast_component() {
        let rendered = ide_flash_line(ToastKind::Warning, "read-only");

        assert_eq!(a3s_tui::style::strip_ansi(&rendered), "⚠ read-only");
        assert!(rendered.contains("\x1b[38;2;245;166;35m"));
    }

    // ---- 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_wide_unicode() {
        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
                                              // These wide 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 wide 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);
    }
}