rpi-cli 0.1.4

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates — a Rust port of @earendil-works/pi-coding-agent's CLI surface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
//! Interactive mode for pi-cli.
//!
//! Full-screen terminal UI with a streaming transcript, an editor, a live
//! status indicator, and tool-execution display. Mirrors the TypeScript
//! `packages/coding-agent/src/modes/interactive/interactive-mode.ts` event→UI
//! mapping (`handleEvent`), driven by the live `AgentEvent` stream the harness
//! emits via the `BroadcastEmitter` installed in [`crate::session`].
//!
//! Key architecture facts (see `docs/tui-gap-analysis.md`):
//! - `TuiAltScreen::start()` and `show_overlay` are stubs, so this module owns
//!   a `spawn_blocking` crossterm `read()` loop for key dispatch and a
//!   `tokio::spawn` task that drains `broadcast::Receiver<AgentEvent>` into UI
//!   mutations.
//! - The layout root is built ONCE at startup (mirrors the TS
//!   `fullscreenLayoutRoot`); per-message we mutate only `chat_container` /
//!   `status_container` / `autocomplete_container` children and call
//!   `request_render(false)` so the differential renderer repaints just the
//!   changed rows.
//! - Selectors (`/model` `/session` `/theme`) are implemented by **swapping the
//!   `editor_container` child** (the TS `showSelector` swap pattern,
//!   `interactive-mode.ts:4354-4377`) — the `show_overlay` stub is avoided
//!   entirely. An `active_selector` state field holds the live `SelectList`;
//!   while it is `Some` the key loop routes to it first and restores the editor
//!   on done/cancel.

use std::collections::HashMap;
use std::io::IsTerminal;
use std::sync::Arc;
use std::sync::mpsc::{self, channel};

use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers};
use tokio::sync::broadcast;

use rpi_agent::{AgentEvent, AgentMessage};
use rpi_harness::session::types::{Entry, EntryQuery};
use rpi_ai::types::{AssistantMessage, Content};
use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
use rpi_tui::{
    AutocompleteManager, CombinedAutocompleteProvider, Container, Editor, EditorOptions,
    EditorStyle, FilePathAutocompleteProvider, Focusable, FollowMode, Loader, ProcessTerminal,
    ScrollView, ScrollViewOptions, SlashCommand as SlashCommandEntry, SlashCommandAutocompleteProvider, Spacer,
    StackChild, StackEntry, Text, TuiAltScreen, TUI, VStack, AssistantBlock,
    AssistantMessageComponent, AssistantMessageOptions, AutocompleteSuggestions,
    FooterComponent, SelectList, SelectItem, ThemeManager, ThemePreset,
    ToolExecutionComponent, render_diff,
    BashExecutionComponent, BashTruncation, UserMessageComponent,
};

#[allow(unused_imports)]
use rpi_tui::BashStatus;

use crate::args::Args;

/// B5e: the markdown-transformer trait object the assistant-message render path
/// applies to raw text BEFORE the [`Markdown`] renderer styles it. A plain
/// `Fn(&str) -> String` (NO `rpi-extensions` types) so `rpi-tui` stays free of
/// an `rpi-extensions` dep — `rpi-cli` (which already depends on
/// `rpi-extensions`) builds the closure from the live `RegistrySnapshot` and
/// hands the trait object to `AssistantMessageComponent::set_markdown_transformer`.
type MarkdownTransformer = Arc<dyn Fn(&str) -> String + Send + Sync>;

/// B5e: build the `AssistantMessageComponent` markdown-transformer closure the
/// render path applies to raw assistant text before styling. Wraps any plugin
/// `register_markdown_transformer` handlers registered in `snapshot` (chained
/// in registration order: each handler's output feeds the next). `None` when
/// no markdown transformers are registered (the component defaults to the
/// identity transform + this avoids a closure allocation on the hot render
/// path).
///
/// The closure captures an `Arc<RegistrySnapshot>` clone so it outlives the
/// borrow that built it (the snapshot's `active` flag guards dispatch in
/// `emit_resources_discover`/event translation; a reloaded session's old
/// snapshot flips false, so a stale closure no-ops rather than driving a
/// half-swapped registry — the transformer falls back to the input unchanged
/// on an inactive snapshot, matching the plugin's per-handler skip-on-error).
///
/// This is the cycle-free seam: `rpi-tui` takes a `Fn(&str) -> String` trait
/// object (no `rpi-extensions` dep); `rpi-cli` (which already depends on
/// `rpi-extensions`) builds the closure from the live `RegistrySnapshot`. The
/// calling pattern mirrors `plugin_stub_smoke.rs`'s direct `RenderFn` round-
/// trip (input `{"markdown":…}` → `render_fn` → reclaim `out` via the plugin's
/// `free_string` → parse `{"markdown":…}`).
fn build_markdown_transformer(
    snapshot: Option<std::sync::Arc<rpi_extensions::RegistrySnapshot>>,
) -> Option<MarkdownTransformer> {
    let snapshot = snapshot?;
    // Pre-check: if no markdown renderers are registered, return None so the
    // component uses the identity path (no per-delta closure call). The
    // renderers list is a per-call `renderers_of` clone; snapshotting it once
    // here keeps the closure cheap on the hot path.
    let renderers = snapshot.renderers_of(rpi_extensions::RegisteredRendererKind::Markdown);
    if renderers.is_empty() {
        return None;
    }
    Some(Arc::new(move |raw: &str| -> String {
        transform_markdown_chain(&snapshot, &renderers, raw)
    }))
}

/// Drive the markdown-transformer chain for one input string. Each registered
/// handler receives the previous handler's output (or the raw input for the
/// first), as a `{"markdown": <text>}` JSON envelope; its `RenderFn` returns
/// `{"markdown": <transformed>}` (rc=0) or an error (rc!=0). On any failure —
/// nonzero rc, a panic across the FFI (caught), a missing `markdown` field, or
/// an inactive snapshot — the chain short-circuits to the current text
/// unchanged (per-handler skip-on-error, mirroring pi's `runner.ts` fan-out).
fn transform_markdown_chain(
    snapshot: &rpi_extensions::RegistrySnapshot,
    renderers: &[rpi_extensions::RegisteredRenderer],
    raw: &str,
) -> String {
    // A stale snapshot (post-/reload) must not drive a swapped-out registry.
    // The renderers were captured from this snapshot; if it has gone inactive,
    // fall back to the raw input so the UI never renders stale-transformed text
    // from a dead plugin.
    if !snapshot.is_active() {
        return raw.to_string();
    }

    let mut current = raw.to_string();
    for renderer in renderers {
        let input = match serde_json::to_string(&serde_json::json!({ "markdown": current })) {
            Ok(s) => s,
            Err(_) => return current, // serialize failure — keep current, stop chain
        };
        // SAFETY: `render_fn` is a plugin-provided `extern "C" fn` over a
        // borrowed `StbStringRef` + an out-param. The plugin warrants
        // `poll`/`render` are non-blocking + thread-safe (the same contract
        // the tool adapter relies on). `user_data` is the plugin's opaque
        // pointer, stable for the registry lifetime (the keepalive keeps the
        // cdylib mapped). We reclaim `out` via the plugin's `free_string`
        // exactly once. The whole call is `catch_unwind`-wrapped — a plugin
        // panic must not unwind across the FFI boundary (same policy as the
        // tool partial cb + the runtime_action trampoline).
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut out = rpi_plugin_sdk::StbString::empty();
            let rc = (renderer.render_fn)(
                rpi_plugin_sdk::StbStringRef::from_str(&input),
                &mut out as *mut rpi_plugin_sdk::StbString,
                renderer.user_data,
            );
            let text = if rc == 0 {
                let s = out.to_string_lossy();
                Some(s)
            } else {
                None
            };
            // Reclaim the plugin-owned `out` regardless of rc (rc!=0 may still
            // have written an error JSON the plugin allocated). `free_with` is
            // idempotent on an empty `StbString`.
            out.free_with(Some(renderer.plugin_free_string));
            text
        }));
        let out_text = match outcome {
            Ok(Some(s)) => s,
            Ok(None) => return current, // rc != 0 — skip this handler, keep current
            Err(_) => return current,  // panic — skip, keep current (do not abort: the
            // render path is not the action trampoline; a panicking transformer
            // degrades to identity rather than killing the process. Logged via
            // the `tracing` crate's panic hook.)
        };
        // Parse `{"markdown": <text>}`; lenient — a missing/non-string field
        // keeps the current text (skip this handler).
        let next = serde_json::from_str::<serde_json::Value>(&out_text)
            .ok()
            .and_then(|v| v.get("markdown").and_then(|m| m.as_str()).map(|s| s.to_string()))
            .unwrap_or(current);
        current = next;
    }
    current
}



// ===========================================================================
// Slash commands — trait + registry
// ===========================================================================
//
// Each built-in slash command is one `impl SlashCommand`. The commands are
// registered at startup into a [`CommandRegistry`] (one source of truth) that
// serves both dispatch ("given this token, run the command") and autocomplete
// ("list the visible commands"). This replaces the old two-list + sync-test
// arrangement, where `handle_slash_command` and `v1_slash_commands()` had to be
// kept in lock-step by hand.
//
// `execute` runs on the blocking key/compose thread (the editor `on_submit`
// callback and the Ctrl+L hotkey both land there), so it MUST stay synchronous:
//   - commands needing async (`set_model`/`set_thinking_level`/`set_active_tools`)
//     `tokio::spawn` the work and return immediately;
//   - commands needing the main async loop (`compact`/`copy`/`exit`/`clear`/
//     `user-input`) signal it via `ctx.tx.send(TuiMessage::…)`;
//   - everything else mutates the chat container + requests a render directly.

/// The borrowed world a slash command runs against. All fields are `Arc` (or a
/// cheap `String` snapshot), so one `CommandContext` clones freely into each
/// command without per-capture ceremony — this struct is exactly the set of
/// `*_for_cb` clones the old submit closure used to make individually.
#[derive(Clone)]
struct CommandContext {
    chat: Arc<Container>,
    tui: Arc<TuiAltScreen>,
    tx: mpsc::Sender<TuiMessage>,
    state: Arc<TuiState>,
    editor: Arc<Editor>,
    editor_container: Arc<Container>,
    lane: Arc<dyn AgentLane>,
    model_catalog: Arc<Vec<rpi_ai::Model>>,
    /// Lane model id snapshot, read once via `lane.get_model().await` BEFORE the
    /// blocking key loop starts. Selectors/key loop can't await, so they read
    /// this owned string instead. Semantically unchanged from pre-refactor.
    lane_model_id: String,
    cwd: std::path::PathBuf,
    /// Harness resources snapshot (skills + prompt templates) for `/context`.
    /// Captured once at TUI startup because the blocking submit thread can't
    /// `.await get_resources()`.
    resources: Arc<rpi_harness::types::AgentHarnessResources>,
    /// B5d: the reload context `/reload` drives. `Arc<ReloadContext>` so the
    /// blocking submit thread can cheaply clone it into the `ReloadCommand`
    /// without an `.await` (the command can't drive reload directly — it signals
    /// the main loop via `TuiMessage::ReloadExtensions`, which awaits the shared
    /// `reload_extension_resources` routine on the async runtime).
    reload_context: Arc<crate::session::ReloadContext>,
}

/// One slash command.
trait SlashCommand: Send + Sync {
    /// Canonical name, with the leading `/` (e.g. "/model").
    fn name(&self) -> &'static str;
    /// Aliases, also `/`-prefixed. Matched alongside `name()` during dispatch.
    /// Use [`SlashCommand::alias_visible`] to also surface an alias in the
    /// `/`-autocomplete list (most aliases stay hidden).
    fn aliases(&self) -> &'static [&'static str] {
        &[]
    }
    /// Whether the canonical name appears in the `/` autocomplete list. Hidden
    /// commands (`/context`, `/name`, …) return `false`.
    fn visible(&self) -> bool {
        true
    }
    /// Aliases that should also appear in the `/` autocomplete list. Defaults to
    /// none — most aliases (`/q`, `/m`, `/think`, `/resume`, `/v`) are kept off
    /// the list to keep it short. `/new` and `/quit` override this to surface.
    fn alias_visible(&self) -> &'static [&'static str] {
        &[]
    }
    /// Description shown in autocomplete and `/help`. A non-empty description is
    /// required to surface in autocomplete even when `visible()` is true.
    fn description(&self) -> &'static str {
        ""
    }
    /// Execute the command. Only invoked for inputs starting with `/` whose
    /// first token matches `name()` or an alias. `args` is the whitespace-
    /// trimmed remainder after the command token ("" when none). Must stay
    /// synchronous (see the module-level note) — async work goes through
    /// `ctx.tx.send(TuiMessage::…)` or `tokio::spawn`.
    fn execute(&self, ctx: &CommandContext, args: &str);
}

/// Holds all registered slash commands; the single source of truth for both
/// dispatch and the autocomplete list.
struct CommandRegistry {
    commands: Vec<Arc<dyn SlashCommand>>,
}

impl CommandRegistry {
    fn new() -> Self {
        Self { commands: Vec::new() }
    }

    fn register(&mut self, cmd: Arc<dyn SlashCommand>) {
        self.commands.push(cmd);
    }

    /// Find the command whose `name()` or an alias matches `token` (e.g. "/q").
    /// `token` is the first whitespace-delimited word of the input, `/`-prefixed.
    fn find(&self, token: &str) -> Option<&Arc<dyn SlashCommand>> {
        self.commands
            .iter()
            .find(|c| c.name() == token || c.aliases().contains(&token))
    }

    /// The autocomplete entries, derived from the registry so it can never drift
    /// from what dispatch recognizes. Surfaces the canonical name when
    /// `visible()` + non-empty description, plus any `alias_visible()` entries.
    /// Order = registration order; built-ins are registered before templates,
    /// so they win on a fuzzy tie (unchanged).
    fn visible_entries(&self) -> Vec<SlashCommandEntry> {
        let mut out: Vec<SlashCommandEntry> = Vec::new();
        for c in &self.commands {
            if c.visible() && !c.description().is_empty() {
                out.push(SlashCommandEntry {
                    name: c.name().into(),
                    description: c.description().into(),
                });
            }
            // Surfaced aliases share the command's description.
            for alias in c.alias_visible() {
                out.push(SlashCommandEntry {
                    name: (*alias).into(),
                    description: c.description().into(),
                });
            }
        }
        out
    }
}

/// Resolve the command for a `/`-prefixed input and run it, or emit the
/// unknown-command error if nothing matches. Non-slash text never reaches here
/// — callers route only `/`-prefixed inputs and send plain text directly.
fn dispatch_slash(text: &str, ctx: &CommandContext, registry: &CommandRegistry) {
    let mut parts = text.split_whitespace();
    let token = parts.next().unwrap_or("");
    let args = parts.collect::<Vec<_>>().join(" ");
    match registry.find(token) {
        Some(cmd) => cmd.execute(ctx, &args),
        None => {
            add_error_message(
                &ctx.chat,
                &format!("Unknown command: {text}. Type /help for available commands."),
            );
            ctx.tui.request_render(false);
        }
    }
}

/// A slash command that is recognized but not implemented in this v1 build.
/// One struct feeds every `/settings`/`/export`/… entry — no per-command
/// boilerplate.
struct UnsupportedCommand {
    name: &'static str,
    desc: &'static str,
}

impl UnsupportedCommand {
    fn new(name: &'static str, desc: &'static str) -> Self {
        Self { name, desc }
    }
}

impl SlashCommand for UnsupportedCommand {
    fn name(&self) -> &'static str {
        self.name
    }
    /// Visible with a description so autocomplete lists it (the user discovers
    /// the command exists) even though running it reports "not supported".
    fn description(&self) -> &'static str {
        self.desc
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        add_note_message(&ctx.chat, &format!("{} is not supported in v1.", self.name));
        ctx.tui.request_render(false);
    }
}

// ---- Built-in command implementations ----

struct HelpCommand;
impl SlashCommand for HelpCommand {
    fn name(&self) -> &'static str {
        "/help"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/?"]
    }
    fn description(&self) -> &'static str {
        "Show available commands"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        add_help_message(&ctx.chat);
        ctx.tui.request_render(false);
    }
}

struct ClearChatCommand;
impl SlashCommand for ClearChatCommand {
    fn name(&self) -> &'static str {
        "/clear"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/new"]
    }
    // `/new` carries its own weight as a discoverable entry, so surface it.
    fn alias_visible(&self) -> &'static [&'static str] {
        &["/new"]
    }
    fn description(&self) -> &'static str {
        "Clear the conversation"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::ClearChat);
    }
}

struct ExitCommand;
impl SlashCommand for ExitCommand {
    fn name(&self) -> &'static str {
        "/exit"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/quit", "/q"]
    }
    // `/quit` is surfaced (matches pi's BUILTIN list); `/q` stays a hidden alias.
    fn alias_visible(&self) -> &'static [&'static str] {
        &["/quit"]
    }
    fn description(&self) -> &'static str {
        "Exit the application"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::Exit);
    }
}

struct VersionCommand;
impl SlashCommand for VersionCommand {
    fn name(&self) -> &'static str {
        "/version"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/v"]
    }
    fn description(&self) -> &'static str {
        "Show version information"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        add_version_message(&ctx.chat);
        ctx.tui.request_render(false);
    }
}

struct HotkeysCommand;
impl SlashCommand for HotkeysCommand {
    fn name(&self) -> &'static str {
        "/hotkeys"
    }
    fn description(&self) -> &'static str {
        "Show keyboard shortcuts"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        add_hotkeys_message(&ctx.chat);
        ctx.tui.request_render(false);
    }
}

struct ModelCommand;
impl SlashCommand for ModelCommand {
    fn name(&self) -> &'static str {
        "/model"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/m"]
    }
    fn description(&self) -> &'static str {
        "Choose a model (selector)"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_model_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.model_catalog,
            &ctx.lane,
            &ctx.lane_model_id,
            &ctx.chat,
        );
    }
}

struct ThinkingCommand;
impl SlashCommand for ThinkingCommand {
    fn name(&self) -> &'static str {
        "/thinking"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/think"]
    }
    fn description(&self) -> &'static str {
        "Set thinking level (selector)"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_thinking_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.lane,
            &ctx.model_catalog,
            &ctx.lane_model_id,
            &ctx.chat,
        );
    }
}

struct ToolsCommand;
impl SlashCommand for ToolsCommand {
    fn name(&self) -> &'static str {
        "/tools"
    }
    fn description(&self) -> &'static str {
        "Toggle tools on/off"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_tools_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.lane,
            &ctx.chat,
        );
    }
}

struct ImagesCommand;
impl SlashCommand for ImagesCommand {
    fn name(&self) -> &'static str {
        "/images"
    }
    fn description(&self) -> &'static str {
        "Toggle inline images"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_images_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.chat,
        );
    }
}

struct SessionCommand;
impl SlashCommand for SessionCommand {
    fn name(&self) -> &'static str {
        "/session"
    }
    fn aliases(&self) -> &'static [&'static str] {
        &["/resume"]
    }
    fn description(&self) -> &'static str {
        "List saved sessions"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_session_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.cwd,
            &ctx.tx,
        );
    }
}

struct ThemeCommand;
impl SlashCommand for ThemeCommand {
    fn name(&self) -> &'static str {
        "/theme"
    }
    fn description(&self) -> &'static str {
        "Choose a theme (selector)"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_theme_selector(&ctx.state, &ctx.editor_container, &ctx.editor, &ctx.tui);
    }
}

struct CompactCommand;
impl SlashCommand for CompactCommand {
    fn name(&self) -> &'static str {
        "/compact"
    }
    fn description(&self) -> &'static str {
        "Compact the conversation"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::Compact);
    }
}

struct CopyCommand;
impl SlashCommand for CopyCommand {
    fn name(&self) -> &'static str {
        "/copy"
    }
    fn description(&self) -> &'static str {
        "Copy last reply to clipboard"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::Copy);
    }
}

struct ExportCommand;
impl SlashCommand for ExportCommand {
    fn name(&self) -> &'static str {
        "/export"
    }
    fn description(&self) -> &'static str {
        "Export session to a markdown file"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::ExportSession);
    }
}

struct ForkCommand;
impl SlashCommand for ForkCommand {
    fn name(&self) -> &'static str {
        "/fork"
    }
    fn description(&self) -> &'static str {
        "Fork the session into a new one"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::ForkSession);
    }
}

struct NameCommand;
impl SlashCommand for NameCommand {
    fn name(&self) -> &'static str {
        "/name"
    }
    fn description(&self) -> &'static str {
        "Set session display name"
    }
    fn execute(&self, ctx: &CommandContext, args: &str) {
        let name = args.trim();
        if name.is_empty() {
            add_note_message(
                &ctx.chat,
                "Usage: /name <display name> — sets the current session's name.",
            );
            ctx.tui.request_render(false);
            return;
        }
        let _ = ctx.tx.send(TuiMessage::SetSessionName(name.to_string()));
    }
}

struct ImportCommand;
impl SlashCommand for ImportCommand {
    fn name(&self) -> &'static str {
        "/import"
    }
    fn description(&self) -> &'static str {
        "Import a session file (path)"
    }
    fn execute(&self, ctx: &CommandContext, args: &str) {
        let path = args.trim();
        if path.is_empty() {
            add_note_message(
                &ctx.chat,
                "Usage: /import <path-to-session.jsonl> — copies the file into the session dir and switches to it.",
            );
            ctx.tui.request_render(false);
            return;
        }
        let _ = ctx.tx.send(TuiMessage::ImportSession(path.to_string()));
    }
}

struct SettingsCommand;
impl SlashCommand for SettingsCommand {
    fn name(&self) -> &'static str {
        "/settings"
    }
    fn description(&self) -> &'static str {
        "Open settings menu"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_settings_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.lane,
            &ctx.model_catalog,
            &ctx.lane_model_id,
            &ctx.chat,
        );
    }
}

struct ScopedModelsCommand;
impl SlashCommand for ScopedModelsCommand {
    fn name(&self) -> &'static str {
        "/scoped-models"
    }
    fn description(&self) -> &'static str {
        "Choose models for Ctrl+M cycling"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        open_scoped_models_selector(
            &ctx.state,
            &ctx.editor_container,
            &ctx.editor,
            &ctx.tui,
            &ctx.model_catalog,
            &ctx.chat,
        );
    }
}

struct ShareCommand;
impl SlashCommand for ShareCommand {
    fn name(&self) -> &'static str {
        "/share"
    }
    fn description(&self) -> &'static str {
        "Share session (gist via gh, or clipboard)"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        let _ = ctx.tx.send(TuiMessage::ShareSession);
    }
}

struct ArminCommand;
impl SlashCommand for ArminCommand {
    fn name(&self) -> &'static str {
        "/armin"
    }
    fn description(&self) -> &'static str {
        "??? (easter egg)"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        crate::extras::add_armin(&ctx.chat);
        ctx.tui.request_render(false);
    }
}

struct EarendilCommand;
impl SlashCommand for EarendilCommand {
    fn name(&self) -> &'static str {
        "/earendil"
    }
    fn description(&self) -> &'static str {
        "Announcement"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        crate::extras::add_earendil(&ctx.chat);
        ctx.tui.request_render(false);
    }
}

/// `/context` — lists discovered context files, skills, and prompt templates.
/// Hidden from autocomplete (needs the resources snapshot to be meaningful as a
/// discovery surface; like `/name`, it's recognized-v1 but kept off the list).
struct ContextCommand;
impl SlashCommand for ContextCommand {
    fn name(&self) -> &'static str {
        "/context"
    }
    fn visible(&self) -> bool {
        false
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        show_context_panel(&ctx.chat, &ctx.resources);
        ctx.tui.request_render(false);
    }
}

/// `/reload` — re-run extension + resource discovery into the LIVE harness
/// (B5d): reload the cdylib plugins, invalidate the old `ActionBridge` +
/// registry snapshot, rebuild skills/prompts/context/SYSTEM.md/APPEND_SYSTEM.md
/// + the `TeeEmitter`, and push the rebuilt state via the B5d harness setters.
/// The command itself runs on the blocking submit thread, so it can't drive
/// the async `reload_extension_resources` routine directly — it signals the main
/// loop via `TuiMessage::ReloadExtensions`, which awaits it on the async runtime.
/// (A plugin's `runtime_action(Reload)` signals the same loop via the
/// `ReloadMailbox` the TUI installs — the B5d async-reload design avoids the
/// self-unmapping race a synchronous plugin-initiated reload would have.)
struct ReloadCommand;
impl SlashCommand for ReloadCommand {
    fn name(&self) -> &'static str {
        "/reload"
    }
    fn description(&self) -> &'static str {
        "Reload extensions, skills, prompts"
    }
    fn execute(&self, ctx: &CommandContext, _args: &str) {
        // Signal the main loop. It owns the `&AgentHarness` borrow the
        // `reload_extension_resources` routine needs (the blocking submit thread
        // only has the context's `Arc<ReloadContext>` + the `Arc<dyn AgentLane>`).
        add_note_message(
            &ctx.chat,
            "Reloading extensions + resources…",
        );
        ctx.tui.request_render(false);
        let _ = ctx.tx.send(TuiMessage::ReloadExtensions);
    }
}

/// Build the full command registry: active built-ins first (so they win on a
/// fuzzy autocomplete tie), then the v1-out-of-scope stubs. Prompt-template
/// commands are merged in separately by the autocomplete builder (they dispatch
/// via template expansion, not this registry).
fn build_builtin_registry() -> CommandRegistry {
    let mut r = CommandRegistry::new();
    r.register(Arc::new(HelpCommand));
    r.register(Arc::new(ClearChatCommand));
    r.register(Arc::new(ExitCommand));
    r.register(Arc::new(VersionCommand));
    r.register(Arc::new(ModelCommand));
    r.register(Arc::new(ThinkingCommand));
    r.register(Arc::new(ToolsCommand));
    r.register(Arc::new(ImagesCommand));
    r.register(Arc::new(SessionCommand));
    r.register(Arc::new(ThemeCommand));
    r.register(Arc::new(CompactCommand));
    r.register(Arc::new(CopyCommand));
    r.register(Arc::new(HotkeysCommand));
    r.register(Arc::new(ArminCommand));
    r.register(Arc::new(EarendilCommand));
    r.register(Arc::new(ContextCommand));
    // Recognized but inert in v1 (one struct backs them all). The TS builtins
    // out of v1 scope; each carries a description so autocomplete surfaces its
    // existence even though running it reports "not supported".
    r.register(Arc::new(NameCommand));
    r.register(Arc::new(SettingsCommand));
    r.register(Arc::new(ScopedModelsCommand));
    r.register(Arc::new(ExportCommand));
    r.register(Arc::new(ImportCommand));
    r.register(Arc::new(ShareCommand));
    r.register(Arc::new(ForkCommand));
    r.register(Arc::new(UnsupportedCommand::new(
        "/clone",
        "Duplicate the current session",
    )));
    r.register(Arc::new(UnsupportedCommand::new(
        "/tree",
        "Navigate session tree",
    )));
    r.register(Arc::new(UnsupportedCommand::new(
        "/trust",
        "Save project trust decision",
    )));
    r.register(Arc::new(UnsupportedCommand::new(
        "/login",
        "Configure provider authentication",
    )));
    r.register(Arc::new(UnsupportedCommand::new(
        "/logout",
        "Remove provider authentication",
    )));
    r.register(Arc::new(ReloadCommand));
    r
}

// ===========================================================================
// Channel + helpers
// ===========================================================================

/// Message type for communication between the key/callback threads and the
/// main async loop.
enum TuiMessage {
    UserInput(String),
    Exit,
    /// Clear the transcript (from `/clear`).
    ClearChat,
    /// Compact the conversation (from `/compact`).
    Compact,
    /// Copy the last assistant reply to the clipboard (from `/copy`).
    Copy,
    /// Hot-switch to another saved session (from the `/session` selector):
    /// the payload is the session id the selector's item value carried.
    SwitchSession(String),
    /// Export the current session to a markdown file (from `/export`).
    ExportSession,
    /// Fork the current session into a new one and switch to it (from `/fork`).
    ForkSession,
    /// Rename the current session (from `/name <name>`).
    SetSessionName(String),
    /// Import a JSONL session file into the session dir and switch to it
    /// (from `/import <path>`).
    ImportSession(String),
    /// Share the current session (`/share`): `gh gist create` when the gh CLI
    /// is available, otherwise copy the transcript to the clipboard.
    ShareSession,
    /// `/reload` — re-run extension + resource discovery into the live harness
    /// (B5d). The command (and a plugin's `runtime_action(Reload)` via the
    /// mailbox) signal the main loop, which awaits
    /// `reload_extension_resources` on the async runtime.
    ReloadExtensions,
}

/// Extract the concatenated text content from an assistant message (mirrors
/// the TS `contentText` projection — drops thinking/tool-call/image blocks).
fn assistant_text(msg: &AssistantMessage) -> String {
    msg.content
        .iter()
        .filter_map(|c| match c {
            Content::Text(t) => Some(t.text.clone()),
            _ => None,
        })
        .collect()
}

/// The user message's text (Text content or the text blocks of a Blocks
/// payload — images are skipped, consistent with the v1 text-only prompt path).
fn user_message_text(msg: &rpi_ai::types::UserMessage) -> String {
    match &msg.content {
        rpi_ai::types::UserContent::Text(s) => s.clone(),
        rpi_ai::types::UserContent::Blocks(blocks) => blocks
            .iter()
            .filter_map(|c| match c {
                Content::Text(t) => Some(t.text.clone()),
                _ => None,
            })
            .collect(),
    }
}

/// Render the `/settings` panel: the saved settings.json values the session
/// honors, plus pointers to the commands that edit them (theme via `/theme`,
/// defaults via flags, cycle scope via `/scoped-models`). Kept for the
/// read-only summary; the interactive menu is [`open_settings_selector`].
fn show_settings_panel(chat: &Arc<Container>) {
    let s = crate::settings::load_settings().unwrap_or_default();
    let mut lines: Vec<String> = Vec::new();
    lines.push("⚙️  Saved settings:".into());
    lines.push(format!(
        "  Theme: {} (edit with /theme)",
        s.theme.as_deref().unwrap_or("(default)")
    ));
    lines.push(format!(
        "  Default model: {} (set at launch with --model)",
        s.default_model.as_deref().unwrap_or("(none)")
    ));
    lines.push(format!(
        "  Default thinking: {} (set at launch with --thinking)",
        s.default_thinking_level.as_deref().unwrap_or("(default)")
    ));
    match &s.scoped_models {
        Some(list) if !list.is_empty() => lines.push(format!(
            "  Ctrl+M cycle scope: {} (edit with /scoped-models)",
            list.join(", ")
        )),
        _ => lines.push("  Ctrl+M cycle scope: all models (edit with /scoped-models)".into()),
    }
    let body = lines.join("\n");
    container_note_block(chat, &body);
}

/// The catalog allowed in the Ctrl+M cycle: the `/scoped-models` set from
/// settings.json when present, otherwise every model. The current model is
/// always included (fallback) so cycling can never strand the user off-scope.
fn scoped_catalog(catalog: &[rpi_ai::Model], current_id: &str) -> Vec<rpi_ai::Model> {
    let scoped = crate::settings::load_settings()
        .ok()
        .and_then(|s| s.scoped_models)
        .unwrap_or_default();
    if scoped.is_empty() {
        return catalog.to_vec();
    }
    let mut out: Vec<rpi_ai::Model> = catalog
        .iter()
        .filter(|m| scoped.iter().any(|s| s.eq_ignore_ascii_case(&m.id)))
        .cloned()
        .collect();
    // Never strand the user: if the current model isn't in scope, keep it.
    if !out.iter().any(|m| m.id.eq_ignore_ascii_case(current_id)) {
        if let Some(cur) = catalog.iter().find(|m| m.id.eq_ignore_ascii_case(current_id)) {
            out.push(cur.clone());
        }
    }
    out
}

/// Interactive `/settings` menu: a top-level selector over the editable
/// settings, each opening a sub-selector that applies the choice AND persists
/// it to settings.json (theme / default model / default thinking / cycle
/// scope). Selecting a menu item swaps the current selector for the
/// sub-selector (the `active_selector` slot is single, so each open replaces
/// the previous list); the sub-selector's cancel restores the editor.
fn open_settings_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    lane: &Arc<dyn AgentLane>,
    catalog: &[rpi_ai::Model],
    lane_model_id: &str,
    chat: &Arc<Container>,
) {
    let settings = crate::settings::load_settings().unwrap_or_default();
    let mut items: Vec<SelectItem> = Vec::new();
    items.push(
        SelectItem::new("theme", "Theme")
            .with_description(&settings.theme.clone().unwrap_or_else(|| "(default)".into())),
    );
    items.push(
        SelectItem::new("model", "Default model")
            .with_description(&settings.default_model.clone().unwrap_or_else(|| "(none)".into())),
    );
    items.push(
        SelectItem::new("thinking", "Default thinking")
            .with_description(&settings.default_thinking_level.clone().unwrap_or_else(|| "(default)".into())),
    );
    let scope_desc = match &settings.scoped_models {
        Some(list) if !list.is_empty() => format!("{}", list.join(", ")),
        _ => "all models".to_string(),
    };
    items.push(
        SelectItem::new("scoped-models", "Ctrl+M cycle scope").with_description(&scope_desc),
    );
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let lane_sel = lane.clone();
    let chat_sel = chat.clone();
    let catalog_sel = catalog.to_vec();
    let lane_model_sel = lane_model_id.to_string();
    list.on_select(Arc::new(move |item| {
        // Swap this menu for the sub-selector; each sub-selector saves its
        // choice to settings.json on select.
        match item.value.as_str() {
            "theme" => open_settings_theme_selector(
                &state_sel, &ec_sel, &editor_sel, &tui_sel, &chat_sel,
            ),
            "model" => open_settings_model_selector(
                &state_sel,
                &ec_sel,
                &editor_sel,
                &tui_sel,
                &lane_sel,
                &catalog_sel,
                &lane_model_sel,
                &chat_sel,
            ),
            "thinking" => open_settings_thinking_selector(
                &state_sel,
                &ec_sel,
                &editor_sel,
                &tui_sel,
                &lane_sel,
                &catalog_sel,
                &lane_model_sel,
                &chat_sel,
            ),
            "scoped-models" => open_scoped_models_selector(
                &state_sel, &ec_sel, &editor_sel, &tui_sel, &catalog_sel, &chat_sel,
            ),
            _ => close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel),
        }
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Settings);
}

/// Apply a theme choice AND persist it to settings.json (`/settings` → Theme).
fn open_settings_theme_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    chat: &Arc<Container>,
) {
    let items = vec![
        SelectItem::new("dark", "Dark").with_description("Default dark theme"),
        SelectItem::new("light", "Light").with_description("Light background"),
        SelectItem::new("monochrome", "Monochrome").with_description("No color accents"),
    ];
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    list.on_select(Arc::new(move |item| {
        let preset = match item.value.as_str() {
            "light" => ThemePreset::Light,
            "monochrome" => ThemePreset::Monochrome,
            _ => ThemePreset::Dark,
        };
        state_sel.theme_manager.apply_preset(preset);
        let mut settings = crate::settings::load_settings().unwrap_or_default();
        settings.theme = Some(item.value.clone());
        let saved = crate::settings::save_settings(&settings);
        add_note_message(
            &chat_sel,
            &format!(
                "Theme set to {} (saved{})",
                item.label,
                if saved.is_ok() { "" } else { ", not saved" },
            ),
        );
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
        tui_sel.render_now(true);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Settings);
}

/// Choose the default model AND persist it (`/settings` → Default model):
/// applies live via `lane.set_model` and saves `defaultModel` to settings.json
/// (which `provider::resolve` honors as pi's `findInitialModel` step 3).
fn open_settings_model_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    lane: &Arc<dyn AgentLane>,
    catalog: &[rpi_ai::Model],
    lane_model_id: &str,
    chat: &Arc<Container>,
) {
    let mut items: Vec<SelectItem> = Vec::new();
    for m in catalog {
        let label = if m.name.is_empty() { short_model_name(&m.id) } else { m.name.clone() };
        let marker = if m.id.eq_ignore_ascii_case(lane_model_id) { " (current)" } else { "" };
        items.push(SelectItem::new(&m.id, &label).with_description(&format!("{id}{marker}", id = m.id)));
    }
    if items.is_empty() {
        add_note_message(chat, "No models in the catalog.");
        tui.request_render(false);
        return;
    }
    let list = Arc::new(SelectList::new(items, 10));

    let catalog_arc = catalog.to_vec();
    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    let lane_sel = lane.clone();
    list.on_select(Arc::new(move |item| {
        let Some(model) = catalog_arc.iter().find(|m| m.id == item.value).cloned() else {
            add_note_message(&chat_sel, &format!("Model {} not found.", item.label));
            close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
            return;
        };
        state_sel.set_current_model(&model);
        let lane = lane_sel.clone();
        tokio::spawn(async move {
            let _ = lane.set_model(model).await;
        });
        let mut settings = crate::settings::load_settings().unwrap_or_default();
        settings.default_model = Some(item.value.clone());
        let saved = crate::settings::save_settings(&settings);
        add_note_message(
            &chat_sel,
            &format!(
                "Default model set to {} (saved{}",
                short_model_name(&item.value),
                if saved.is_ok() { ")" } else { ", not saved)" },
            ),
        );
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Settings);
}

/// Choose the default thinking level AND persist it (`/settings` → Default
/// thinking): applies live via `lane.set_thinking_level` and saves
/// `defaultThinkingLevel` to settings.json.
fn open_settings_thinking_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    lane: &Arc<dyn AgentLane>,
    catalog: &[rpi_ai::Model],
    lane_model_id: &str,
    chat: &Arc<Container>,
) {
    let model = catalog.iter().find(|m| m.id.eq_ignore_ascii_case(lane_model_id));
    let levels: Vec<rpi_ai::types::ThinkingLevel> = model
        .map(|m| m.supported_thinking_levels())
        .unwrap_or_else(|| {
            use rpi_ai::types::ThinkingLevel::*;
            vec![Off, Minimal, Low, Medium, High]
        });
    let mut items: Vec<SelectItem> = Vec::new();
    for lvl in &levels {
        let name = thinking_level_name(*lvl);
        items.push(SelectItem::new(name, name).with_description(thinking_level_description(*lvl)));
    }
    if items.is_empty() {
        add_note_message(chat, "This model has no supported thinking levels.");
        tui.request_render(false);
        return;
    }
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    let lane_sel = lane.clone();
    list.on_select(Arc::new(move |item| {
        let Some(level) = thinking_level_from_name(&item.value) else {
            add_note_message(&chat_sel, &format!("Unknown thinking level: {}.", item.label));
            close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
            return;
        };
        let lane = lane_sel.clone();
        let footer_sel = state_sel.footer.clone();
        tokio::spawn(async move {
            let _ = lane.set_thinking_level(level).await;
        });
        footer_sel.set_thinking_level(Some(thinking_level_name(level)));
        let mut settings = crate::settings::load_settings().unwrap_or_default();
        settings.default_thinking_level = Some(item.value.clone());
        let saved = crate::settings::save_settings(&settings);
        add_note_message(
            &chat_sel,
            &format!(
                "Default thinking set to {} (saved{}",
                item.label,
                if saved.is_ok() { ")" } else { ", not saved)" },
            ),
        );
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Settings);
}

/// `/scoped-models`: a multi-toggle selector over the catalog. Selecting an
/// item toggles it in the in-progress set (the selector stays open); Esc saves
/// the set to settings.json and closes. The active scoped set is echoed after
/// each toggle so the user sees the current selection.
fn open_scoped_models_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    catalog: &[rpi_ai::Model],
    chat: &Arc<Container>,
) {
    if catalog.is_empty() {
        add_note_message(chat, "No models in the catalog.");
        tui.request_render(false);
        return;
    }
    // Seed the edit set from the saved scoped models.
    let seed: Vec<String> = crate::settings::load_settings()
        .ok()
        .and_then(|s| s.scoped_models)
        .unwrap_or_default();
    *state.scoped_edit.lock().unwrap() = Some(seed);

    let mut items: Vec<SelectItem> = Vec::new();
    for m in catalog {
        items.push(SelectItem::new(&m.id, &m.id));
    }
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let chat_sel = chat.clone();
    let tui_sel = tui.clone();
    list.on_select(Arc::new(move |item| {
        // Toggle the model in the in-progress set; the selector stays open.
        let mut set = state_sel.scoped_edit.lock().unwrap();
        let set = set.get_or_insert_with(Vec::new);
        if let Some(pos) = set.iter().position(|m| m.eq_ignore_ascii_case(&item.value)) {
            set.remove(pos);
            add_note_message(
                &chat_sel,
                &format!("{} removed — Esc to save", item.label),
            );
        } else {
            set.push(item.value.clone());
            add_note_message(
                &chat_sel,
                &format!("{} added — Esc to save", item.label),
            );
        }
        tui_sel.request_render(false);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    let chat_cancel = chat.clone();
    list.on_cancel(Arc::new(move || {
        // Save the edited set to settings.json and close.
        let set = state_cancel.scoped_edit.lock().unwrap().take().unwrap_or_default();
        let mut settings = crate::settings::load_settings().unwrap_or_default();
        settings.scoped_models = if set.is_empty() { None } else { Some(set.clone()) };
        match crate::settings::save_settings(&settings) {
            Ok(()) => {
                if set.is_empty() {
                    add_note_message(&chat_cancel, "Ctrl+M cycles all models (scope cleared).");
                } else {
                    add_note_message(
                        &chat_cancel,
                        &format!("Ctrl+M cycle scope: {}", set.join(", ")),
                    );
                }
            }
            Err(e) => add_error_message(&chat_cancel, &format!("Could not save settings: {e}")),
        }
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::ScopedModels);
}

/// `/share`: mirror the TS intent (share the session). With the `gh` CLI on
/// PATH, create a gist of the exported markdown; otherwise fall back to the
/// clipboard (best-effort) and note the local path.
async fn share_session(harness: &AgentHarness, chat: &Arc<Container>) {
    use std::process::Stdio;

    // Reuse the export builder for the transcript text.
    let tree = harness.session().view("main");
    let entries = match tree.find_entries(&EntryQuery {
        entry_type: None,
        custom_type: None,
        order: None,
        limit: None,
        cursor: None,
    }).await {
        Ok(e) => e,
        Err(e) => {
            add_error_message(chat, &format!("Could not read session: {e}"));
            return;
        }
    };
    let mut md = String::from("# Session\n\n");
    for e in entries {
        let Entry::Message(me) = e else { continue };
        match &me.message {
            AgentMessage::User(u) => {
                md.push_str(&format!("## User\n\n{}\n\n", user_message_text(u)));
            }
            AgentMessage::Assistant(a) => {
                let text = assistant_text(a);
                if !text.is_empty() {
                    md.push_str(&format!("## Assistant\n\n{}\n\n", text));
                }
            }
            _ => {}
        }
    }

    // `gh gist create` — stdin-piped, best-effort; only when gh exists.
    let gh = std::process::Command::new("gh")
        .arg("gist")
        .arg("create")
        .arg("--filename")
        .arg("session.md")
        .arg("-")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn();
    if let Ok(mut child) = gh {
        use std::io::Write;
        if let Some(mut stdin) = child.stdin.take() {
            let _ = stdin.write_all(md.as_bytes());
            let _ = stdin.flush();
        }
        let out = child.wait_with_output().ok();
        if let Some(out) = out {
            if out.status.success() {
                let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
                add_note_message(chat, &format!("Shared session: {url}"));
                return;
            }
        }
        add_note_message(
            chat,
            "gh gist failed — falling back to the clipboard.",
        );
    } else {
        add_note_message(
            chat,
            "gh CLI not found — falling back to the clipboard.",
        );
    }
    // Clipboard fallback (or transcript echo when the clipboard feature is off).
    if copy_to_clipboard(&md) {
        add_note_message(chat, "Session transcript copied to the clipboard.");
    } else {
        add_note_message(
            chat,
            "Clipboard unavailable — use /export to write the transcript to a file.",
        );
    }
}

/// Export the current session to a markdown transcript file. Writes
/// `<cwd>/<session-name-or-id>.md` with the user/assistant/tool-call history
/// (mirrors the TS `/export` intent locally — no remote sharing in v1).
/// Best-effort: failures surface as a chat note.
/// Export the current session to a markdown transcript file. Writes
/// `<cwd>/<session-name-or-id>.md` with the user/assistant/tool-call history
/// (mirrors the TS `/export` intent locally — no remote sharing in v1).
/// Best-effort: failures surface as a chat note.
async fn export_session(harness: &AgentHarness, chat: &Arc<Container>) {
    let tree = harness.session().view("main");
    let entries = match tree.find_entries(&EntryQuery {
        entry_type: None,
        custom_type: None,
        order: None,
        limit: None,
        cursor: None,
    }).await {
        Ok(e) => e,
        Err(e) => {
            add_error_message(chat, &format!("Could not read session: {e}"));
            return;
        }
    };
    let name = tree.get_name().await.ok().flatten().unwrap_or_default();
    let id = tree
        .get_leaf_id()
        .await
        .ok()
        .flatten()
        .unwrap_or_else(|| "session".to_string());
    let mut md = String::from("# Session\n\n");
    for e in entries {
        let Entry::Message(me) = e else { continue };
        match &me.message {
            AgentMessage::User(u) => {
                md.push_str(&format!("## User\n\n{}\n\n", user_message_text(u)));
            }
            AgentMessage::Assistant(a) => {
                let text = assistant_text(a);
                if !text.is_empty() {
                    md.push_str(&format!("## Assistant\n\n{}\n\n", text));
                }
            }
            _ => {}
        }
    }
    let file_name = if name.is_empty() {
        format!("{id}.md")
    } else {
        format!("{name}.md")
    };
    let path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(&file_name);
    match std::fs::write(&path, md) {
        Ok(_) => add_note_message(
            chat,
            &format!("Exported session to {}", path.display()),
        ),
        Err(e) => add_error_message(chat, &format!("Could not write export: {e}")),
    }
}

/// Fork the current session into a new JSONL session and switch to it (TS
/// `/fork` — a copy of the transcript in a fresh file; the fork is a new
/// session the user continues in). Uses the repo's `fork_typed`, then swaps
/// the harness backing and renders the (empty-ish) fork transcript.
/// Hot-switch the harness to another saved session: abort any in-flight run,
/// open the target session file, swap the durable backing, and re-render the
/// transcript from the new history (mirrors pi's `/session` resume-in-place).
/// Shared by the `/session` selector, `/import`, and `/fork`. The current
/// model/footer stay put (v1 doesn't replay the session's ModelChange entries).
async fn switch_to_session(
    harness: &AgentHarness,
    lane: &Arc<dyn AgentLane>,
    id: &str,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
) -> bool {
    if *state.status.lock().unwrap() == RunStatus::Working {
        state.set_status(RunStatus::Aborting);
        let _ = lane.abort().await;
    }
    let cwd_str = cwd.to_string_lossy().to_string();
    match crate::session::open_session_by_id(id, &cwd_str).await {
        Ok(new_session) => {
            let _ = harness.set_session(new_session).await;
            chat.clear();
            add_welcome_message(chat);
            render_session_history(harness, chat, state.markdown_transformer()).await;
            state.set_status(RunStatus::Idle);
            add_note_message(chat, &format!("Switched to session {id}."));
            true
        }
        Err(e) => {
            state.set_status(RunStatus::Idle);
            add_error_message(chat, &format!("Could not open session {id}: {e}"));
            false
        }
    }
}

/// `/import <path>`: copy a JSONL session file into the default session dir,
/// then hot-switch to it (the file name becomes its id — matching the
/// selector/`open_session_by_id` containment rules).
async fn import_session(
    harness: &AgentHarness,
    lane: &Arc<dyn AgentLane>,
    path: &str,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
) {
    use std::path::Path as FsPath;

    let src = FsPath::new(path);
    if !src.is_file() {
        add_error_message(chat, &format!("Import source not found: {path}"));
        return;
    }
    let Some(fname) = src.file_name().and_then(|f| f.to_str()) else {
        add_error_message(chat, "Import source has no file name.");
        return;
    };
    if !fname.ends_with(".jsonl") {
        add_error_message(chat, "Import source must be a .jsonl session file.");
        return;
    }
    let dir = crate::session::default_session_dir(cwd);
    if let Err(e) = std::fs::create_dir_all(&dir) {
        add_error_message(chat, &format!("Could not create session dir: {e}"));
        return;
    }
    let dest = dir.join(fname);
    match std::fs::copy(src, &dest) {
        Ok(_) => {
            let id = fname
                .strip_suffix(".jsonl")
                .unwrap_or(fname)
                .to_string();
            if switch_to_session(harness, lane, &id, cwd, chat, state).await {
                add_note_message(chat, &format!("Imported session from {path}"));
            }
        }
        Err(e) => add_error_message(chat, &format!("Could not copy import: {e}")),
    }
}

async fn fork_session(
    harness: &AgentHarness,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
) {
    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
    use rpi_tools::FileSystem;

    let cwd_str = cwd.to_string_lossy().to_string();
    let dir = crate::session::default_session_dir(cwd);
    let env = Arc::new(rpi_tools::OsExecutionEnv::with_cwd(cwd.to_path_buf()));
    let fs: Arc<dyn FileSystem> = env.clone();
    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs,
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(rpi_harness::session::memory::SystemClock),
        ids: Arc::new(rpi_harness::session::session::DefaultIdGenerator::new()),
    });
    // The fork needs the rich JSONL metadata (with the on-disk path); resolve
    // it from the session list by the current session's id.
    let id = harness.session().storage().metadata().id.clone();
    let metas = match crate::session::list_session_metadata(&cwd_str).await {
        Ok(m) => m,
        Err(e) => {
            add_error_message(chat, &format!("Could not list sessions: {e}"));
            return;
        }
    };
    let Some(source) = metas.iter().find(|m| m.id == id) else {
        add_error_message(chat, &format!("Current session {id} not found on disk."));
        return;
    };
    let fork_storage = match repo
        .fork_typed(
            source,
            &rpi_harness::session::jsonl::JsonlSessionCreateOptions {
                id: None,
                parent_session_id: Some(source.id.clone()),
                cwd: cwd_str.clone(),
                metadata: None,
            },
            &rpi_harness::session::types::ForkOptions::default(),
        )
        .await
    {
        Ok(s) => s,
        Err(e) => {
            add_error_message(chat, &format!("Could not fork session: {e}"));
            return;
        }
    };
    let new_session = rpi_harness::session::session::Session::new(Arc::new(fork_storage), None);
    let _ = harness.set_session(new_session).await;
    chat.clear();
    add_welcome_message(chat);
    render_session_history(harness, chat, state.markdown_transformer()).await;
    state.set_status(RunStatus::Idle);
    add_note_message(chat, "Forked into a new session.");
}

/// Render the restored session's prior transcript (user + assistant messages)
/// into the chat container. Called at TUI startup for `--continue`/`--resume`/
/// `--session` launches; a no-op for fresh sessions (no entries). Best-effort:
/// any session read failure just starts with an empty transcript.
///
/// `transformer` is the live assistant-markdown transformer (B5e); `None` is
/// the identity path. Each restored assistant component installs it so replayed
/// history renders through the same `register_markdown_transformer` handlers
/// the live stream does.
async fn render_session_history(
    harness: &AgentHarness,
    chat: &Arc<Container>,
    transformer: Option<MarkdownTransformer>,
) {
    let tree = harness.session().view("main");
    let entries = match tree.find_entries(&EntryQuery {
        entry_type: None,
        custom_type: None,
        order: None,
        limit: None,
        cursor: None,
    }).await {
        Ok(e) => e,
        Err(_) => return,
    };
    let mut rendered_any = false;
    for e in entries {
        let Entry::Message(me) = e else { continue };
        match &me.message {
            AgentMessage::User(u) => {
                add_user_message(chat, &user_message_text(u));
                rendered_any = true;
            }
            AgentMessage::Assistant(a) => {
                let comp = Arc::new(AssistantMessageComponent::new(
                    AssistantMessageOptions::default(),
                ));
                if let Some(t) = &transformer {
                    comp.set_markdown_transformer(Some(t.clone()));
                }
                comp.update_blocks(&assistant_blocks(a));
                chat.add_child(comp);
                chat.add_child(Arc::new(Spacer::new(1)));
                rendered_any = true;
            }
            _ => {}
        }
    }
    if rendered_any {
        chat.add_child(Arc::new(Spacer::new(1)));
    }
}

/// Project an assistant message's content into the provider-free
/// [`AssistantBlock`] list (text + thinking blocks, in document order) the
/// `AssistantMessageComponent` renders. Tool-call/image blocks are dropped —
/// they're rendered by their own components in the transcript. This keeps the
/// thinking blocks visible in the TUI (they previously vanished because the
/// stream path only fed the concatenated *text* into the component).
fn assistant_blocks(msg: &AssistantMessage) -> Vec<AssistantBlock> {
    msg.content
        .iter()
        .filter_map(|c| match c {
            Content::Text(t) => Some(AssistantBlock::Text(t.text.clone())),
            Content::Thinking(t) => Some(AssistantBlock::Thinking(t.thinking.clone())),
            _ => None,
        })
        .collect()
}

/// The name displayed for a model id (last path segment / after the final
/// `:`), to keep the footer compact.
fn short_model_name(id: &str) -> String {
    id.rsplit([':', '/'])
        .next()
        .filter(|s| !s.is_empty())
        .unwrap_or(id)
        .to_string()
}

// ===========================================================================
// Streaming run status
// ===========================================================================

/// The live status of the agent run, fed to the footer + status slot.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RunStatus {
    Idle,
    Working,
    Aborting,
}

/// Which selector overlay (if any) is currently swapped into the editor slot.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SelectorKind {
    /// `/model` — available models (live switch via `lane.set_model`).
    Model,
    /// `/thinking` — supported thinking levels (live via `lane.set_thinking_level`).
    Thinking,
    /// `/tools` — toggle builtin tools on/off.
    Tools,
    /// `/images` — toggle inline image rendering.
    Images,
    /// `/session` — saved JSONL sessions (restore not implemented in v1).
    Session,
    /// `/theme` — dark / light / monochrome presets applied live.
    Theme,
    /// `/scoped-models` — multi-toggle Ctrl+M cycle scope.
    ScopedModels,
    /// `/settings` — interactive settings menu (and its sub-selectors).
    Settings,
}

/// Shared mutable TUI state, `Arc`-cloned into the drain task, the key loop,
/// and the render-tick task.
struct TuiState {
    /// The in-flight streaming assistant message (cleared on finalize).
    current_assistant: std::sync::Mutex<Option<Arc<AssistantMessageComponent>>>,
    /// Tool-execution components keyed by `tool_call_id`.
    tool_components: std::sync::Mutex<HashMap<String, Arc<ToolExecutionComponent>>>,
    /// Bash-execution components keyed by `tool_call_id` (kept separate from the
    /// generic tool map so bash output streams into a `BashExecutionComponent`
    /// rather than a plain `ToolExecutionComponent`). Phase 5 routing.
    bash_components: std::sync::Mutex<HashMap<String, Arc<BashExecutionComponent>>>,
    /// The most recently created tool component (bash or generic). Ctrl+T
    /// toggles `expanded` on this — a pragmatic "expand last tool" since the
    /// key loop has no per-line focus. Updated on every tool/bash Start.
    last_tool_comp: std::sync::Mutex<Option<Arc<ToolExecutionComponent>>>,
    /// Run status for the status indicator + interrupt routing.
    status: std::sync::Mutex<RunStatus>,
    /// The footer, updated live by the drain task.
    footer: Arc<FooterComponent>,
    /// The status-container (status slot in the dock) — cleared/filled with a
    /// loader while a run is active.
    status_container: Arc<Container>,
    /// The chat transcript container.
    chat_container: Arc<Container>,
    /// The active loader shown while `Working`.
    loader: Arc<Loader>,
    /// The last finalized assistant text (for `/copy`). Updated by the drain
    /// task on `MessageEnd` / `AgentEnd`.
    last_assistant_text: std::sync::Mutex<String>,
    /// The active selector overlay, swapped into the editor slot. `Some` while
    /// a selector is open; the key loop routes to it first and restores the
    /// editor on done/cancel.
    active_selector: std::sync::Mutex<Option<(Arc<SelectList>, SelectorKind)>>,
    /// The autocomplete manager (slash + @file providers) consulted on every
    /// editor keystroke.
    autocomplete: AutocompleteManager,
    /// The container rendered above the editor holding the live autocomplete
    /// suggestion list (cleared when there are no suggestions).
    autocomplete_container: Arc<Container>,
    /// The owned theme manager — `/theme` applies presets here. The global
    /// `theme()` is read-only after OnceLock init, so per-instance state is the
    /// only way to apply a preset at runtime.
    theme_manager: Arc<ThemeManager>,
    /// The alt-screen handle, held so `set_status` can reflect run state in the
    /// terminal window title ("rpi — working" / "rpi"). `None` in unit tests
    /// that never call `set_status` with a title.
    tui: Option<Arc<TuiAltScreen>>,
    /// The model id currently shown in the footer + used as the Ctrl+M
    /// cycle anchor. Sync-tracked (updated on every `/model`/Ctrl+M switch) so
    /// the blocking key loop can cycle without awaiting `lane.get_model()`.
    current_model_id: std::sync::Mutex<String>,
    /// Whether inline image rendering is enabled (`/images` toggle). Stored
    /// even though image wiring is minimal this pass — the flag is consulted
    /// where images would be shown and echoed back by `/images`.
    show_images: std::sync::Mutex<bool>,
    /// Submitted-message history for ↑/↓ recall, most recent first (mirrors
    /// the TS editor `history` array). Bounded at [`HISTORY_LIMIT`].
    history: std::sync::Mutex<Vec<String>>,
    /// Browse index while recalling history: -1 = not browsing, 0 = most
    /// recent, 1 = older, … Reset to -1 on every submit.
    history_index: std::sync::Mutex<isize>,
    /// The editor text captured when entering browse mode, restored when the
    /// user navigates back past the newest entry (TS `historyDraft`).
    history_draft: std::sync::Mutex<Option<String>>,
    /// The previous turn's input token count, used by the cache-miss notice:
    /// a large input that reads nothing from cache after an established prefix
    /// means the prefix was re-billed (simplified `maybeShowCacheMissNotice`).
    last_input_tokens: std::sync::Mutex<i64>,
    /// The in-progress scoped-models selection while the `/scoped-models`
    /// selector is open (toggle per item, Esc saves). `None` when not editing.
    scoped_edit: std::sync::Mutex<Option<Vec<String>>>,
    /// B5e: the live assistant-markdown transformer, built from the current
    /// `RegistrySnapshot`'s `register_markdown_transformer` handlers. `None`
    /// when no markdown transformers are registered (identity render path).
    /// Swapped on `/reload` (a fresh snapshot ⇒ a fresh closure; the old
    /// closure no-ops once its snapshot's `active` flag flips false) and
    /// re-installed on the in-flight `current_assistant` so a reloaded plugin's
    /// transform takes effect on the visible streaming message immediately.
    /// New assistant components pick up whatever closure is current at
    /// construction time via [`install_markdown_transformer`].
    markdown_transformer: std::sync::Mutex<Option<MarkdownTransformer>>,
}

/// How many submitted messages are kept for ↑ recall (mirrors the TS
/// editor's 100-entry cap).
const HISTORY_LIMIT: usize = 100;

/// A turn with at least this many input tokens is worth a cache-miss notice
/// when nothing was read from cache (matches the TS 20k threshold).
const CACHE_MISS_MIN_INPUT_TOKENS: i64 = 20_000;

/// Compact token count for the cache-miss notice: 1.2M / 34.5K / 900.
fn format_tokens(n: i64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{:.1}K", n as f64 / 1_000.0)
    } else {
        n.to_string()
    }
}

/// Record a submitted message for ↑ recall (mirrors TS `addToHistory`):
/// trims, skips empty + consecutive duplicates, caps at [`HISTORY_LIMIT`], and
/// resets the browse state so a fresh prompt never resumes mid-history.
fn push_history(state: &Arc<TuiState>, text: &str) {
    let trimmed = text.trim().to_string();
    if trimmed.is_empty() {
        return;
    }
    let mut history = state.history.lock().unwrap();
    if history.first() == Some(&trimmed) {
        return;
    }
    history.insert(0, trimmed);
    history.truncate(HISTORY_LIMIT);
    *state.history_index.lock().unwrap() = -1;
    *state.history_draft.lock().unwrap() = None;
}

/// Navigate message history. `direction` is -1 (↑, older) or 1 (↓, newer).
/// Mirrors TS `navigateHistory`: the first entry into browse mode stashes the
/// current editor text as the draft; navigating back past the newest entry
/// restores that draft.
fn navigate_history(state: &Arc<TuiState>, editor: &Arc<Editor>, direction: i32) {
    let history = state.history.lock().unwrap();
    if history.is_empty() {
        return;
    }
    let mut index = state.history_index.lock().unwrap();
    let new_index = *index - direction as isize;
    if new_index < -1 || new_index >= history.len() as isize {
        return;
    }
    if *index == -1 && new_index >= 0 {
        // Entering browse mode: stash the current input.
        *state.history_draft.lock().unwrap() = Some(editor.get_text());
    }
    *index = new_index;
    if new_index == -1 {
        // Exited browse mode: restore the draft (or clear if there was none).
        let draft = state.history_draft.lock().unwrap().take();
        match draft {
            Some(d) => {
                let len = d.len();
                editor.set_text(&d);
                editor.set_cursor(0, len);
            }
            None => editor.set_text(""),
        }
    } else {
        let text = history[new_index as usize].clone();
        let len = text.len();
        editor.set_text(&text);
        editor.set_cursor(0, len);
    }
}

impl TuiState {
    fn set_status(&self, status: RunStatus) {
        *self.status.lock().unwrap() = status;
        match status {
            RunStatus::Working => {
                self.footer.set_status("Working…");
                // Reflect the in-flight turn in the terminal window/tab title
                // (OSC 2). No-op when `tui` is absent (unit tests).
                if let Some(tui) = &self.tui {
                    tui.set_title("rpi — working");
                }
                self.status_container.clear();
                self.loader.start();
                self.status_container.add_child(self.loader.clone());
            }
            RunStatus::Aborting => {
                self.footer.set_status("Aborting…");
            }
            RunStatus::Idle => {
                self.footer.set_status("");
                if let Some(tui) = &self.tui {
                    tui.set_title("rpi");
                }
                self.loader.stop();
                self.status_container.clear();
            }
        }
    }

    /// Whether a selector overlay is currently open (routes keys to it first).
    fn selector_open(&self) -> bool {
        self.active_selector.lock().unwrap().is_some()
    }

    /// Record a freshly created tool component as the "most recent" so Ctrl+T
    /// can toggle its expansion. Idempotent overwrites — only the latest lives.
    fn remember_tool(&self, comp: Arc<ToolExecutionComponent>) {
        *self.last_tool_comp.lock().unwrap() = Some(comp);
    }

    /// Toggle `expanded` on the most recent tool component (Ctrl+T). Returns
    /// `true` if a component was toggled. Limitation: the key loop tracks no
    /// per-line focus, so this always targets the *last* tool shown — not the
    /// one under the cursor. Documented in the plan; a focused expansion would
    /// need mouse/line hit-testing which is out of scope this pass.
    fn toggle_expand_last_tool(&self) -> bool {
        if let Some(comp) = self.last_tool_comp.lock().unwrap().as_ref() {
            let cur = comp.is_expanded();
            comp.set_expanded(!cur);
            true
        } else {
            false
        }
    }

    /// The model id currently tracked as active (footer + Ctrl+M anchor).
    fn current_model_id(&self) -> String {
        self.current_model_id.lock().unwrap().clone()
    }

    /// Update the tracked model id + footer label after a switch (live or
    /// cycle). Called from the `/model` on_select and the Ctrl+M handler.
    fn set_current_model(&self, model: &rpi_ai::Model) {
        *self.current_model_id.lock().unwrap() = model.id.clone();
        self.footer.set_model(&short_model_name(&model.id));
    }

    /// B5e: read a clone of the current assistant-markdown transformer (if any).
    /// New assistant components call this at construction so they render with
    /// whatever plugin `register_markdown_transformer` handlers are live.
    fn markdown_transformer(&self) -> Option<MarkdownTransformer> {
        self.markdown_transformer.lock().unwrap().clone()
    }

    /// B5e: swap the live transformer. Used at startup (install the first
    /// closure built from the initial `RegistrySnapshot`) and on `/reload`
    /// (rebuild from the fresh snapshot). On a reload the reloaded plugin's
    /// transform should take effect on the VISIBLE streaming message too, so
    /// this re-installs on the in-flight `current_assistant` component — its
    /// `set_markdown_transformer` rebuilds the last blocks immediately. A
    /// `None` clears the transform (identity), e.g. a reload that unregisters
    /// every markdown transformer.
    fn set_markdown_transformer_with_reinstall(&self, transformer: Option<MarkdownTransformer>) {
        *self.markdown_transformer.lock().unwrap() = transformer.clone();
        if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
            comp.set_markdown_transformer(transformer);
        }
    }
}

// ===========================================================================
// interactive_tui — the entry point
// ===========================================================================

/// TUI-based interactive mode.
///
/// `event_rx` carries the live `AgentEvent` stream (installed by
/// [`crate::session::build`]); when `None` (e.g. a non-TUI caller reuses this
/// fn), it falls back to a blocking, await-final-text path.
///
/// `model_catalog` is the read-only catalog the `/model` selector displays.
///
/// This implementation mirrors the TypeScript `InteractiveMode` class:
/// build the layout root once, drain `AgentEvent`s into UI mutations that
/// mirror `handleEvent`, and dispatch keys from a `spawn_blocking` crossterm
/// loop (the `TuiAltScreen` start() handler is a stub). Selectors and
/// autocomplete are layered on via the editor-container swap pattern.
pub async fn interactive_tui(
    harness: &AgentHarness,
    event_rx: Option<broadcast::Receiver<AgentEvent>>,
    args: &Args,
    model_catalog: Vec<rpi_ai::Model>,
    initial: Option<String>,
    extra_messages: &[String],
    theme: Option<&str>,
    reload_context: &crate::session::ReloadContext,
) -> i32 {
    let lane: Arc<dyn AgentLane> = harness.lane("main");

    // Resolve the active model once, up front. The full id feeds the TuiState
    // tracking field + the selectors/key loop (which run on a blocking thread
    // and can't await `lane.get_model()`); the short name feeds the footer.
    let lane_model_id = lane
        .get_model()
        .await
        .map(|m| m.id)
        .unwrap_or_default();
    let model_name = short_model_name(&lane_model_id);

    // The cwd for @file autocomplete + session discovery.
    let cwd = std::env::current_dir()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|_| std::path::PathBuf::from("."));

    // Channel between the key/callback threads and the main async loop.
    let (tx, rx) = channel::<TuiMessage>();

    // ---- TUI + containers ----
    let terminal = Box::new(ProcessTerminal::new());
    let tui = Arc::new(TuiAltScreen::new(terminal, true, None));

    let chat_container = Arc::new(Container::new());
    add_welcome_message(&chat_container);

    // First-launch gate: if `~/.rpi/.setup_done` is absent, show the welcome
    // banner + the earendil announcement once, then write the sentinel. The TS
    // original is a multi-step dialog (theme picker + analytics opt-in); this
    // v1 simplifies to a one-shot banner (theme still pickable via `/theme`,
    // analytics deferred — no telemetry wiring). See `extras.rs`.
    crate::extras::maybe_first_time_setup(&chat_container);

    // A --continue/--resume/--session launch opens on an existing JSONL
    // session — render its prior user/assistant transcript so the user sees
    // where they left off (tool executions are skipped: their live display
    // belongs to the current run, and replaying old results would be noise).
    let initial_transformer = build_markdown_transformer(
        reload_context.extension_session.lock().unwrap().snapshot_arc(),
    );
    render_session_history(&harness, &chat_container, initial_transformer.clone()).await;

    // `document_container` wraps the welcome header + chat so the scrollview
    // follows the whole transcript (mirrors TS `documentContainer`).
    let document_container = Arc::new(Container::new());
    document_container.add_child(chat_container.clone());

    let scroll_view = Arc::new(ScrollView::new(
        document_container.clone(),
        ScrollViewOptions {
            follow: FollowMode::End,
            primary: true,
            ..Default::default()
        },
    ));

    // ---- Editor ----
    // Bordered box matching native pi: no `> ` prompt, no placeholder — the
    // editor renders full-width `─` top/bottom borders with padding-only lines
    // (see Editor::render). padding_x:1 gives a 1-col inset inside the box.
    let editor = Arc::new(Editor::new(
        EditorOptions {
            padding_x: 1,
            ..Default::default()
        },
        EditorStyle::default(),
        Arc::new(rpi_tui::Keybindings::new()),
    ));

    // ---- Footer + status ----
    let footer = Arc::new(FooterComponent::new());
    footer.set_model(&model_name);
    footer.set_hints("Enter: Send | Shift+Enter: New line | Ctrl+C: Abort/Exit | Esc: Abort | Ctrl+L: Model | Ctrl+M: Cycle | Ctrl+T: Expand tool | /help");

    let status_container = Arc::new(Container::new());
    let loader = Arc::new(Loader::with_text("Working…"));

    // ---- Autocomplete (slash commands + @file paths, rooted at cwd) ----
    // Prompt templates discovered at session build (Part A2) are surfaced as
    // `/`-prefixed entries alongside the built-in slash commands: typing
    // `/<name>` in the editor expands the template (mirrors pi
    // `expandPromptTemplate`, `agent-session.ts:1124`). The description carries
    // the template's frontmatter description (or a fallback) so the autocomplete
    // popover shows what each template does.
    //
    // We snapshot the full resources once (skills + prompt-templates): the
    // autocomplete builder consumes the templates, and the `/context` command
    // (fired from the blocking submit handler, which can't `.await`) reads the
    // snapshot to render the discovered-resources panel without touching the
    // harness async accessor.
    let resources_snapshot = harness.get_resources().await.unwrap_or_default();
    let template_slash_commands: Vec<SlashCommandEntry> = resources_snapshot
        .prompt_templates
        .clone()
        .unwrap_or_default()
        .iter()
        .map(|t| SlashCommandEntry {
            name: format!("/{}", t.name),
            description: t
                .description
                .clone()
                .unwrap_or_else(|| "Expand prompt template".to_string()),
        })
        .collect();
    let resources_arc: Arc<rpi_harness::types::AgentHarnessResources> = Arc::new(resources_snapshot);
    // Build the built-in command registry once — the single source of truth for
    // both dispatch and the built-in autocomplete entries. The discovered
    // prompt-template commands are merged into the autocomplete list separately
    // (they dispatch via template expansion, not the registry); built-ins come
    // first so they win on a fuzzy tie.
    let registry = Arc::new(build_builtin_registry());
    let mut all_slash_commands = registry.visible_entries();
    all_slash_commands.extend(template_slash_commands);
    let autocomplete = AutocompleteManager::new();
    {
        let mut combined = CombinedAutocompleteProvider::new();
        combined.add_provider(Arc::new(SlashCommandAutocompleteProvider::new(
            all_slash_commands,
        )));
        combined.add_provider(Arc::new(FilePathAutocompleteProvider::with_root(cwd.clone())));
        autocomplete.set_provider(Arc::new(combined));
    }
    let autocomplete_container = Arc::new(Container::new());

    let state = Arc::new(TuiState {
        current_assistant: std::sync::Mutex::new(None),
        tool_components: std::sync::Mutex::new(HashMap::new()),
        bash_components: std::sync::Mutex::new(HashMap::new()),
        last_tool_comp: std::sync::Mutex::new(None),
        status: std::sync::Mutex::new(RunStatus::Idle),
        footer: footer.clone(),
        status_container: status_container.clone(),
        chat_container: chat_container.clone(),
        loader: loader.clone(),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        autocomplete,
        autocomplete_container: autocomplete_container.clone(),
        theme_manager: Arc::new(ThemeManager::new()),
        tui: Some(tui.clone()),
        current_model_id: std::sync::Mutex::new(lane_model_id.clone()),
        show_images: std::sync::Mutex::new(true),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        last_input_tokens: std::sync::Mutex::new(0),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: std::sync::Mutex::new(initial_transformer),
    });

    // Apply the saved theme from `~/.rpi/agent/settings.json` (best-effort).
    // The host passes `theme` in; when it matches a known preset it is applied
    // immediately so launch opens in the user's chosen theme (matching pi
    // reading `Settings.theme` at startup). Unknown values are ignored.
    if let Some(theme_name) = theme {
        let preset = match theme_name {
            "light" => Some(ThemePreset::Light),
            "monochrome" => Some(ThemePreset::Monochrome),
            "dark" => Some(ThemePreset::Dark),
            _ => None,
        };
        if let Some(preset) = preset {
            state.theme_manager.apply_preset(preset);
        }
    }

    // Capture the model catalog + cwd for the selector builders + the key loop
    // (the callbacks fire on blocking threads and need owned data).
    let model_catalog_arc = Arc::new(model_catalog.clone());
    let lane_model_id = lane
        .get_model()
        .await
        .map(|m| m.id)
        .unwrap_or_default();

    // ---- Layout root (built ONCE; mirrors TS fullscreenLayoutRoot) ----
    // root = VStack[ scrollview(basis:0 grow:1 shrink:1 min:1), dock(shrink:1) ]
    // dock  = VStack[ status(auto), autocomplete(auto), editor_container(shrink:0 min:3), footer(auto) ]
    //
    // The scrollview gets `basis(0)` so the constrained stack allocator starts
    // it at zero height and grows it to fill the space the dock does not need
    // — this keeps the dock (editor borders + footer) pinned to the bottom and
    // never shrinks it below the editor's 3 rows (top border + content + bottom
    // border). The editor_container is `shrink(0).min_size(3)` so a tall
    // transcript can never clip the bordered editor below its minimum.
    let editor_container = Arc::new(Container::new());
    editor_container.add_child(editor.clone());

    let dock = Arc::new(VStack::from_children(vec![
        StackChild::Entry(StackEntry::new(status_container.clone())),
        StackChild::Entry(StackEntry::new(autocomplete_container.clone())),
        StackChild::Entry(
            StackEntry::new(editor_container.clone())
                .shrink(0)
                .min_size(3),
        ),
        StackChild::Entry(StackEntry::new(footer.clone())),
    ]));

    let root = VStack::from_children(vec![
        StackChild::Entry(
            StackEntry::new(scroll_view.clone())
                .basis(0)
                .grow(1)
                .shrink(1)
                .min_size(1),
        ),
        StackChild::Entry(StackEntry::new(dock).shrink(1)),
    ]);

    tui.set_layout_root(Some(Arc::new(root)));
    tui.set_focus(Some(editor.clone()));
    editor.set_focused(true);

    // ---- Submit handler (fires on the blocking key thread; must stay sync) ----
    //
    // The handler captures one `CommandContext` (the set of `*_for_cb` clones
    // the old version made individually) + the registry, then routes `/`-text
    // through `dispatch_slash` and sends plain text directly. Each command's
    // `execute` owns its own effects (selector open, `tx.send`, `tokio::spawn`,
    // chat mutation) — the handler itself stays a thin router.
    //
    // One `CommandContext` is built and cloned for both the submit handler and
    // the key loop (Ctrl+L routes `/model` through the same registry); all
    // fields are `Arc`/cheap, so the clones are free.
    let ctx = CommandContext {
        chat: chat_container.clone(),
        tui: tui.clone(),
        tx: tx.clone(),
        state: state.clone(),
        editor: editor.clone(),
        editor_container: editor_container.clone(),
        lane: lane.clone(),
        model_catalog: model_catalog_arc.clone(),
        lane_model_id: lane_model_id.clone(),
        cwd: cwd.clone(),
        resources: resources_arc.clone(),
        reload_context: Arc::new(reload_context.clone()),
    };
    let ctx_for_cb = ctx.clone();
    let registry_for_cb = registry.clone();
    editor.on_submit(Arc::new(move |text: &str| {
        let text = text.trim();
        if text.is_empty() {
            return;
        }

        if text.starts_with('/') {
            dispatch_slash(text, &ctx_for_cb, &registry_for_cb);
            return;
        }

        add_user_message(&ctx_for_cb.chat, text);
        ctx_for_cb.tui.request_render(false);
        // Remember the message for ↑ recall (slash commands are not part of
        // the replayable message history).
        push_history(&ctx_for_cb.state, text);
        let _ = ctx_for_cb.tx.send(TuiMessage::UserInput(text.to_string()));
    }));

    tui.start_readerless();

    // ---- Streaming drain task ----
    let drain_handle = if let Some(rx) = event_rx {
        let tui_drain = tui.clone();
        let state_drain = state.clone();
        let chat_drain = chat_container.clone();
        Some(tokio::spawn(async move {
            drain_agent_events(rx, tui_drain, state_drain, chat_drain).await;
        }))
    } else {
        None
    };

    // ---- B5d: plugin→TUI reload bridge ----
    // A plugin's `runtime_action(Reload)` can't drive the reload synchronously
    // (its cdylib would be unmapped while the call frame is still on the stack).
    // Instead the `ActionBridge`'s reload callback signals `reload_context.mailbox`
    // (an `UnboundedSender<()>`); this task drains those signals and forwards
    // `TuiMessage::ReloadExtensions` into the main loop, which runs the shared
    // `reload_extension_resources` routine asynchronously. The mailbox is the
    // cycle-free seam: rpi-extensions carries only `()` (no `TuiMessage` type —
    // leaf DAG preserved); the TUI owns the receiver + the reload routine.
    let (reload_sig_tx, mut reload_sig_rx) =
        tokio::sync::mpsc::unbounded_channel::<()>();
    reload_context.mailbox.install(reload_sig_tx);
    let reload_tx = tx.clone();
    let reload_bridge_handle = tokio::spawn(async move {
        while reload_sig_rx.recv().await.is_some() {
            if reload_tx.send(TuiMessage::ReloadExtensions).is_err() {
                break; // main loop gone — stop forwarding
            }
        }
    });

    // ---- Render-tick task (advances the loader spinner while Working) ----
    //
    // The `Loader` only advances its frame on render; without a periodic
    // `request_render` the spinner visibly freezes between events.
    let tui_tick = tui.clone();
    let state_tick = state.clone();
    let tick_handle = tokio::spawn(async move {
        let mut interval = tokio::time::interval(std::time::Duration::from_millis(120));
        interval.tick().await; // discard immediate
        loop {
            interval.tick().await;
            let working = *state_tick.status.lock().unwrap() == RunStatus::Working;
            if working {
                tui_tick.request_render(false);
            }
        }
    });

    // ---- Key dispatch loop (spawn_blocking crossterm read) ----
    let running = Arc::new(std::sync::Mutex::new(true));
    let running_key = running.clone();
    let tx_for_key = tx.clone();
    let tui_for_key = tui.clone();
    let editor_for_key = editor.clone();
    let editor_container_for_key = editor_container.clone();
    let scroll_for_key = scroll_view.clone();
    let lane_for_key = lane.clone();
    let state_for_key = state.clone();
    // Ctrl+L routes through the same registry as `/model` (one path, not two),
    // so the key loop needs the same `CommandContext` + registry the submit
    // handler uses. All fields are `Arc`/cheap, so this clone is free.
    let ctx_for_key = ctx.clone();
    let registry_for_key = registry.clone();

    tokio::task::spawn_blocking(move || {
        loop {
            if !*running_key.lock().unwrap() {
                break;
            }
            let Ok(ev) = crossterm::event::read() else {
                continue;
            };
            // `Event::Resize` is delivered as its own event (not a Key). With
            // `start_readerless` there is no competing terminal-reader thread to
            // handle it, so refresh the cached terminal size here and force a
            // full redraw so the constrained layout re-fits the new dimensions.
            if let Event::Resize(_cols, _rows) = ev {
                tui_for_key.refresh_size();
                continue;
            }
            let Event::Key(key) = ev else { continue; };
            // Drop release/repeat events — on Windows a single keystroke
            // yields both a Press and a Release; without this filter every
            // char is inserted twice. (Mirrors the TS `isKeyRelease` guard;
            // the editor never sets `wants_key_release`.) On terminals that
            // only emit Press this is a no-op.
            if key.kind != KeyEventKind::Press {
                continue;
            }

            // 0. Ctrl+C is ALWAYS the escape hatch — even with a selector
            //    open (a stuck run or a mis-open selector must never trap the
            //    user): abort an active run, else exit. Checked before the
            //    selector routing below.
            if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('c') {
                let status = *state_for_key.status.lock().unwrap();
                if status == RunStatus::Working {
                    state_for_key.set_status(RunStatus::Aborting);
                    let lane = lane_for_key.clone();
                    tokio::spawn(async move {
                        let _ = lane.abort().await;
                    });
                } else {
                    let _ = tx_for_key.send(TuiMessage::Exit);
                }
                continue;
            }

            // 1. A selector overlay is open → route to it first. Only Esc
            //    (cancel) and Enter/Up/Down/Ctrl-K/J/P/N (navigate/select)
            //    escape to the selector; on done/cancel the selector callbacks
            //    restore the editor and clear `active_selector`.
            if state_for_key.selector_open() {
                // Esc always cancels the selector (even with modifiers off).
                // Route through `SelectList::handle_key(Esc)` so the list's
                // `on_cancel` fires (the `/scoped-models` toggle selector saves
                // its edits there) — the old shortcut called `close_selector`
                // directly and skipped the callback.
                if key.code == KeyCode::Esc {
                    let (selector, _kind) = state_for_key
                        .active_selector
                        .lock()
                        .unwrap()
                        .clone()
                        .expect("selector_open guaranteed Some");
                    selector.handle_key(key);
                    continue;
                }
                let (selector, _kind) = state_for_key
                    .active_selector
                    .lock()
                    .unwrap()
                    .clone()
                    .expect("selector_open guaranteed Some");
                selector.handle_key(key);
                tui_for_key.request_render(false);
                continue;
            }

            // 2a. Ctrl+D (EOF): exit. Mirrors pi binding Ctrl+D to quit — and
            //     when a run is active, abort it first (same as Ctrl+C) so the
            //     key is never a no-op while a stuck command is running.
            if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('d') {
                let status = *state_for_key.status.lock().unwrap();
                if status == RunStatus::Working {
                    state_for_key.set_status(RunStatus::Aborting);
                    let lane = lane_for_key.clone();
                    tokio::spawn(async move {
                        let _ = lane.abort().await;
                    });
                } else {
                    let _ = tx_for_key.send(TuiMessage::Exit);
                }
                continue;
            }

            // 2b. Esc: interrupt an active run (mirrors Ctrl+C abort). When a
            //     selector is open Esc already cancelled it above; when idle,
            //     Esc falls through to the editor (no-op-ish). Only fire while
            //     Working so an idle Esc doesn't abort a non-existent run.
            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Esc {
                let status = *state_for_key.status.lock().unwrap();
                if status == RunStatus::Working {
                    state_for_key.set_status(RunStatus::Aborting);
                    let lane = lane_for_key.clone();
                    tokio::spawn(async move {
                        let _ = lane.abort().await;
                    });
                    continue;
                }
            }

            // 2c. Ctrl+T: toggle expansion on the most recent tool component.
            //     The key loop tracks no per-line focus, so this is an "expand
            //     last tool" affordance rather than a cursor-targeted toggle
            //     (documented limitation; see `toggle_expand_last_tool`).
            if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('t') {
                state_for_key.toggle_expand_last_tool();
                tui_for_key.request_render(false);
                continue;
            }

            // 2d. Ctrl+M: cycle to the next model in the catalog after the one
            //     currently tracked in `current_model_id`, apply it live via
            //     `lane.set_model` (takes effect on the next user message — the
            //     in-flight run's config is already snapshotted), and update the
            //     footer. `set_model` is async so it runs on a spawned task.
            if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('m') {
                let current = state_for_key.current_model_id();
                // Cycle within the `/scoped-models` set (settings.json) when
                // configured; otherwise the full catalog.
                let scope = scoped_catalog(&ctx_for_key.model_catalog, &current);
                if let Some(next) = cycle_next_model(&scope, &current) {
                    state_for_key.set_current_model(&next);
                    let lane = lane_for_key.clone();
                    tokio::spawn(async move {
                        let _ = lane.set_model(next).await;
                    });
                    tui_for_key.request_render(false);
                }
                continue;
            }

            // 3. Ctrl+L: open the model selector. Routed through the `/model`
            //    command so the hotkey and the slash command share one path
            //    (TS binds Ctrl+L to model-select).
            if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('l') {
                if let Some(cmd) = registry_for_key.find("/model") {
                    cmd.execute(&ctx_for_key, "");
                }
                continue;
            }

            // 4. Tab: accept the top autocomplete suggestion (if any).
            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Tab {
                if accept_top_suggestion(&state_for_key, &editor_for_key) {
                    tui_for_key.request_render(false);
                }
                continue;
            }

            // 5. Global transcript scroll: PageUp/PageDown move the scrollview.
            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::PageUp {
                scroll_for_key.scroll_by(-10);
                tui_for_key.request_render(false);
                continue;
            }
            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::PageDown {
                scroll_for_key.scroll_by(10);
                tui_for_key.request_render(false);
                continue;
            }

            // 5b. ↑/↓ browse submitted-message history when the caret sits at
            //     the start/end of the editor (mirrors TS
            //     `tui.editor.historyPrevious/Next`, which only intercept at
            //     the first/last visual line); anywhere else they fall through
            //     to the editor for multi-line cursor movement.
            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Up {
                let (row, col) = editor_for_key.cursor_position();
                if row == 0 && col == 0 {
                    navigate_history(&state_for_key, &editor_for_key, -1);
                    tui_for_key.request_render(false);
                    continue;
                }
            }
            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Down {
                let text = editor_for_key.get_text();
                let (row, col) = editor_for_key.cursor_position();
                let last_row = text.lines().count().saturating_sub(1);
                let last_len = text.lines().last().map(str::len).unwrap_or(0);
                if row == last_row && col >= last_len {
                    navigate_history(&state_for_key, &editor_for_key, 1);
                    tui_for_key.request_render(false);
                    continue;
                }
            }

            // 6. Otherwise forward to the editor + refresh autocomplete.
            editor_for_key.handle_key(key);
            refresh_autocomplete(&state_for_key, &editor_for_key);
            tui_for_key.request_render(false);
        }
    });

    // ---- Initial prompts (run before reading from the channel) ----
    let mut prompts: Vec<String> = Vec::new();
    if let Some(init) = initial {
        prompts.push(init);
    }
    for m in extra_messages {
        prompts.push(m.clone());
    }
    for prompt in prompts {
        if !*running.lock().unwrap() {
            break;
        }
        add_user_message(&chat_container, &prompt);
        tui.request_render(false);
        run_prompt_streaming(&lane, &prompt, &tui, &state, drain_handle.is_some()).await;
    }

    // ---- Main loop: process submitted input + lifecycle messages ----
    loop {
        if !*running.lock().unwrap() {
            break;
        }
        match rx.try_recv() {
            Ok(TuiMessage::UserInput(prompt)) => {
                // Clear the editor so the next prompt starts fresh (the submit
                // handler runs on the blocking key thread and can't mutate the
                // editor state safely there; clearing here, on the async loop,
                // keeps it on one thread).
                editor.clear();
                run_prompt_streaming(&lane, &prompt, &tui, &state, drain_handle.is_some()).await;
            }
            Ok(TuiMessage::ClearChat) => {
                chat_container.clear();
                add_welcome_message(&chat_container);
                tui.request_render(false);
            }
            Ok(TuiMessage::Compact) => {
                run_compact(&lane, &tui, &state).await;
            }
            Ok(TuiMessage::Copy) => {
                copy_last_assistant(&state, &chat_container);
                tui.request_render(false);
            }
            Ok(TuiMessage::Exit) => {
                *running.lock().unwrap() = false;
                break;
            }
            Ok(TuiMessage::SwitchSession(id)) => {
                switch_to_session(&harness, &lane, &id, &cwd, &chat_container, &state).await;
                tui.request_render(false);
            }
            Ok(TuiMessage::ImportSession(path)) => {
                import_session(&harness, &lane, &path, &cwd, &chat_container, &state).await;
                tui.request_render(false);
            }
            Ok(TuiMessage::ShareSession) => {
                share_session(&harness, &chat_container).await;
                tui.request_render(false);
            }
            Ok(TuiMessage::SetSessionName(name)) => {
                let outcome = harness.session().set_name(Some(&name)).await;
                match outcome {
                    Ok(_) => add_note_message(
                        &chat_container,
                        &format!("Session renamed to \"{name}\"."),
                    ),
                    Err(e) => add_error_message(
                        &chat_container,
                        &format!("Could not rename session: {e}"),
                    ),
                }
                tui.request_render(false);
            }
            Ok(TuiMessage::ExportSession) => {
                export_session(&harness, &chat_container).await;
                tui.request_render(false);
            }
            Ok(TuiMessage::ForkSession) => {
                fork_session(&harness, &cwd, &chat_container, &state).await;
                tui.request_render(false);
            }
            Ok(TuiMessage::ReloadExtensions) => {
                // B5d: drive the shared reload routine on the async runtime,
                // then surface the outcome. `reload_context` was passed into
                // `interactive_tui` and is the same `Arc<ReloadContext>` the
                // `ReloadCommand` + the plugin mailbox both route through —
                // clone the `Arc` out so the borrow of `harness` (the main
                // loop's `&AgentHarness`) lives across the await.
                let reload_ctx = ctx.reload_context.clone();
                add_note_message(&chat_container, "Reloading extensions + resources…");
                tui.request_render(false);
                let outcome =
                    crate::session::reload_extension_resources(&harness, &reload_ctx).await;
                // B5e: the reload swapped a fresh `ExtensionSession` into the
                // context's cell. Rebuild the markdown transformer from that
                // fresh snapshot and install it on the in-flight streaming
                // component (so a reloaded plugin's transformer takes effect on
                // the visible message immediately) + future components (they
                // read `state.markdown_transformer()` at construction). The old
                // closure no-ops once its snapshot's `active` flag flips false
                // (reload already did that before the swap).
                let fresh_transformer = build_markdown_transformer(
                    reload_ctx.extension_session.lock().unwrap().snapshot_arc(),
                );
                state.set_markdown_transformer_with_reinstall(fresh_transformer);
                if outcome.had_warnings {
                    add_error_message(
                        &chat_container,
                        &format!("{} (with warnings — see stderr for details).", outcome.summary),
                    );
                } else {
                    add_note_message(&chat_container, &outcome.summary);
                }
                tui.request_render(false);
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => {
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            }
            Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
        }
    }

    // ---- Shutdown ----
    tick_handle.abort();
    if let Some(handle) = drain_handle {
        handle.abort();
    }
    // Drop the reload bridge: clearing the mailbox closes the signal channel,
    // the drain task's `recv` returns `None`, and the task exits. (Aborting is
    // redundant — the recv terminates — but cheap + makes shutdown explicit.)
    reload_context.mailbox.clear();
    reload_bridge_handle.abort();
    tui.stop(Default::default());
    println!("\nGoodbye!");
    let _ = args;

    0
}

// ===========================================================================
// Run a single prompt (streaming or blocking)
// ===========================================================================

/// Drive a single prompt through the lane. When `streaming` is true, the
/// `AgentEvent` drain task renders the response live and this function only
/// awaits completion (to surface hard errors). When false (no `event_rx`),
/// it falls back to the blocking await-final-text path.
async fn run_prompt_streaming(
    lane: &Arc<dyn AgentLane>,
    prompt: &str,
    tui: &Arc<TuiAltScreen>,
    state: &Arc<TuiState>,
    streaming: bool,
) {
    // Ensure the run starts in a clean streaming state.
    state.set_status(RunStatus::Working);
    tui.request_render(false);

    let outcome = lane.prompt_text(prompt, Vec::new()).await;

    // The drain task finalized the assistant message via MessageEnd/AgentEnd,
    // but guard against runs that ended without a terminal event (e.g. a hard
    // provider rejection before any streaming) by clearing streaming state.
    {
        let mut cur = state.current_assistant.lock().unwrap();
        if let Some(comp) = cur.take() {
            comp.set_streaming(false);
        }
    }

    state.set_status(RunStatus::Idle);

    match outcome {
        Ok(result) => match &result.outcome {
            HarnessRunOutcome::Failed { error, final_message, .. } => {
                // Only add an error line if the stream did NOT already render
                // an assistant message for it (drain task leaves
                // current_assistant Some only on an abrupt end).
                let already_rendered = final_message.is_some();
                if !already_rendered {
                    let msg = final_message
                        .as_ref()
                        .and_then(|m| m.error_message.clone())
                        .unwrap_or_else(|| format!("{error:?}"));
                    add_error_message(&state.chat_container, &msg);
                }
            }
            HarnessRunOutcome::Suspended { .. } => {
                add_error_message(
                    &state.chat_container,
                    "Run suspended (deferred) — resume is not supported in v1.",
                );
            }
            HarnessRunOutcome::Aborted { final_message, .. } => {
                // Aborted runs render their own partial/final message via the
                // stream; only add a note on the blocking fallback path.
                if !streaming {
                    add_error_message(&state.chat_container, "Request aborted.");
                    let _ = final_message; // (rendered by the stream in streaming mode)
                }
            }
            HarnessRunOutcome::Completed { final_message, .. } => {
                if !streaming {
                    let text = assistant_text(final_message);
                    if !text.is_empty() {
                        add_assistant_message_blocking(
                            &state.chat_container,
                            &text,
                            state.markdown_transformer(),
                        );
                        *state.last_assistant_text.lock().unwrap() = text;
                    }
                }
            }
        },
        Err(e) => {
            add_error_message(&state.chat_container, &e.to_string());
        }
    }

    tui.request_render(false);
}

/// `/compact`: drive a compaction on the lane (mirrors TS `app.compact`).
/// Reports the outcome as a transcript note; v1's compaction summarizes the
/// session in place, so no streaming display is wired (compaction emits no
/// `AgentEvent`s — only the harness bus `RunEnd`).
async fn run_compact(lane: &Arc<dyn AgentLane>, tui: &Arc<TuiAltScreen>, state: &Arc<TuiState>) {
    state.set_status(RunStatus::Working);
    tui.request_render(false);
    match lane.compact(None).await {
        Ok(_) => {
            add_note_message(&state.chat_container, "Conversation compacted.");
        }
        Err(e) => {
            add_error_message(
                &state.chat_container,
                &format!("Compact failed: {e}"),
            );
        }
    }
    state.set_status(RunStatus::Idle);
    tui.request_render(false);
}

/// `/copy`: copy the last assistant reply to the clipboard. Best-effort —
/// when no clipboard is available (or the `clipboard` feature is off), prints a
/// hint instead. Mirrors the TS `/copy` (copies `this.messages.at(-1)` text).
fn copy_last_assistant(state: &Arc<TuiState>, chat: &Arc<Container>) {
    let text = state.last_assistant_text.lock().unwrap().clone();
    if text.is_empty() {
        add_note_message(chat, "Nothing to copy yet — no assistant reply captured.");
        return;
    }
    if copy_to_clipboard(&text) {
        add_note_message(chat, "Copied last reply to the clipboard.");
    } else {
        // Clipboard unavailable — print the text to the transcript so the user
        // can select/copy it manually (degrades gracefully in headless envs).
        let preview: String = text.chars().take(200).collect();
        add_note_message(
            chat,
            &format!("Clipboard unavailable. Last reply: {preview}{}", if text.chars().count() > 200 { "" } else { "" }),
        );
    }
}

/// Best-effort clipboard write. Enabled only with the `clipboard` feature
/// (`arboard`); otherwise returns `false` so the caller degrades to a hint.
#[cfg(feature = "clipboard")]
fn copy_to_clipboard(text: &str) -> bool {
    match arboard::Clipboard::new() {
        Ok(mut cb) => cb.set_text(text).is_ok(),
        Err(_) => false,
    }
}

#[cfg(not(feature = "clipboard"))]
fn copy_to_clipboard(_text: &str) -> bool {
    false
}

/// Blocking fallback (no `event_rx`): render the final assistant text as a
/// single `AssistantMessageComponent`, mirroring the pre-streaming behavior.
/// `transformer` is the live assistant-markdown transformer (B5e); `None` is
/// the identity path. The blocking path only fires when `event_rx` is absent,
/// so it shares the same transformer the streaming path installs on its
/// components.
fn add_assistant_message_blocking(
    container: &Arc<Container>,
    text: &str,
    transformer: Option<MarkdownTransformer>,
) {
    if text.is_empty() {
        return;
    }
    let msg = Arc::new(AssistantMessageComponent::new(AssistantMessageOptions::default()));
    if let Some(t) = &transformer {
        msg.set_markdown_transformer(Some(t.clone()));
    }
    msg.update_text(text);
    container.add_child(msg);
    container.add_child(Arc::new(Spacer::new(1)));
}

// ===========================================================================
// AgentEvent drain task — the streaming core
// ===========================================================================

/// Drain `AgentEvent`s from the broadcast receiver and apply the TS
/// `handleEvent` event→UI mapping. Runs on a `tokio::spawn`'d task for the
/// lifetime of the TUI.
async fn drain_agent_events(
    mut rx: broadcast::Receiver<AgentEvent>,
    tui: Arc<TuiAltScreen>,
    state: Arc<TuiState>,
    chat: Arc<Container>,
) {
    loop {
        match rx.recv().await {
            Ok(event) => handle_agent_event(event, &tui, &state, &chat).await,
            Err(broadcast::error::RecvError::Lagged(_)) => {
                // We dropped some intermediate deltas; the next MessageUpdate/
                // MessageEnd carries a full partial snapshot so the UI re-syncs.
                continue;
            }
            Err(broadcast::error::RecvError::Closed) => break,
        }
    }
}

/// Apply a single `AgentEvent` to the UI. Mirrors the TS `handleEvent` switch
/// (`interactive-mode.ts:3068-3396`).
async fn handle_agent_event(
    event: AgentEvent,
    tui: &Arc<TuiAltScreen>,
    state: &Arc<TuiState>,
    chat: &Arc<Container>,
) {
    match event {
        AgentEvent::AgentStart => {
            state.set_status(RunStatus::Working);
            tui.request_render(false);
        }

        AgentEvent::AgentEnd { .. } => {
            // Finalize any still-streaming assistant message.
            if let Some(comp) = state.current_assistant.lock().unwrap().take() {
                comp.set_streaming(false);
            }
            state.set_status(RunStatus::Idle);
            tui.request_render(false);
        }

        AgentEvent::TurnStart => {
            // A new turn: reset the streaming-assistant guard so the next
            // MessageStart creates a fresh component.
            if let Some(comp) = state.current_assistant.lock().unwrap().take() {
                comp.set_streaming(false);
            }
        }

        AgentEvent::TurnEnd { message, tool_results } => {
            // Finalize the assistant message for this turn.
            if let Some(comp) = state.current_assistant.lock().unwrap().take() {
                if let AgentMessage::Assistant(a) = &message {
                    comp.update_blocks(&assistant_blocks(a));
                }
                comp.set_streaming(false);
            }
            // Any tool results whose components were never ended by a
            // ToolExecutionEnd get a static rendering here (best-effort). The
            // normal path removes the component via ToolExecutionEnd; this is
            // just a no-op guard so a stray TurnEnd doesn't double-finalize.
            let tools = state.tool_components.lock().unwrap();
            for tr in &tool_results {
                if tools.contains_key(&tr.tool_call_id) {
                    // Will be removed below via ToolExecutionEnd in the normal
                    // path; leave as-is if still present.
                    let _ = tr;
                }
            }
            drop(tools);
            tui.request_render(false);
        }

        AgentEvent::MessageStart { message } => match message {
            AgentMessage::Assistant(a) => {
                let comp = Arc::new(AssistantMessageComponent::new(
                    AssistantMessageOptions::default(),
                ));
                // B5e: install the live markdown transformer so the plugin's
                // `register_markdown_transformer` handlers apply from the very
                // first streamed delta. `set_streaming` before the transform
                // install is fine (transform fires on `update_blocks`, below).
                if let Some(t) = state.markdown_transformer() {
                    comp.set_markdown_transformer(Some(t));
                }
                comp.set_streaming(true);
                // Render text AND thinking blocks in order (the old path fed
                // only the concatenated text, so thinking blocks never showed).
                comp.update_blocks(&assistant_blocks(&a));
                chat.add_child(comp.clone());
                chat.add_child(Arc::new(Spacer::new(0)));
                *state.current_assistant.lock().unwrap() = Some(comp);
                tui.request_render(false);
            }
            // User / ToolResult / Custom starts are echoed at submit time or
            // via the tool-execution components; ignore here to avoid dupes.
            _ => {}
        },

        AgentEvent::MessageUpdate { message, assistant_message_event } => {
            if let AgentMessage::Assistant(a) = &message {
                let text = assistant_text(a);
                // Scan content for finalized tool calls → proactively create
                // tool components (TS shows the tool as soon as the assistant
                // emits the ToolCall; ToolExecutionStart coalesces if it
                // already exists).
                for c in &a.content {
                    if let Content::ToolCall(tc) = c {
                        let mut tools = state.tool_components.lock().unwrap();
                        if !tools.contains_key(&tc.id) {
                            let comp = Arc::new(ToolExecutionComponent::new(
                                &tc.name,
                                &tc.arguments.to_string(),
                            ));
                            comp.set_running();
                            chat.add_child(comp.clone());
                            tools.insert(tc.id.clone(), comp);
                        }
                    }
                }
                let _ = assistant_message_event; // snapshot already applied via `a`
                if let Some(comp) = state.current_assistant.lock().unwrap().as_ref() {
                    // Stream the full block list (text + thinking) each update
                    // so thinking blocks render live as they arrive.
                    comp.update_blocks(&assistant_blocks(a));
                }
                *state.last_assistant_text.lock().unwrap() = text;
                tui.request_render(false);
            }
        }

        AgentEvent::MessageEnd { message } => {
            if let AgentMessage::Assistant(a) = &message {
                let text = assistant_text(a);
                if let Some(comp) = state.current_assistant.lock().unwrap().take() {
                    comp.update_blocks(&assistant_blocks(a));
                    comp.set_streaming(false);
                }
                // Cache the finalized text for `/copy`.
                if !text.is_empty() {
                    *state.last_assistant_text.lock().unwrap() = text;
                }
                // Cache-miss notice (simplified `maybeShowCacheMissNotice`):
                // the previous turn's input established a cacheable prefix; a
                // large input this turn that read nothing from cache means the
                // prefix was re-billed. No cost display — v1 has no per-run
                // cost tracking here.
                let usage = &a.usage;
                let prev_input = *state.last_input_tokens.lock().unwrap();
                if prev_input > 0
                    && usage.input >= CACHE_MISS_MIN_INPUT_TOKENS
                    && usage.cache_read == 0
                {
                    add_note_message(
                        &state.chat_container,
                        &format!(
                            "Cache miss: {} tokens re-billed",
                            format_tokens(usage.input)
                        ),
                    );
                }
                *state.last_input_tokens.lock().unwrap() = usage.input;
            }
            tui.request_render(false);
        }

        AgentEvent::ToolExecutionStart { tool_call_id, tool_name, args } => {
            if tool_name == "bash" {
                // Bash streams into a dedicated BashExecutionComponent (command
                // header + live preview + exit/truncation status) rather than a
                // generic ToolExecutionComponent. The command comes from the
                // `command` field of the bash tool args.
                let command = args
                    .get("command")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let comp = Arc::new(BashExecutionComponent::new(command));
                chat.add_child(comp.clone());
                state
                    .bash_components
                    .lock()
                    .unwrap()
                    .insert(tool_call_id.clone(), comp);
            } else {
                let comp = {
                    let mut tools = state.tool_components.lock().unwrap();
                    if let Some(existing) = tools.get(&tool_call_id) {
                        existing.set_args(&args.to_string());
                        existing.clone()
                    } else {
                        let comp = Arc::new(ToolExecutionComponent::new(&tool_name, &args.to_string()));
                        comp.set_running();
                        chat.add_child(comp.clone());
                        tools.insert(tool_call_id.clone(), comp.clone());
                        comp
                    }
                };
                state.remember_tool(comp);
            }
            tui.request_render(false);
        }

        AgentEvent::ToolExecutionUpdate { tool_call_id, tool_name, partial_result, .. } => {
            if tool_name == "bash" {
                // Append the streamed chunk to the bash component's preview.
                let chunk = summarize_tool_result(&partial_result);
                if let Some(bash) = state.bash_components.lock().unwrap().get(&tool_call_id) {
                    bash.append_output(&chunk);
                } else {
                    // No component yet — create a running bash one so the
                    // partial shows (command unknown at Update time; leave blank).
                    let comp = Arc::new(BashExecutionComponent::new(""));
                    comp.append_output(&chunk);
                    chat.add_child(comp.clone());
                    state
                        .bash_components
                        .lock()
                        .unwrap()
                        .insert(tool_call_id.clone(), comp);
                }
            } else if let Some(comp) = state.tool_components.lock().unwrap().get(&tool_call_id) {
                let summary = summarize_tool_result(&partial_result);
                comp.set_result(&summary, false);
                apply_edit_diff(comp, &tool_name, &partial_result.details, &tui);
                state.remember_tool(comp.clone());
            } else {
                // No component yet — create a running one so the partial shows.
                let comp = Arc::new(ToolExecutionComponent::new(&tool_name, ""));
                comp.set_running();
                comp.set_result(&summarize_tool_result(&partial_result), false);
                apply_edit_diff(&comp, &tool_name, &partial_result.details, &tui);
                chat.add_child(comp.clone());
                state
                    .tool_components
                    .lock()
                    .unwrap()
                    .insert(tool_call_id.clone(), comp.clone());
                state.remember_tool(comp);
            }
            tui.request_render(false);
        }

        AgentEvent::ToolExecutionEnd { tool_call_id, tool_name, result, is_error } => {
            if tool_name == "bash" {
                let bash = state.bash_components.lock().unwrap().remove(&tool_call_id);
                if let Some(bash) = bash {
                    finalize_bash(&bash, &result, is_error);
                } else {
                    // Bash ended without a Start/Update — render a finalized
                    // component directly from the result text.
                    let command = result
                        .details
                        .get("command")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let comp = Arc::new(BashExecutionComponent::new(command));
                    comp.append_output(&summarize_tool_result(&result));
                    finalize_bash(&comp, &result, is_error);
                    chat.add_child(comp);
                }
            } else {
                let comp = state.tool_components.lock().unwrap().remove(&tool_call_id);
                if let Some(comp) = comp {
                    comp.set_result(&summarize_tool_result(&result), is_error);
                    apply_edit_diff(&comp, &tool_name, &result.details, &tui);
                } else {
                    // Tool ended without a Start/Update (e.g. a very fast tool):
                    // render a finalized component directly.
                    let comp = Arc::new(ToolExecutionComponent::new(&tool_name, ""));
                    comp.set_result(&summarize_tool_result(&result), is_error);
                    apply_edit_diff(&comp, &tool_name, &result.details, &tui);
                    chat.add_child(comp.clone());
                    state.remember_tool(comp);
                }
            }
            tui.request_render(false);
        }
    }
}

/// Extract `BashToolDetails` (`truncation`, `full_output_path`) from a bash
/// tool result and mark the component complete. Mirrors the TS bash finalize
/// path; only the fields `BashExecutionComponent` needs are read.
fn finalize_bash(comp: &Arc<BashExecutionComponent>, result: &rpi_agent::AgentToolResult, is_error: bool) {
    // The exit code isn't in details directly (TS carries it elsewhere); use
    // `is_error` as the error signal and 0/1 as a best-effort exit code.
    let exit_code = if is_error { Some(1) } else { Some(0) };
    let truncated = result
        .details
        .get("truncation")
        .and_then(|t| t.get("truncated"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let full_output_path = result
        .details
        .get("full_output_path")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let truncation = BashTruncation {
        truncated,
        full_output_path,
    };
    let cancelled = false; // cancellation surfaces via Abort/AgentEnd, not a bash detail
    comp.set_complete(exit_code, cancelled, truncation);
}

/// If `tool_name` is an editing tool (`edit`) whose `details.diff` carries a
/// display-diff string, render it with colors and attach to the component so
/// the changes show in the transcript. `write` has no diff (details: Null) and
/// stays a plain summary.
fn apply_edit_diff(
    comp: &Arc<ToolExecutionComponent>,
    tool_name: &str,
    details: &serde_json::Value,
    tui: &Arc<TuiAltScreen>,
) {
    if tool_name != "edit" {
        return;
    }
    let Some(diff_text) = details.get("diff").and_then(|v| v.as_str()) else {
        return;
    };
    if diff_text.is_empty() {
        return;
    }
    let width = tui.width();
    let lines = render_diff(diff_text, width);
    comp.set_diff(lines);
}

/// Render an `AgentToolResult` as a single-line summary for the
/// `ToolExecutionComponent` (joins text blocks; truncates for compactness).
fn summarize_tool_result(result: &rpi_agent::AgentToolResult) -> String {
    use rpi_agent::TextContentOrImage;
    let mut parts: Vec<String> = Vec::new();
    for c in &result.content {
        if let TextContentOrImage::Text(t) = c {
            parts.push(t.text.clone());
        }
    }
    let joined = parts.join("\n");
    // Keep the tool line compact: collapse to a single line, trim length.
    let one_line: String = joined.lines().collect::<Vec<_>>().join("");
    if one_line.chars().count() > 200 {
        let truncated: String = one_line.chars().take(200).collect();
        format!("{truncated}")
    } else {
        one_line
    }
}

// ===========================================================================
// Selectors — editor-container swap (TS showSelector pattern)
// ===========================================================================

/// Swap the `editor_container`'s child (the editor) for a `SelectList`,
/// hiding the editor while the selector is open. Records the selector in
/// `state.active_selector` so the key loop routes to it.
fn open_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    list: Arc<SelectList>,
    kind: SelectorKind,
) {
    // Unfocus the editor so its cursor marker doesn't render behind the list.
    editor.set_focused(false);
    // Swap: clear the container and add just the list.
    editor_container.clear();
    editor_container.add_child(list.clone());
    *state.active_selector.lock().unwrap() = Some((list, kind));
    tui.request_render(false);
}

/// Restore the editor into the `editor_container` and clear the active
/// selector. Called by selector `on_cancel` and the Esc handler.
fn close_selector(state: &Arc<TuiState>, editor_container: &Arc<Container>, editor: &Arc<Editor>, tui: &Arc<TuiAltScreen>) {
    editor_container.clear();
    editor_container.add_child(editor.clone());
    editor.set_focused(true);
    *state.active_selector.lock().unwrap() = None;
    tui.request_render(false);
}

/// Build + open the `/model` selector. Items are the resolved catalog (display
/// label = model name; description = id), with the current model marked.
/// Selecting applies the model **live** via `lane.set_model` (takes effect on
/// the next user message — the in-flight run's config is already snapshotted),
/// updates the footer, and notes the next-prompt effect.
fn open_model_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    catalog: &[rpi_ai::Model],
    lane: &Arc<dyn AgentLane>,
    lane_model_id: &str,
    chat: &Arc<Container>,
) {
    let mut items: Vec<SelectItem> = Vec::new();
    for m in catalog {
        let label = if m.name.is_empty() { short_model_name(&m.id) } else { m.name.clone() };
        let marker = if m.id.eq_ignore_ascii_case(lane_model_id) { " (current)" } else { "" };
        items.push(
            SelectItem::new(&m.id, &label)
                .with_description(&format!("{id}{marker}", id = m.id)),
        );
    }
    if items.is_empty() {
        add_note_message(
            chat,
            "No models in the catalog. Use --model at startup to select one.",
        );
        tui.request_render(false);
        return;
    }
    let list = Arc::new(SelectList::new(items, 10));

    // Capture the catalog + lane so the on_select closure can resolve the
    // chosen Model and apply it. `on_select` fires on the blocking key thread,
    // so the async `set_model` runs on a spawned task (matches Ctrl+M).
    let catalog_arc = catalog.to_vec();
    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    let lane_sel = lane.clone();
    list.on_select(Arc::new(move |item| {
        let Some(model) = catalog_arc.iter().find(|m| m.id == item.value).cloned() else {
            add_note_message(&chat_sel, &format!("Model {} not found in catalog.", item.label));
            close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
            return;
        };
        state_sel.set_current_model(&model);
        let lane = lane_sel.clone();
        tokio::spawn(async move {
            let _ = lane.set_model(model).await;
        });
        add_note_message(
            &chat_sel,
            &format!(
                "Model set to {} — applies to the next message.",
                short_model_name(&item.value)
            ),
        );
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Model);
}

/// Cycle to the next catalog entry after `current_id`, wrapping to the first.
/// Returns `None` only when the catalog is empty or the current id isn't
/// found (in which case the first entry is returned — a no-op if it IS the
/// current). Used by the Ctrl+M model-cycle hotkey.
fn cycle_next_model(catalog: &[rpi_ai::Model], current_id: &str) -> Option<rpi_ai::Model> {
    if catalog.is_empty() {
        return None;
    }
    let idx = catalog
        .iter()
        .position(|m| m.id.eq_ignore_ascii_case(current_id));
    match idx {
        Some(i) => {
            let next = (i + 1) % catalog.len();
            Some(catalog[next].clone())
        }
        None => Some(catalog[0].clone()),
    }
}

/// Build + open the `/session` selector. Lists JSONL session files under the
/// default session dir (`<cwd>/.pi/sessions`). Selecting reports "restore not
/// implemented in v1" (existing constraint) but shows the list for
/// discoverability.
fn open_session_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    cwd: &std::path::Path,
    tx: &mpsc::Sender<TuiMessage>,
) {
    let dir = crate::session::default_session_dir(cwd);
    let mut items: Vec<SelectItem> = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("(unnamed)")
                .to_string();
            let display = path
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or(&stem)
                .to_string();
            items.push(SelectItem::new(&stem, &display));
        }
    }
    if items.is_empty() {
        add_note_message(
            &state.chat_container,
            "No saved sessions found. Sessions are created automatically in interactive mode.",
        );
        tui.request_render(false);
        return;
    }
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let tx_sel = tx.clone();
    list.on_select(Arc::new(move |item| {
        // Close the selector first, then ask the async loop to hot-switch:
        // opening the session file + swapping the harness backing is async
        // (repo list/open) and must not run on the blocking key thread.
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
        let _ = tx_sel.send(TuiMessage::SwitchSession(item.value.clone()));
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Session);
}

/// Build + open the `/theme` selector. Presets [dark, light, monochrome];
/// selecting applies it live via the owned `ThemeManager` + re-renders.
fn open_theme_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
) {
    let items = vec![
        SelectItem::new("dark", "Dark").with_description("Default dark theme"),
        SelectItem::new("light", "Light").with_description("Light background"),
        SelectItem::new("monochrome", "Monochrome").with_description("No color accents"),
    ];
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = state.chat_container.clone();
    list.on_select(Arc::new(move |item| {
        let preset = match item.value.as_str() {
            "light" => ThemePreset::Light,
            "monochrome" => ThemePreset::Monochrome,
            _ => ThemePreset::Dark,
        };
        state_sel.theme_manager.apply_preset(preset);
        // A quick accent note so the user sees the change registered even if
        // the terminal's own colors mask the preset difference.
        add_note_message(&chat_sel, &format!("Theme set to {}.", item.label));
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
        tui_sel.render_now(true);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Theme);
}

// ===========================================================================
// Feasible selectors — /thinking, /tools, /images
// ===========================================================================

/// One-line descriptions for each thinking level, ported from
/// thinking-selector.ts (the TS `getThinkingLevelDescription` table).
fn thinking_level_description(level: rpi_ai::types::ThinkingLevel) -> &'static str {
    use rpi_ai::types::ThinkingLevel::*;
    match level {
        Off => "Off — No reasoning",
        Minimal => "Minimal — Brief reasoning (~1k tokens)",
        Low => "Low — Light reasoning (~1k tokens)",
        Medium => "Medium — Moderate reasoning (~80% of max)",
        High => "High — Extensive reasoning (~95% of max)",
        Xhigh => "Xhigh — Near-maximal reasoning",
        Max => "Max — Maximum reasoning",
    }
}

/// The lowercase serialized name of a [`ThinkingLevel`] (matches its
/// `#[serde(rename_all = "lowercase")]` form): "off", "minimal", … "max".
fn thinking_level_name(level: rpi_ai::types::ThinkingLevel) -> &'static str {
    use rpi_ai::types::ThinkingLevel::*;
    match level {
        Off => "off",
        Minimal => "minimal",
        Low => "low",
        Medium => "medium",
        High => "high",
        Xhigh => "xhigh",
        Max => "max",
    }
}

/// Parse a thinking-level name back to the enum (case-insensitive). Returns
/// `None` for an unknown name; used by the `/thinking` selector callback.
fn thinking_level_from_name(name: &str) -> Option<rpi_ai::types::ThinkingLevel> {
    use rpi_ai::types::ThinkingLevel::*;
    match name.to_ascii_lowercase().as_str() {
        "off" => Some(Off),
        "minimal" => Some(Minimal),
        "low" => Some(Low),
        "medium" => Some(Medium),
        "high" => Some(High),
        "xhigh" => Some(Xhigh),
        "max" => Some(Max),
        _ => None,
    }
}

/// Build + open the `/thinking` selector. Items are the levels the current
/// model supports (`Model::supported_thinking_levels`), each with a
/// description; the current level (read beforehand via `lane.get_thinking_level`)
/// is preselected. Selecting applies it live via `lane.set_thinking_level`.
///
/// `on_select` fires on the blocking key thread, so it can't await
/// `lane.get_thinking_level()` to know the current level — the opener resolves
/// it first (best-effort) and preselects; the toggle on_select just applies
/// whatever was picked.
fn open_thinking_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    lane: &Arc<dyn AgentLane>,
    catalog: &[rpi_ai::Model],
    lane_model_id: &str,
    chat: &Arc<Container>,
) {
    // Find the current model in the catalog to read its supported levels. If
    // absent, fall back to all levels so the selector still opens.
    let model = catalog
        .iter()
        .find(|m| m.id.eq_ignore_ascii_case(lane_model_id));
    let levels: Vec<rpi_ai::types::ThinkingLevel> = model
        .map(|m| m.supported_thinking_levels())
        .unwrap_or_else(|| {
            use rpi_ai::types::ThinkingLevel::*;
            vec![Off, Minimal, Low, Medium, High]
        });
    let mut items: Vec<SelectItem> = Vec::new();
    for lvl in &levels {
        let name = thinking_level_name(*lvl);
        items.push(
            SelectItem::new(name, name)
                .with_description(thinking_level_description(*lvl)),
        );
    }
    if items.is_empty() {
        add_note_message(chat, "This model has no supported thinking levels.");
        tui.request_render(false);
        return;
    }
    let list = Arc::new(SelectList::new(items, 10));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    let lane_sel = lane.clone();
    list.on_select(Arc::new(move |item| {
        let Some(level) = thinking_level_from_name(&item.value) else {
            add_note_message(&chat_sel, &format!("Unknown thinking level: {}.", item.label));
            close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
            return;
        };
        let lane = lane_sel.clone();
        let footer_sel = state_sel.footer.clone();
        tokio::spawn(async move {
            let _ = lane.set_thinking_level(level).await;
        });
        // Reflect the chosen level in the footer's model suffix (pi parity:
        // `model • thinking off` / `model • medium`). The shown text for the
        // Off level is "off", matching the TS `thinkingLevel === "off"` branch.
        footer_sel.set_thinking_level(Some(thinking_level_name(level)));
        add_note_message(&chat_sel, &format!("Thinking set to {}.", item.label));
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Thinking);
}

/// Build + open the `/tools` selector. Lists the 7 builtin tool names; each
/// visit reads the live active set via `lane.get_active_tools()` (best-effort,
/// resolved synchronously by the opener using `tokio::runtime::Handle` block_on
/// — the blocking key thread can't await) and selecting a tool **toggles** it
/// on/off via `lane.set_active_tools`. Active tools are marked `(on)`.
fn open_tools_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    lane: &Arc<dyn AgentLane>,
    chat: &Arc<Container>,
) {
    // Best-effort read of the current active set. The opener runs on the async
    // runtime (it's called from the main loop's channel dispatch or the submit
    // closure that lives on the blocking thread — but `handle.block_on` is safe
    // because `get_active_tools` is std-Mutex-backed and finishes quickly).
    let active = match tokio::runtime::Handle::try_current() {
        Ok(h) => h.block_on(async { lane.get_active_tools().await }).unwrap_or_default(),
        Err(_) => Vec::new(),
    };
    let mut items: Vec<SelectItem> = Vec::new();
    for name in crate::session::BUILTIN_TOOL_NAMES {
        let on = active.iter().any(|a| a == name);
        let label = if on { format!("{name} (on)") } else { (*name).to_string() };
        items.push(SelectItem::new(name, &label).with_description("Toggle tool on/off"));
    }
    let list = Arc::new(SelectList::new(items, 10));

    // Capture the active set so on_select can toggle without re-reading.
    let active_captured = active.clone();
    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    let lane_sel = lane.clone();
    list.on_select(Arc::new(move |item| {
        let mut next = active_captured.clone();
        if let Some(pos) = next.iter().position(|a| a == &item.value) {
            next.remove(pos);
        } else {
            next.push(item.value.clone());
        }
        let on = next.iter().any(|a| a == &item.value);
        let lane = lane_sel.clone();
        let next_clone = next.clone();
        tokio::spawn(async move {
            let _ = lane.set_active_tools(next_clone).await;
        });
        let list_str = if next.is_empty() {
            "(none)".to_string()
        } else {
            next.join(", ")
        };
        add_note_message(
            &chat_sel,
            &format!(
                "{} {} — active tools: {}",
                item.value,
                if on { "enabled" } else { "disabled" },
                list_str
            ),
        );
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Tools);
}

/// Build + open the `/images` selector (Yes/No). Stores the choice in
/// `state.show_images` and notes it. Image wiring is minimal this pass — the
/// flag is consulted where images would be shown and echoed back here.
fn open_images_selector(
    state: &Arc<TuiState>,
    editor_container: &Arc<Container>,
    editor: &Arc<Editor>,
    tui: &Arc<TuiAltScreen>,
    chat: &Arc<Container>,
) {
    let current = *state.show_images.lock().unwrap();
    let items = vec![
        SelectItem::new("yes", "Yes")
            .with_description(if current { "Inline images (current)" } else { "Inline images" }),
        SelectItem::new("no", "No")
            .with_description(if current { "Placeholder only" } else { "Placeholder only (current)" }),
    ];
    let list = Arc::new(SelectList::new(items, 5));

    let state_sel = state.clone();
    let ec_sel = editor_container.clone();
    let editor_sel = editor.clone();
    let tui_sel = tui.clone();
    let chat_sel = chat.clone();
    list.on_select(Arc::new(move |item| {
        let on = item.value == "yes";
        *state_sel.show_images.lock().unwrap() = on;
        add_note_message(
            &chat_sel,
            &format!("Inline images {}.", if on { "enabled" } else { "disabled" }),
        );
        close_selector(&state_sel, &ec_sel, &editor_sel, &tui_sel);
    }));
    let state_cancel = state.clone();
    let ec_cancel = editor_container.clone();
    let editor_cancel = editor.clone();
    let tui_cancel = tui.clone();
    list.on_cancel(Arc::new(move || {
        close_selector(&state_cancel, &ec_cancel, &editor_cancel, &tui_cancel);
    }));

    open_selector(state, editor_container, editor, tui, list, SelectorKind::Images);
}

// ===========================================================================
// Autocomplete
// ===========================================================================

/// Refresh the autocomplete suggestion list from the current editor text +
/// cursor. Renders the suggestions into `autocomplete_container` (above the
/// editor) or clears it when there are none.
fn refresh_autocomplete(state: &Arc<TuiState>, editor: &Arc<Editor>) {
    let text = editor.get_text();
    let (_row, col) = editor.cursor_position();
    // The editor's `cursor_col` is a byte offset into the current line; for
    // single-line input (the common case) that equals the byte offset into
    // `get_text()`, which is exactly what the autocomplete providers expect to
    // slice on. Clamp to the text length so a stale/multi-line col can't
    // overshoot. Providers snap to a char boundary internally as a safety net
    // (`autocomplete::snap_cursor`), so a byte col landing mid-character never
    // panics.
    let cursor = col.min(text.len());
    let suggestions = state.autocomplete.get_suggestions(&text, cursor);
    render_autocomplete(state, suggestions);
}

/// Render (or clear) the autocomplete suggestion list into the container.
fn render_autocomplete(state: &Arc<TuiState>, suggestions: Option<AutocompleteSuggestions>) {
    state.autocomplete_container.clear();
    let Some(sugg) = suggestions else {
        return;
    };
    if sugg.items.is_empty() {
        return;
    }
    // Build a compact list: top item marked with `→`, rest with `  `.
    // Cap at 5 lines so the dock doesn't swallow the transcript.
    let accent = state.theme_manager.get().colors.accent;
    let muted = state.theme_manager.get().colors.muted;
    for (i, item) in sugg.items.iter().take(5).enumerate() {
        let prefix = if i == 0 { "" } else { "  " };
        let label = item.display_text();
        let line = if i == 0 {
            format!("{prefix}{} {}", accent.fg(label), muted.fg(item.description.as_deref().unwrap_or("")))
        } else {
            format!("{prefix}{} {}", muted.fg(label), muted.fg(item.description.as_deref().unwrap_or("")))
        };
        state
            .autocomplete_container
            .add_child(Arc::new(Text::new(line, 1, 0)));
    }
}

/// Accept the top autocomplete suggestion: replace `text[start..end]` with the
/// suggestion text, reposition the caret, and clear the suggestion list.
/// Returns `true` if a suggestion was accepted.
fn accept_top_suggestion(state: &Arc<TuiState>, editor: &Arc<Editor>) -> bool {
    let text = editor.get_text();
    let (_row, col) = editor.cursor_position();
    let cursor = col.min(text.len());
    let Some(sugg) = state.autocomplete.get_suggestions(&text, cursor) else {
        return false;
    };
    let Some(top) = sugg.items.first() else {
        return false;
    };
    // Replace the [start, end) span with the suggestion text. `start`/`end`
    // are byte offsets emitted by the providers on char boundaries, so the
    // `text[..start]` / `text[end..]` slices are sound for multibyte input.
    let start = sugg.start.min(text.len());
    let end = sugg.end.min(text.len());
    let mut replaced = String::with_capacity(text.len() + top.text.len());
    replaced.push_str(&text[..start]);
    replaced.push_str(&top.text);
    // Keep the text AFTER the replaced span (mid-line completion: replacing
    // `[start, end)` must not drop the rest of the line).
    replaced.push_str(&text[end..]);
    if top.insert_space && !replaced.ends_with('/') {
        replaced.push(' ');
    }
    // New caret position: after the inserted text (byte offset; the editor
    // snaps `set_cursor` to a char boundary as a safety net).
    let new_cursor = replaced.len().min(
        start + top.text.len()
            + if top.insert_space && !top.text.ends_with('/') {
                1
            } else {
                0
            },
    );
    editor.set_text(&replaced);
    editor.set_cursor(0, new_cursor);
    state.autocomplete_container.clear();
    true
}

// ===========================================================================
// Transcript message helpers
// ===========================================================================

/// Add the welcome header to the chat container.
fn add_welcome_message(container: &Arc<Container>) {
    container.add_child(Arc::new(Text::new("rpi interactive TUI", 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
    container.add_child(Arc::new(Text::new(
        "Type your message and press Enter to send.",
        1, 0,
    )));
    container.add_child(Arc::new(Text::new(
        "Ctrl+C: Abort/Exit | Esc: Abort | Enter: Send | Shift+Enter: New line | Tab: Complete | Ctrl+L: Model | Ctrl+M: Cycle | Ctrl+T: Expand tool | /help",
        1, 0,
    )));
    container.add_child(Arc::new(Spacer::new(1)));
}

/// Add the `/help` command listing to the chat container.
fn add_help_message(container: &Arc<Container>) {
    container.add_child(Arc::new(Text::new("📚 Available Commands:", 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
    container.add_child(Arc::new(Text::new("  /help, /?       — Show this help message", 1, 0)));
    container.add_child(Arc::new(Text::new("  /clear, /new    — Clear the conversation", 1, 0)));
    container.add_child(Arc::new(Text::new("  /exit, /quit, /q — Exit the application", 1, 0)));
    container.add_child(Arc::new(Text::new("  /version, /v    — Show version information", 1, 0)));
    container.add_child(Arc::new(Text::new("  /model, /m      — Choose a model (live switch)", 1, 0)));
    container.add_child(Arc::new(Text::new("  /thinking, /think — Set reasoning depth (selector)", 1, 0)));
    container.add_child(Arc::new(Text::new("  /tools          — Toggle built-in tools on/off", 1, 0)));
    container.add_child(Arc::new(Text::new("  /images         — Toggle inline image rendering", 1, 0)));
    container.add_child(Arc::new(Text::new("  /session        — List saved sessions", 1, 0)));
    container.add_child(Arc::new(Text::new("  /theme          — Choose a theme (selector)", 1, 0)));
    container.add_child(Arc::new(Text::new("  /compact        — Compact the conversation", 1, 0)));
    container.add_child(Arc::new(Text::new("  /copy           — Copy last reply to clipboard", 1, 0)));
    container.add_child(Arc::new(Text::new("  /hotkeys        — Show keyboard shortcuts", 1, 0)));
    container.add_child(Arc::new(Text::new("  /armin          — 🐾 Easter egg", 1, 0)));
    container.add_child(Arc::new(Text::new("  /earendil       — Earendil announcement", 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
}

/// Add the `/version` block to the chat container.
fn add_version_message(container: &Arc<Container>) {
    container.add_child(Arc::new(Text::new("📦 Version Information:", 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
    container.add_child(Arc::new(Text::new("  rpi-cli v0.1.2", 1, 0)));
    container.add_child(Arc::new(Text::new(
        "  Rust implementation of pi coding agent TUI",
        1, 0,
    )));
    container.add_child(Arc::new(Spacer::new(1)));
}

/// Add the `/hotkeys` block to the chat container.
fn add_hotkeys_message(container: &Arc<Container>) {
    container.add_child(Arc::new(Text::new("⌨️  Keyboard Shortcuts:", 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
    container.add_child(Arc::new(Text::new("  Enter         — Send message", 1, 0)));
    container.add_child(Arc::new(Text::new("  Shift+Enter   — New line", 1, 0)));
    container.add_child(Arc::new(Text::new("  Tab           — Accept autocomplete suggestion", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+A / Ctrl+E — Line start / end", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+K / Ctrl+U — Kill to end / start of line (Ctrl+Y yanks)", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+- / Ctrl+R — Undo / redo", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+Y / Alt+Y — Yank / yank-pop", 1, 0)));
    container.add_child(Arc::new(Text::new("  Alt+Backspace — Kill previous word", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+C        — Abort a run, or exit when idle", 1, 0)));
    container.add_child(Arc::new(Text::new("  Esc           — Abort a running prompt", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+L        — Open model selector", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+M        — Cycle to the next model (live)", 1, 0)));
    container.add_child(Arc::new(Text::new("  Ctrl+T        — Expand/collapse last tool result", 1, 0)));
    container.add_child(Arc::new(Text::new("  PageUp/Down   — Scroll transcript", 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
}

/// Add a user message echo to the chat container — a bordered `UserMessageComponent`
/// (surface-colored box with OSC133 prompt-boundary markers) replacing the old
/// plain `> text` echo.
fn add_user_message(container: &Arc<Container>, text: &str) {
    container.add_child(Arc::new(UserMessageComponent::new(text.to_string())));
    container.add_child(Arc::new(Spacer::new(0)));
}

/// Add an error message to the chat container.
fn add_error_message(container: &Arc<Container>, text: &str) {
    container.add_child(Arc::new(Text::new(format!("{text}"), 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
}

/// Add a neutral note (e.g. unsupported-command message) to the chat container.
fn add_note_message(container: &Arc<Container>, text: &str) {
    container.add_child(Arc::new(Text::new(format!("ℹ️  {text}"), 1, 0)));
    container.add_child(Arc::new(Spacer::new(1)));
}

/// Render the `/context` panel: a transcript message listing the discovered
/// context files, skills, and prompt templates loaded for this session
/// (Part A resource discovery). Reads the harness resources snapshot captured
/// at TUI startup (the blocking submit handler can't `await get_resources()`.
///
/// Mirrors pi's context-panel intent (pi surfaces loaded resources on startup +
/// via `/reload`); here it's a transcript note rather than an overlay since the
/// resource set is session-static between `/reload`s (deferred).
fn show_context_panel(
    chat: &Arc<Container>,
    resources: &Arc<rpi_harness::types::AgentHarnessResources>,
) {
    let skills = resources.skills.as_deref().unwrap_or(&[]);
    let templates = resources.prompt_templates.as_deref().unwrap_or(&[]);
    let mut lines: Vec<String> = Vec::new();
    lines.push("📂 Discovered resources for this session:".into());

    if skills.is_empty() {
        lines.push("  Skills: (none discovered — create .pi/skills/ or ~/.rpi/agent/skills/)".into());
    } else {
        lines.push(format!("  Skills ({}):", skills.len()));
        for s in skills {
            let marker = if s.disable_model_invocation == Some(true) {
                " [hidden]"
            } else {
                ""
            };
            let desc: String = s.description.chars().take(72).collect();
            lines.push(format!("{}{marker}{desc}", s.name));
        }
    }

    if templates.is_empty() {
        lines.push("  Prompt templates: (none — create .pi/prompts/ or ~/.rpi/agent/prompts/)".into());
    } else {
        lines.push(format!("  Prompt templates ({}):", templates.len()));
        for t in templates {
            let desc = t
                .description
                .as_deref()
                .unwrap_or("(no description)")
                .chars()
                .take(72)
                .collect::<String>();
            lines.push(format!("    • /{}{desc}", t.name));
        }
    }
    lines.push("  Context files (AGENTS.md/CLAUDE.md) are injected from the ancestor walk;".into());
    lines.push("  SYSTEM.md / APPEND_SYSTEM.md feed the base + append prompt sections.".into());
    lines.push("  Use --no-skills/-ns, --no-prompt-templates/-np, --no-context-files/-nc to suppress.".into());
    let body = lines.join("\n");
    container_note_block(chat, &body);
}

/// Append a multi-line neutral note (header line + body) to the chat container.
fn container_note_block(container: &Arc<Container>, body: &str) {
    for line in body.lines() {
        container.add_child(Arc::new(Text::new(line.to_string(), 1, 0)));
    }
    container.add_child(Arc::new(Spacer::new(1)));
}

// ===========================================================================
// TUI support + entry detection
// ===========================================================================

/// Check if the terminal supports TUI mode.
pub fn is_tui_supported() -> bool {
    std::io::stdout().is_terminal()
}

// Keep the `Color` import used (theme accent rendering in autocomplete).
#[allow(unused_imports)]
use rpi_tui::Color as _Color;

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

    #[test]
    fn test_layout_renders_welcome_message() {
        let chat = Arc::new(Container::new());
        add_welcome_message(&chat);

        let scroll = Arc::new(ScrollView::new(
            chat.clone(),
            ScrollViewOptions {
                follow: FollowMode::End,
                primary: true,
                ..Default::default()
            },
        ));

        let editor = Arc::new(Editor::new(
            EditorOptions {
                padding_x: 1,
                ..Default::default()
            },
            EditorStyle::default(),
            Arc::new(rpi_tui::Keybindings::new()),
        ));
        let dock = Arc::new(Container::new());
        dock.add_child(editor);

        let footer = Arc::new(FooterComponent::new());

        let root = VStack::from_children(vec![
            StackChild::Entry(StackEntry::new(scroll.clone()).grow(1).min_size(1)),
            StackChild::Entry(StackEntry::new(dock)),
            StackChild::Entry(StackEntry::new(footer)),
        ]);

        let frame = rpi_tui::render_layout_frame(Arc::new(root), 80, 24);

        let all: String = frame.lines.join("\n");
        assert!(all.contains("rpi interactive"), "Welcome message not found. Rendered: {}", all);
        assert!(all.contains("Type your message"), "Help text not found. Rendered: {}", all);
    }

    #[test]
    fn test_chat_container_has_welcome_content() {
        let chat = Arc::new(Container::new());
        add_welcome_message(&chat);

        let lines = chat.render(80);
        let all: String = lines.join("\n");
        assert!(all.contains("rpi interactive"), "Welcome message not in chat container: {:?}", lines);
    }

    /// Reproduction for "Tab 补全了但显示没刷新": after `accept_top_suggestion`
    /// replaces the editor text, the NEXT rendered frame must show the
    /// completed text (" /model " with the caret after it), not the old
    /// prefix. Mirrors the real dock layout (autocomplete_container above the
    /// bordered editor) and drives the same accept path the Tab handler uses.
    #[test]
    fn tab_accept_suggestion_reflects_in_next_render() {
        use rpi_tui::render_layout_frame;

        let editor = Arc::new(Editor::new(
            EditorOptions { padding_x: 1, ..Default::default() },
            EditorStyle::default(),
            Arc::new(rpi_tui::Keybindings::new()),
        ));
        editor.set_focused(true);
        let editor_container = Arc::new(Container::new());
        editor_container.add_child(editor.clone());
        let autocomplete_container = Arc::new(Container::new());
        let footer = Arc::new(rpi_tui::Text::new("FOOTER", 0, 0));
        let dock = Arc::new(VStack::from_children(vec![
            StackChild::Entry(StackEntry::new(autocomplete_container.clone())),
            StackChild::Entry(StackEntry::new(editor_container.clone()).shrink(0).min_size(3)),
            StackChild::Entry(StackEntry::new(footer)),
        ]));

        // Simulate the user typing "/mo" (the popup shows suggestions).
        let mut manager = AutocompleteManager::new();
        let mut combined = CombinedAutocompleteProvider::new();
        combined.add_provider(Arc::new(SlashCommandAutocompleteProvider::with_default_commands()));
        combined.add_provider(Arc::new(FilePathAutocompleteProvider::new()));
        manager.set_provider(Arc::new(combined));
        // Simulate typing "/mo" via the real insert path (advances the caret
        // by char length, like `handle_key` does).
        editor.insert("/mo");
        assert_eq!(editor.cursor_position(), (0, 3));

        let frame_before = render_layout_frame(dock.clone(), 80, 10);
        assert!(
            frame_before.lines.iter().any(|l| l.contains("/mo")),
            "precondition: editor shows the typed prefix. Frame rows:\n{}",
            frame_before.lines.iter().map(|l| format!("  [{l}]")).collect::<Vec<_>>().join("\n")
        );

        // Tab: accept the top suggestion (the same code path as the key loop).
        let text = editor.get_text();
        let (_row, col) = editor.cursor_position();
        let cursor = col.min(text.len());
        let sugg = manager
            .get_suggestions(&text, cursor)
            .expect("slash suggestions for /mo");
        let top = sugg.items.first().expect("at least one suggestion");
        let start = sugg.start.min(text.len());
        let end = sugg.end.min(text.len());
        let mut replaced = String::new();
        replaced.push_str(&text[..start]);
        replaced.push_str(&top.text);
        replaced.push_str(&text[end..]);
        if top.insert_space && !replaced.ends_with('/') {
            replaced.push(' ');
        }
        editor.set_text(&replaced);
        editor.set_cursor(0, replaced.len().min(start + top.text.len()));
        autocomplete_container.clear();
        assert_eq!(editor.get_text(), "/model");

        // The next render MUST display the completed text.
        let frame_after = render_layout_frame(dock, 80, 10);
        let all: String = frame_after.lines.join("\n");
        assert!(
            all.contains("/model"),
            "completed text missing from next render. Got:\n{all}"
        );
        // The caret must sit AFTER the completed command (the snap_boundary
        // regression put it one char early: "/mode|l" with the final char
        // dangling past the caret).
        let editor_line = frame_after
            .lines
            .iter()
            .find(|l| l.contains("/model"))
            .expect("editor row with completed text");
        assert!(
            editor_line.contains(&format!("/model{}", rpi_tui::CURSOR_MARKER)),
            "caret must follow the full completed text. Got: {editor_line:?}"
        );
    }

    #[test]
    fn test_slash_command_dispatch() {
        // The registry is the single source of truth for dispatch: `find(token)`
        // returns the command (by name or alias) whose `name()` is the canonical
        // form, or `None` for an unknown token. This replaces the old enum-based
        // `handle_slash_command` assertions with equivalent registry lookups.
        let registry = build_builtin_registry();

        // Helper: a token resolves to the command with this canonical name.
        let resolves_to = |token: &str, canonical: &str| {
            let found = registry.find(token).expect("{token} should resolve");
            assert_eq!(
                found.name(),
                canonical,
                "{token} resolved to {} (expected {canonical})",
                found.name()
            );
        };

        resolves_to("/help", "/help");
        resolves_to("/?", "/help"); // alias → canonical
        resolves_to("/clear", "/clear");
        resolves_to("/new", "/clear"); // alias
        resolves_to("/q", "/exit"); // alias
        resolves_to("/quit", "/exit"); // alias
        resolves_to("/version", "/version");
        resolves_to("/v", "/version"); // alias
        resolves_to("/hotkeys", "/hotkeys");
        resolves_to("/model", "/model");
        resolves_to("/m", "/model"); // alias
        resolves_to("/theme", "/theme");
        resolves_to("/session", "/session");
        resolves_to("/resume", "/session"); // alias
        resolves_to("/compact", "/compact");
        resolves_to("/copy", "/copy");
        resolves_to("/thinking", "/thinking");
        resolves_to("/think", "/thinking"); // alias
        resolves_to("/tools", "/tools");
        resolves_to("/images", "/images");
        resolves_to("/armin", "/armin");
        resolves_to("/earendil", "/earendil");
        resolves_to("/context", "/context");
        // Out-of-v1-scope commands resolve to their own UnsupportedCommand entry.
        resolves_to("/settings", "/settings");
        resolves_to("/name", "/name");
        resolves_to("/export", "/export");

        // Unknown token → not found.
        assert!(registry.find("/nope").is_none(), "/nope should be unknown");
    }

    #[test]

    fn test_registry_visible_entries_cover_dispatch() {
        // The autocomplete list is derived from the registry, so every visible
        // command the dispatcher recognizes must appear in it — by construction,
        // but this guards against a future command being registered with
        // `visible()` / a non-empty description that the builder drops.
        let registry = build_builtin_registry();
        let names: Vec<String> = registry
            .visible_entries()
            .iter()
            .map(|c| c.name.clone())
            .collect();
        for recognized in [
            "/help", "/clear", "/new", "/exit", "/quit", "/version", "/model", "/session", "/theme",
            "/compact", "/copy", "/hotkeys", "/tools", "/images", "/thinking", "/armin",
            "/earendil",
        ] {
            assert!(
                names.contains(&recognized.to_string()),
                "{recognized} missing from autocomplete list"
            );
        }
        // Hidden commands stay off the list.
        for hidden in ["/context", "/q", "/m", "/v", "/think", "/resume", "/?"] {
            assert!(
                !names.contains(&hidden.to_string()),
                "{hidden} should be hidden from autocomplete"
            );
        }
    }

    #[test]
    fn test_agent_event_mapping_creates_assistant_and_tool() {
        // Synthetic AgentEvent sequence → UI mutations, exercised against the
        // real drain handler with a no-op TUI stand-in.
        use rpi_ai::types::{StopReason, TextContent, TextContentType, ThinkingContent, ThinkingContentType, ToolCall, ToolCallType, Usage};

        let state = Arc::new(TuiState {
            current_assistant: std::sync::Mutex::new(None),
            tool_components: std::sync::Mutex::new(HashMap::new()),
            bash_components: std::sync::Mutex::new(HashMap::new()),
            last_tool_comp: std::sync::Mutex::new(None),
            status: std::sync::Mutex::new(RunStatus::Idle),
            footer: Arc::new(FooterComponent::new()),
            status_container: Arc::new(Container::new()),
            chat_container: Arc::new(Container::new()),
            loader: Arc::new(Loader::new()),
            last_assistant_text: std::sync::Mutex::new(String::new()),
            active_selector: std::sync::Mutex::new(None),
            autocomplete: AutocompleteManager::new(),
            autocomplete_container: Arc::new(Container::new()),
            theme_manager: Arc::new(ThemeManager::new()),
            tui: None,
            current_model_id: std::sync::Mutex::new(String::new()),
            show_images: std::sync::Mutex::new(true),
            history: std::sync::Mutex::new(Vec::new()),
            history_index: std::sync::Mutex::new(-1),
            history_draft: std::sync::Mutex::new(None),
        last_input_tokens: std::sync::Mutex::new(0),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: std::sync::Mutex::new(None),
        });

        // The drain handler takes `Arc<TuiAltScreen>`, which needs a real
        // terminal; instead, exercise the *mutation* half directly against a
        // captured chat container via a synthetic message-start event's data.
        let assistant = AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![
                Content::Thinking(ThinkingContent {
                    kind: ThinkingContentType,
                    thinking: "Reasoning about the reply.".into(),
                    thinking_signature: None,
                    redacted: false,
                }),
                Content::Text(TextContent {
                    kind: TextContentType,
                    text: "Hello.".into(),
                    text_signature: None,
                }),
                Content::ToolCall(ToolCall {
                    kind: ToolCallType,
                    id: "tc1".into(),
                    name: "bash".into(),
                    arguments: serde_json::json!({"command": "echo hi"}),
                    thought_signature: None,
                    namespace: None,
                }),
            ],
            api: rpi_ai::Api::AnthropicMessages,
            provider: "anthropic".into(),
            model: "claude-sonnet-5".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: StopReason::Stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        };

        // Manually apply the MessageStart assistant branch logic (mirrors the
        // drain handler, without needing a TuiAltScreen).
        let comp = Arc::new(AssistantMessageComponent::new(AssistantMessageOptions::default()));
        comp.set_streaming(true);
        comp.update_blocks(&assistant_blocks(&assistant));
        let chat = Arc::new(Container::new());
        chat.add_child(comp.clone());
        *state.current_assistant.lock().unwrap() = Some(comp);

        // Manually apply the MessageUpdate tool-call scan (mirrors drain).
        for c in &assistant.content {
            if let Content::ToolCall(tc) = c {
                let mut tools = state.tool_components.lock().unwrap();
                if !tools.contains_key(&tc.id) {
                    let tc_comp = Arc::new(ToolExecutionComponent::new(
                        &tc.name,
                        &tc.arguments.to_string(),
                    ));
                    tc_comp.set_running();
                    chat.add_child(tc_comp.clone());
                    tools.insert(tc.id.clone(), tc_comp);
                }
            }
        }

        // Assert: the assistant component rendered the text + the thinking
        // block (the update_blocks path keeps thinking visible), and a tool
        // component was registered.
        let rendered = chat.render(80);
        let joined: String = rendered.join("\n");
        assert!(joined.contains("Hello."), "assistant text not rendered: {joined}");
        assert!(
            joined.contains("Reasoning about the reply."),
            "thinking block not rendered: {joined}"
        );
        assert_eq!(state.tool_components.lock().unwrap().len(), 1);
        assert!(state.current_assistant.lock().unwrap().is_some());

        // Manually apply ToolExecutionEnd (mirrors drain).
        let ended = state.tool_components.lock().unwrap().remove("tc1").unwrap();
        ended.set_result("hi", false);
        assert!(state.tool_components.lock().unwrap().is_empty());
    }

    #[test]
    fn test_short_model_name() {
        assert_eq!(short_model_name("anthropic:claude-sonnet-5"), "claude-sonnet-5");
        assert_eq!(short_model_name("claude-sonnet-5"), "claude-sonnet-5");
    }

    #[test]
    fn test_cycle_next_model_wraps_around() {
        use rpi_ai::{Api, Model};
        let mk = |id: &str| {
            Model::new(id, id, Api::AnthropicMessages, "anthropic", "https://api.anthropic.com")
        };
        let catalog = [mk("a"), mk("b"), mk("c")];
        // Next after "a" is "b"; after "c" wraps to "a".
        assert_eq!(cycle_next_model(&catalog, "a").unwrap().id, "b");
        assert_eq!(cycle_next_model(&catalog, "c").unwrap().id, "a");
        // An unknown current id falls back to the first model.
        assert_eq!(cycle_next_model(&catalog, "zzz").unwrap().id, "a");
        // Empty catalog yields None.
        let empty: Vec<Model> = vec![];
        assert!(cycle_next_model(&empty, "a").is_none());
    }

    #[test]
    fn test_autocomplete_slash_suggestions_render() {
        // The autocomplete container should render at least one suggestion
        // line when the editor holds a `/` prefix, and clear when it doesn't.
        let state = Arc::new(TuiState {
            current_assistant: std::sync::Mutex::new(None),
            tool_components: std::sync::Mutex::new(HashMap::new()),
            bash_components: std::sync::Mutex::new(HashMap::new()),
            last_tool_comp: std::sync::Mutex::new(None),
            status: std::sync::Mutex::new(RunStatus::Idle),
            footer: Arc::new(FooterComponent::new()),
            status_container: Arc::new(Container::new()),
            chat_container: Arc::new(Container::new()),
            loader: Arc::new(Loader::new()),
            last_assistant_text: std::sync::Mutex::new(String::new()),
            active_selector: std::sync::Mutex::new(None),
            autocomplete: AutocompleteManager::new(),
            autocomplete_container: Arc::new(Container::new()),
            theme_manager: Arc::new(ThemeManager::new()),
            tui: None,
            current_model_id: std::sync::Mutex::new(String::new()),
            show_images: std::sync::Mutex::new(true),
            history: std::sync::Mutex::new(Vec::new()),
            history_index: std::sync::Mutex::new(-1),
            history_draft: std::sync::Mutex::new(None),
        last_input_tokens: std::sync::Mutex::new(0),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: std::sync::Mutex::new(None),
        });
        {
            let mut combined = CombinedAutocompleteProvider::new();
            combined.add_provider(Arc::new(SlashCommandAutocompleteProvider::new(
                build_builtin_registry().visible_entries(),
            )));
            state.autocomplete.set_provider(Arc::new(combined));
        }

        let editor = Arc::new(Editor::simple());
        editor.set_text("/he");
        editor.set_cursor(0, 3);
        refresh_autocomplete(&state, &editor);
        let lines = state.autocomplete_container.render(80);
        let joined: String = lines.join("\n");
        assert!(joined.contains("/help"), "slash suggestions not rendered: {joined}");

        // Clear: no suggestions for plain text.
        editor.set_text("hello");
        editor.set_cursor(0, 5);
        refresh_autocomplete(&state, &editor);
        assert!(state.autocomplete_container.render(80).is_empty());
    }

    #[test]
    fn test_select_list_swap_restores_editor() {
        // The editor-container swap: opening a selector replaces the editor
        // child; closing restores it. Verify the container child count + the
        // active_selector flag round-trip.
        let state = Arc::new(TuiState {
            current_assistant: std::sync::Mutex::new(None),
            tool_components: std::sync::Mutex::new(HashMap::new()),
            bash_components: std::sync::Mutex::new(HashMap::new()),
            last_tool_comp: std::sync::Mutex::new(None),
            status: std::sync::Mutex::new(RunStatus::Idle),
            footer: Arc::new(FooterComponent::new()),
            status_container: Arc::new(Container::new()),
            chat_container: Arc::new(Container::new()),
            loader: Arc::new(Loader::new()),
            last_assistant_text: std::sync::Mutex::new(String::new()),
            active_selector: std::sync::Mutex::new(None),
            autocomplete: AutocompleteManager::new(),
            autocomplete_container: Arc::new(Container::new()),
            theme_manager: Arc::new(ThemeManager::new()),
            tui: None,
            current_model_id: std::sync::Mutex::new(String::new()),
            show_images: std::sync::Mutex::new(true),
            history: std::sync::Mutex::new(Vec::new()),
            history_index: std::sync::Mutex::new(-1),
            history_draft: std::sync::Mutex::new(None),
        last_input_tokens: std::sync::Mutex::new(0),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: std::sync::Mutex::new(None),
        });
        let editor_container = Arc::new(Container::new());
        let editor = Arc::new(Editor::simple());
        editor_container.add_child(editor.clone());
        assert!(!state.selector_open());

        let tui_terminal = Box::new(ProcessTerminal::new());
        let tui = Arc::new(TuiAltScreen::new(tui_terminal, true, None));
        let list = Arc::new(SelectList::new(
            vec![SelectItem::new("a", "A"), SelectItem::new("b", "B")],
            5,
        ));
        open_selector(&state, &editor_container, &editor, &tui, list, SelectorKind::Theme);
        assert!(state.selector_open());
        // list only (editor swapped out).
        assert_eq!(editor_container.child_count(), 1);

        close_selector(&state, &editor_container, &editor, &tui);
        assert!(!state.selector_open());
        // editor restored.
        assert_eq!(editor_container.child_count(), 1);
    }

    #[test]
    fn test_message_history_browse_restores_draft() {
        // ↑/↓ recall semantics (mirrors TS navigateHistory): push two
        // messages, browse older → newer → back past the newest restores the
        // draft the user was typing.
        let state = Arc::new(TuiState {
            current_assistant: std::sync::Mutex::new(None),
            tool_components: std::sync::Mutex::new(HashMap::new()),
            bash_components: std::sync::Mutex::new(HashMap::new()),
            last_tool_comp: std::sync::Mutex::new(None),
            status: std::sync::Mutex::new(RunStatus::Idle),
            footer: Arc::new(FooterComponent::new()),
            status_container: Arc::new(Container::new()),
            chat_container: Arc::new(Container::new()),
            loader: Arc::new(Loader::new()),
            last_assistant_text: std::sync::Mutex::new(String::new()),
            active_selector: std::sync::Mutex::new(None),
            autocomplete: AutocompleteManager::new(),
            autocomplete_container: Arc::new(Container::new()),
            theme_manager: Arc::new(ThemeManager::new()),
            tui: None,
            current_model_id: std::sync::Mutex::new(String::new()),
            show_images: std::sync::Mutex::new(true),
            history: std::sync::Mutex::new(Vec::new()),
            history_index: std::sync::Mutex::new(-1),
            history_draft: std::sync::Mutex::new(None),
        last_input_tokens: std::sync::Mutex::new(0),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: std::sync::Mutex::new(None),
        });
        let editor = Arc::new(Editor::simple());

        push_history(&state, "first message");
        push_history(&state, "second message");
        // Consecutive duplicate is skipped.
        push_history(&state, "second message");
        push_history(&state, "   "); // empty → skipped
        assert_eq!(state.history.lock().unwrap().len(), 2);
        assert_eq!(state.history.lock().unwrap()[0], "second message");

        // User starts typing a fresh prompt.
        editor.set_text("half-typed");
        editor.set_cursor(0, 11);

        // ↑ → most recent.
        navigate_history(&state, &editor, -1);
        assert_eq!(editor.get_text(), "second message");
        assert_eq!(*state.history_index.lock().unwrap(), 0);
        // ↑ → older.
        navigate_history(&state, &editor, -1);
        assert_eq!(editor.get_text(), "first message");
        assert_eq!(*state.history_index.lock().unwrap(), 1);
        // ↑ past the oldest → stays (no wrap).
        navigate_history(&state, &editor, -1);
        assert_eq!(editor.get_text(), "first message");
        // ↓ → newer.
        navigate_history(&state, &editor, 1);
        assert_eq!(editor.get_text(), "second message");
        // ↓ past the newest → restores the draft.
        navigate_history(&state, &editor, 1);
        assert_eq!(editor.get_text(), "half-typed");
        assert_eq!(*state.history_index.lock().unwrap(), -1);
    }

    #[test]
    fn test_accept_top_suggestion_replaces_prefix() {
        // `/he` + Tab → `/help ` (slash command provider inserts a space).
        let state = Arc::new(TuiState {
            current_assistant: std::sync::Mutex::new(None),
            tool_components: std::sync::Mutex::new(HashMap::new()),
            bash_components: std::sync::Mutex::new(HashMap::new()),
            last_tool_comp: std::sync::Mutex::new(None),
            status: std::sync::Mutex::new(RunStatus::Idle),
            footer: Arc::new(FooterComponent::new()),
            status_container: Arc::new(Container::new()),
            chat_container: Arc::new(Container::new()),
            loader: Arc::new(Loader::new()),
            last_assistant_text: std::sync::Mutex::new(String::new()),
            active_selector: std::sync::Mutex::new(None),
            autocomplete: AutocompleteManager::new(),
            autocomplete_container: Arc::new(Container::new()),
            theme_manager: Arc::new(ThemeManager::new()),
            tui: None,
            current_model_id: std::sync::Mutex::new(String::new()),
            show_images: std::sync::Mutex::new(true),
            history: std::sync::Mutex::new(Vec::new()),
            history_index: std::sync::Mutex::new(-1),
            history_draft: std::sync::Mutex::new(None),
        last_input_tokens: std::sync::Mutex::new(0),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: std::sync::Mutex::new(None),
        });
        {
            let mut combined = CombinedAutocompleteProvider::new();
            combined.add_provider(Arc::new(SlashCommandAutocompleteProvider::new(
                build_builtin_registry().visible_entries(),
            )));
            state.autocomplete.set_provider(Arc::new(combined));
        }
        let editor = Arc::new(Editor::simple());
        editor.set_text("/he");
        editor.set_cursor(0, 3);
        refresh_autocomplete(&state, &editor);
        let accepted = accept_top_suggestion(&state, &editor);
        assert!(accepted, "should accept the top suggestion");
        let text = editor.get_text();
        assert!(
            text.starts_with("/help"),
            "editor text should start with /help, got {text}"
        );
    }
}