rpi-cli 0.3.23

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
use super::*;
use rpi_tui::Component;

#[test]
fn changelog_command_shows_current_release_and_all_is_explicit() {
    let entries = crate::changelog::bundled_entries();
    let latest = crate::changelog::latest_release(&entries, crate::VERSION);
    let heading = |entry: &crate::changelog::ChangelogEntry| {
        format!("{}.{}.{}", entry.major, entry.minor, entry.patch)
    };
    let latest_heading = heading(&latest[0]);
    let historical_heading = heading(entries.last().unwrap());
    let chat = Arc::new(Container::new());
    add_changelog_message(&chat);
    let output = strip_ansi(&chat.render(120).join("\n"));
    assert!(output.lines().any(|line| line.trim() == latest_heading));
    assert!(!output.lines().any(|line| line.trim() == historical_heading));
    assert!(!output.contains("Native parity phase 1"));
    let chat = Arc::new(Container::new());
    add_changelog_message_with_scope(&chat, true);
    let output = strip_ansi(&chat.render(120).join("\n"));
    assert!(output.lines().any(|line| line.trim() == historical_heading));
    assert!(output.lines().any(|line| line.trim() == latest_heading));
}

#[test]
fn startup_changelog_foreign_profile_is_shown_once_and_persisted() {
    const CHILD: &str = "RPI_CHANGELOG_REGRESSION_CHILD";
    if std::env::var_os(CHILD).is_none() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("settings.json"),
            r#"{"lastChangelogVersion":"0.85.1","custom":{"retained":true}}"#,
        )
        .unwrap();
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "interactive_tui::tests::startup_changelog_foreign_profile_is_shown_once_and_persisted", "--nocapture"])
            .env(CHILD, "1").env(crate::config::CONFIG_DIR_ENV, dir.path()).output().unwrap();
        assert!(
            output.status.success(),
            "{}\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        return;
    }
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            let harness = AgentHarness::create(Default::default()).await.unwrap();
            let settings = crate::settings::load_settings().unwrap();
            let chat = Arc::new(Container::new());
            maybe_add_startup_changelog(&harness, &chat, &settings, false, true).await;
            let output = strip_ansi(&chat.render(120).join("\n"));
            assert!(output.contains("What's New"));
            assert!(output.lines().any(|line| line.trim() == crate::VERSION));
            let old = crate::changelog::bundled_entries().pop().unwrap();
            let old_version = format!("{}.{}.{}", old.major, old.minor, old.patch);
            assert!(!output.lines().any(|line| line.trim() == old_version));
            let settings = crate::settings::load_settings().unwrap();
            assert_eq!(
                settings.last_rpi_changelog_version.as_deref(),
                Some(crate::VERSION)
            );
            assert_eq!(settings.last_changelog_version.as_deref(), Some("0.85.1"));
            let chat = Arc::new(Container::new());
            maybe_add_startup_changelog(&harness, &chat, &settings, false, true).await;
            assert_eq!(chat.child_count(), 0);
            let value: serde_json::Value = serde_json::from_slice(
                &std::fs::read(crate::config::settings_path().unwrap()).unwrap(),
            )
            .unwrap();
            assert_eq!(value["custom"]["retained"], true);
            // A newer process may save a marker after this startup read its settings.
            let mut stale = settings.clone();
            let current_version = semver::Version::parse(crate::VERSION).unwrap();
            let old = crate::changelog::bundled_entries()
                .into_iter()
                .find(|entry| {
                    (entry.major, entry.minor, entry.patch)
                        < (
                            current_version.major,
                            current_version.minor,
                            current_version.patch,
                        )
                })
                .unwrap();
            stale.last_rpi_changelog_version =
                Some(format!("{}.{}.{}", old.major, old.minor, old.patch));
            let mut newer = settings;
            let mut next_version = current_version;
            next_version.patch += 1;
            newer.last_rpi_changelog_version = Some(next_version.to_string());
            crate::settings::save_settings(&newer).unwrap();
            maybe_add_startup_changelog(&harness, &Arc::new(Container::new()), &stale, false, true)
                .await;
            assert_eq!(
                crate::settings::load_settings()
                    .unwrap()
                    .last_rpi_changelog_version,
                Some(next_version.to_string())
            );
        });
}

#[test]
fn collapsed_startup_changelog_links_to_full_notes() {
    let chat = Arc::new(Container::new());
    add_startup_changelog_message(&chat, "## 0.3.17\n\n- full release detail", "0.3.17", true);
    let output = strip_ansi(&chat.render(120).join("\n"));
    assert!(output.contains("Updated to v0.3.17"));
    assert!(output.contains("/changelog"));
    assert!(!output.contains("full release detail"));
    let chat = Arc::new(Container::new());
    add_startup_changelog_message(&chat, "## 0.3.17\n\n- full release detail", "0.3.17", false);
    let output = strip_ansi(&chat.render(120).join("\n"));
    assert!(output.contains("What's New"));
    assert!(output.contains("full release detail"));
}

#[test]
fn queued_user_message_keeps_images_and_image_only_messages() {
    let image = rpi_ai::types::ImageContent {
        kind: rpi_ai::types::ImageContentType,
        data: "test".into(),
        mime_type: "image/png".into(),
    };
    for text in ["", "inspect this"] {
        let message = user_message_with_images(text, vec![image.clone()]);
        let AgentMessage::User(user) = message else {
            panic!("expected user message")
        };
        let rpi_ai::types::UserContent::Blocks(blocks) = user.content else {
            panic!("expected image blocks")
        };
        assert!(
            matches!(blocks.last(), Some(rpi_ai::types::Content::Image(value)) if value == &image)
        );
        assert_eq!(blocks.len(), if text.is_empty() { 1 } else { 2 });
    }
}

#[test]
fn pasted_images_accept_multiple_quoted_paths_without_consuming_normal_text() {
    let dir = tempfile::tempdir().unwrap();
    let mut bytes = Vec::new();
    {
        let mut encoder = png::Encoder::new(&mut bytes, 1, 1);
        encoder.set_color(png::ColorType::Rgba);
        encoder
            .write_header()
            .unwrap()
            .write_image_data(&[255, 0, 0, 255])
            .unwrap();
    }
    let first = dir.path().join("first image.png");
    let second = dir.path().join("second.png");
    std::fs::write(&first, &bytes).unwrap();
    std::fs::write(&second, &bytes).unwrap();
    let quoted = format!("\"{}\" \"{}\"", first.display(), second.display());
    assert_eq!(images_from_pasted_paths(&quoted).unwrap().len(), 2);
    assert_eq!(
        images_from_pasted_paths(&format!("{}\n{}", first.display(), second.display()))
            .unwrap()
            .len(),
        2
    );
    assert!(images_from_pasted_paths("please inspect these images").is_none());
    let state = test_tui_state();
    let images = images_from_pasted_paths(&quoted).unwrap();
    for image in &images {
        state.queue_image(image.clone());
    }
    let sent = state.take_pending_images();
    assert!(state.take_pending_images().is_empty());
    state.queue_image(images[0].clone());
    state.restore_pending_images(sent);
    assert_eq!(state.take_pending_images().len(), 3);
    state.editor.set_text("existing draft");
    assert!(attach_pasted_images(
        &state,
        &format!("\"{}\"", first.display())
    ));
    assert_eq!(state.take_pending_images().len(), 1);
    assert_eq!(state.editor.get_text(), "existing draft");
    assert!(!attach_pasted_images(&state, "normal clipboard text"));
    assert!(state.take_pending_images().is_empty());
}

#[test]
#[ignore = "set RPI_STATS_DLL to the monitor DLL"]
fn monitor_function_key_works_with_a_draft_without_changing_text() {
    use rpi_extensions::{
        dispatch_empty_event, load_session_mixed, NullDiagnostics, RegistrySnapshot,
    };
    use rpi_plugin_sdk::EventTag;
    struct Shutdown(Arc<RegistrySnapshot>);
    impl Drop for Shutdown {
        fn drop(&mut self) {
            dispatch_empty_event(&self.0, EventTag::SessionShutdown);
        }
    }
    let state = test_tui_state();
    let session = load_session_mixed(
        &[],
        &[std::path::PathBuf::from(
            std::env::var("RPI_STATS_DLL").unwrap(),
        )],
        Arc::new(NullDiagnostics),
        None,
    );
    let snapshot = session.snapshot_arc().expect("monitor loaded");
    *state.extension_session.lock().unwrap() = session;
    let _shutdown = Shutdown(snapshot);
    state.editor.set_text("unsent draft");
    assert!(dispatch_key_event(
        &state,
        &KeyEvent::new(KeyCode::F(8), KeyModifiers::NONE),
        &state.editor
    ));
    assert_eq!(state.editor.get_text(), "unsent draft");
    assert!(!dispatch_key_event(
        &state,
        &KeyEvent::new(KeyCode::F(8), KeyModifiers::CONTROL),
        &state.editor
    ));
    assert!(!dispatch_key_event(
        &state,
        &KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE),
        &state.editor
    ));
    assert_eq!(state.editor.get_text(), "unsent draft");
}

#[test]
fn modal_inputs_keep_registered_plugin_shortcuts_until_closed() {
    use rpi_extensions::{ExtensionRegistry, ExtensionSession, PluginKeepalive};
    use rpi_plugin_sdk::{EventTag, StablePluginEvent, EVENT_HANDLER_CLAIMED};
    use std::sync::atomic::{AtomicUsize, Ordering};
    static CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<AtomicUsize>> =
        rpi_plugin_sdk::handles::ToolHandles::new();
    struct ContextOwner(usize);
    impl Drop for ContextOwner {
        fn drop(&mut self) {
            drop(CONTEXTS.remove(self.0 as rpi_plugin_sdk::StepHandle));
        }
    }
    extern "C" fn claim(_: StablePluginEvent, user_data: *mut std::ffi::c_void) -> i32 {
        let context = CONTEXTS.get(user_data).expect("live test context");
        let calls = context.lock().clone();
        calls.fetch_add(1, Ordering::SeqCst);
        EVENT_HANDLER_CLAIMED
    }
    let calls = Arc::new(AtomicUsize::new(0));
    let context = CONTEXTS.insert(calls.clone());
    let _owner = ContextOwner(context as usize);
    let state = test_tui_state();
    let mut registry = ExtensionRegistry::new();
    for name in ["space", "f8", "escape", "enter"] {
        registry.register_shortcut("test".into(), name.into(), "test".into());
    }
    registry.register_event_handler("test".into(), EventTag::Input, claim, context);
    *state.extension_session.lock().unwrap() = ExtensionSession::from_parts(
        Arc::new(registry.snapshot()),
        PluginKeepalive::empty(),
        vec![],
        None,
    );
    let keys = [KeyCode::Char(' '), KeyCode::F(8), KeyCode::Enter];
    for code in keys {
        assert!(dispatch_key_event(
            &state,
            &KeyEvent::new(code, KeyModifiers::NONE),
            &state.editor
        ));
        assert!(dispatch_key_event(
            &state,
            &KeyEvent::new_with_kind(code, KeyModifiers::NONE, KeyEventKind::Release),
            &state.editor
        ));
    }
    let before = calls.load(Ordering::SeqCst);
    for modal in 0..4 {
        match modal {
            0 => *state.active_extension_editor.lock().unwrap() = Some(Arc::new(Editor::simple())),
            1 => *state.active_extension_input.lock().unwrap() = Some(Arc::new(Input::new())),
            2 => {
                *state.active_selector.lock().unwrap() = Some((
                    SelectorView::List(Arc::new(SelectList::new(vec![], 5))),
                    SelectorKind::Extension,
                ))
            }
            _ => state.search.activate(),
        }
        for code in keys.into_iter().chain([KeyCode::Esc]) {
            for kind in [
                KeyEventKind::Press,
                KeyEventKind::Repeat,
                KeyEventKind::Release,
            ] {
                let key = KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind);
                assert!(!dispatch_key_event(&state, &key, &state.editor));
            }
        }
        assert_eq!(calls.load(Ordering::SeqCst), before);
        state.active_extension_editor.lock().unwrap().take();
        state.active_extension_input.lock().unwrap().take();
        state.active_selector.lock().unwrap().take();
        state.search.deactivate();
    }
    assert!(dispatch_key_event(
        &state,
        &KeyEvent::new(KeyCode::F(8), KeyModifiers::NONE),
        &state.editor
    ));
    assert_eq!(calls.load(Ordering::SeqCst), before + 1);
    let space = KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE);
    assert!(dispatch_key_event(&state, &space, &state.editor));
    state.editor.set_text("injected transcription");
    *state.active_extension_input.lock().unwrap() = Some(Arc::new(Input::new()));
    let held = calls.load(Ordering::SeqCst);
    assert!(dispatch_key_event(
        &state,
        &KeyEvent::new_with_kind(space.code, space.modifiers, KeyEventKind::Release),
        &state.editor
    ));
    assert_eq!(
        calls.load(Ordering::SeqCst),
        held + 1,
        "finish the already-owned hold"
    );
    assert!(!dispatch_key_event(&state, &space, &state.editor));
}

/// A draft injected from a voice transcription is submitted only when it is
/// still exactly what we put in the editor and no run has started; any
/// user edit (or a cleared editor) hands it back for editing instead.
#[test]
fn auto_send_cancels_when_the_user_edits_the_draft() {
    let now = std::time::Instant::now();
    let pending = AutoSendPending {
        deadline: now + std::time::Duration::from_secs(2),
        text: "hello world".to_string(),
    };
    // Untouched → still counting down.
    assert!(matches!(
        auto_send_step(Some(&pending), "hello world", true, now),
        AutoSendStep::Wait(_)
    ));
    // One added character is the user's correction: never send a draft
    // they are actively editing.
    assert_eq!(
        auto_send_step(Some(&pending), "hello worlds", true, now),
        AutoSendStep::Cancel
    );
    // Cleared out from under us (a slash command, Esc).
    assert_eq!(
        auto_send_step(Some(&pending), "", true, now),
        AutoSendStep::Cancel
    );
    // Whitespace is not content.
    assert_eq!(
        auto_send_step(Some(&pending), "   ", true, now),
        AutoSendStep::Cancel
    );
}

/// The countdown fires exactly at the deadline, and never injects a prompt
/// into a run that started while it was ticking.
#[test]
fn auto_send_submits_at_the_deadline_only_while_idle() {
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(2000);
    let pending = AutoSendPending {
        deadline,
        text: "go".to_string(),
    };
    assert!(matches!(
        auto_send_step(
            Some(&pending),
            "go",
            true,
            deadline - std::time::Duration::from_millis(1)
        ),
        AutoSendStep::Wait(_)
    ));
    assert_eq!(
        auto_send_step(Some(&pending), "go", true, deadline),
        AutoSendStep::Submit
    );
    // A turn started underneath the countdown — keep the draft, do not
    // queue a prompt mid-turn.
    assert_eq!(
        auto_send_step(Some(&pending), "go", false, deadline),
        AutoSendStep::Cancel
    );
    // Nothing pending.
    assert_eq!(
        auto_send_step(None, "go", true, deadline),
        AutoSendStep::Idle
    );
}

/// The footer text the countdown writes is prefixed so `clear_auto_send`
/// can tell its own message from an unrelated run status.
#[test]
fn auto_send_footer_label_is_recognisable() {
    let label = format!("{AUTO_SEND_PREFIX}2.0s · any key to edit");
    assert!(label.starts_with(AUTO_SEND_PREFIX));
    assert!(!"Working…".starts_with(AUTO_SEND_PREFIX));
}

#[test]
fn markdown_flag_only_comes_from_an_explicit_true() {
    // Tools opt in by setting `details.markdown = true` (rpi-todo does).
    assert!(tool_result_requests_markdown(Some(
        &serde_json::json!({"kind": "todo", "markdown": true})
    )));
    // Absence, a false value, or a non-bool value keeps plain rendering,
    // so every other tool is unaffected.
    assert!(!tool_result_requests_markdown(None));
    assert!(!tool_result_requests_markdown(Some(
        &serde_json::json!({"kind": "todo"})
    )));
    assert!(!tool_result_requests_markdown(Some(
        &serde_json::json!({"markdown": false})
    )));
    assert!(!tool_result_requests_markdown(Some(
        &serde_json::json!({"markdown": "true"})
    )));
}

/// Minimal `TuiState` for unit tests that only touch state flags. Mirrors
/// the explicit literals other tests build, but keeps one copy in sync.
fn test_tui_state() -> Arc<TuiState> {
    Arc::new(TuiState {
        current_assistant: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: 5,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: std::sync::Mutex::new(None),
    })
}

/// A `SetEditorText` injection — and the host's own auto-send clear — must be
/// attributed to `extension`, not to the user.
///
/// A hands-free voice extension stands down whenever `source == "user"`
/// (the human took the keyboard), so mislabelling the plugin's own injected
/// transcription would cancel the whole conversation on its first turn.
#[test]
fn editor_change_source_separates_tui_writes_from_typing() {
    use std::sync::atomic::Ordering;
    let state = test_tui_state();

    // Nothing changed yet → nothing to report.
    assert!(state.take_editor_change().is_none());

    // The render tick applies an extension's draft…
    state.editor_text.push(rpi_extensions::EditorTextEdit {
        text: "你好".to_string(),
        mode: rpi_extensions::EditorTextMode::Replace,
        auto_send_ms: Some(2000),
    });
    assert!(state.drain_editor_text(), "the queued draft must land");
    assert!(
        state.programmatic_editor_write.load(Ordering::SeqCst),
        "a mailbox-applied edit must be marked programmatic"
    );

    // …so its change is ours, not the user's.
    let payload = state
        .take_editor_change()
        .expect("draft applied ⇒ a change");
    assert_eq!(payload["source"], serde_json::json!("extension"));
    assert_eq!(payload["chars"], serde_json::json!(2));
    assert_eq!(payload["empty"], serde_json::json!(false));

    // The mark was consumed: the same text twice is not re-reported, and a
    // genuine human edit is attributed to the user.
    assert!(state.take_editor_change().is_none());
    state.editor.set_text("你好啊");
    let payload = state.take_editor_change().expect("typing ⇒ a change");
    assert_eq!(payload["source"], serde_json::json!("user"));
    assert_eq!(payload["chars"], serde_json::json!(3));
}

/// The attribution mark must not survive unrelated changes, or one injected
/// draft would make the *next* keystroke look programmatic too.
#[test]
fn programmatic_mark_is_consumed_even_with_no_subscriber() {
    use std::sync::atomic::Ordering;
    let state = test_tui_state();
    assert!(
        state
            .extension_session
            .lock()
            .unwrap()
            .snapshot_arc()
            .is_none(),
        "this test relies on nobody subscribing"
    );

    state.editor_text.push(rpi_extensions::EditorTextEdit {
        text: "draft".to_string(),
        mode: rpi_extensions::EditorTextMode::Replace,
        auto_send_ms: None,
    });
    state.drain_editor_text();
    // `sync_editor_change` bails out early (no subscriber)…
    state.sync_editor_change();
    // …but the mark is gone, so the next real edit is the user's.
    assert!(!state.programmatic_editor_write.load(Ordering::SeqCst));
    state.editor.set_text("draft +");
    let payload = state.take_editor_change().expect("typing ⇒ a change");
    assert_eq!(payload["source"], serde_json::json!("user"));
}

/// Regression: the editor clear that follows *every* submit is host
/// housekeeping, not the user typing.
///
/// Reporting it as `source:"user"` switched a hands-free voice session off
/// the instant it was switched on: `/voice auto` turns the mode on, then the
/// render tick notices the cleared editor ~80ms later, stands the mode down
/// and aborts the listen it just started — so the microphone never stayed
/// open and the session looked like it "didn't hear anything".
#[test]
fn submit_clear_is_attributed_to_the_host_not_the_user() {
    let state = test_tui_state();

    // Typing the command is a genuine user edit.
    state.editor.set_text("/voice auto");
    assert_eq!(
        state.take_editor_change().unwrap()["source"],
        serde_json::json!("user")
    );

    // The submit path's clear is not.
    state.clear_editor_programmatically();
    let payload = state.take_editor_change().expect("clearing is a change");
    assert_eq!(payload["empty"], serde_json::json!(true));
    assert_eq!(
        payload["source"],
        serde_json::json!("extension"),
        "a submit-clear must not be reported as the user typing"
    );
}

/// A user-initiated clear (Esc, select-all + delete) still goes through the
/// editor itself and must stay `user` — only host writes are reattributed.
#[test]
fn user_initiated_clear_stays_a_user_change() {
    let state = test_tui_state();
    state.editor.set_text("draft");
    assert_eq!(
        state.take_editor_change().unwrap()["source"],
        serde_json::json!("user")
    );
    state.editor.clear();
    let payload = state.take_editor_change().expect("clearing is a change");
    assert_eq!(payload["source"], serde_json::json!("user"));
}

#[test]
fn live_panel_repaints_while_a_tool_or_bash_is_running() {
    // No panels → only the dock loader animates (reuse the cached
    // transcript instead of rebuilding a long history).
    let empty: HashMap<String, Arc<ToolExecutionComponent>> = HashMap::new();
    assert!(!transcript_has_live_panel(false, &empty));

    // A running tool call is a live panel: its elapsed readout is computed
    // at render time, so it must force a transcript rebuild every tick.
    let mut tools = HashMap::new();
    let tool = Arc::new(ToolExecutionComponent::new("search", "{}"));
    tool.set_running();
    tools.insert("tc1".to_string(), tool);
    assert!(transcript_has_live_panel(false, &tools));

    // A finished tool no longer needs the repaint, but a running bash
    // command still does.
    tools.get("tc1").unwrap().set_result("done", false);
    assert!(!transcript_has_live_panel(false, &tools));
    assert!(transcript_has_live_panel(true, &tools));
}

#[test]
fn dequeue_merge_preserves_a_typed_draft() {
    assert_eq!(merge_queued_into_draft("queued", ""), "queued");
    assert_eq!(merge_queued_into_draft("queued", "   "), "queued");
    assert_eq!(
        merge_queued_into_draft("queued", "typed"),
        "queued\n\ntyped"
    );
}

#[test]
fn dequeue_places_the_caret_at_the_end_of_the_last_line_in_bytes() {
    // Restoring queued messages followed by the old `(0, char_count)` call
    // parked the caret at the end of the FIRST line, and treated a char
    // count as a byte offset (so any CJK draft landed mid-character).
    let editor = Arc::new(Editor::simple());
    // Multi-line + multibyte: the caret must be on the LAST row, after the
    // final byte of that row.
    let text = "排队\n第二行";
    set_editor_text_caret_at_end(&editor, text);
    assert_eq!(editor.get_text(), text);
    assert_eq!(
        editor.cursor_position(),
        (1, "第二行".len()),
        "caret must sit at the end of the last line, in bytes"
    );
}

#[test]
fn settings_menu_covers_the_wired_settings_surface() {
    let state = test_tui_state();
    let settings = crate::settings::Settings::default();
    let items = settings_menu_items(&settings, &state, "claude-sonnet-5");
    let keys: Vec<&str> = items.iter().map(|item| item.key.as_str()).collect();
    assert_eq!(
        keys,
        [
            "theme",
            "model",
            "thinking",
            "scoped-models",
            "hide-thinking",
            "show-images",
            "cache-miss-notices",
            "quiet-startup",
            "collapse-changelog",
            "terminal-progress",
            "fullscreen-copy-on-select",
            "double-escape-action",
            "editor-padding",
            "autocomplete-max-items",
            "http-idle-timeout",
        ]
    );
    // Submenu rows must not cycle their displayed value.
    for item in items.iter().filter(|item| item.has_submenu) {
        assert!(
            item.values.is_empty(),
            "{} should be submenu-only",
            item.key
        );
    }
    // Value rows advertise a cycle that contains the current value.
    for item in items.iter().filter(|item| !item.has_submenu) {
        assert!(!item.values.is_empty(), "{} has no values", item.key);
        assert!(
            item.values.iter().any(|value| value == &item.value),
            "{} current value {} not in {:?}",
            item.key,
            item.value,
            item.values
        );
    }
    // The default model row falls back to the running lane's model.
    let value = |key: &str| {
        items
            .iter()
            .find(|item| item.key == key)
            .unwrap()
            .value
            .as_str()
    };
    assert_eq!(value("model"), "claude-sonnet-5");
    // Native defaults: cache-miss notices off, terminal progress on.
    assert_eq!(value("cache-miss-notices"), "false");
    assert_eq!(value("terminal-progress"), "true");
    assert_eq!(value("collapse-changelog"), "false");
}

#[test]
fn apply_setting_change_updates_settings_and_live_state() {
    let state = test_tui_state();
    let mut settings = crate::settings::Settings::default();

    // Live: hide-thinking flips both the runtime flag and the persisted one.
    let note = apply_setting_change(&state, "hide-thinking", "true", &mut settings);
    assert!(state.hide_thinking());
    assert_eq!(settings.hide_thinking_block, Some(true));
    assert!(note.expect("user-visible note").contains("hidden"));

    // Live: show-images writes the runtime mutex.
    apply_setting_change(&state, "show-images", "false", &mut settings);
    assert!(!*state.show_images.lock().unwrap());
    assert_eq!(settings.show_images, Some(false));

    // Live: cache-miss notices.
    apply_setting_change(&state, "cache-miss-notices", "true", &mut settings);
    assert!(*state.cache_miss_notices.lock().unwrap());
    assert_eq!(settings.show_cache_miss_notices, Some(true));

    // Persist-only rows change settings without a transcript note.
    assert_eq!(
        apply_setting_change(&state, "editor-padding", "3", &mut settings),
        None
    );
    assert_eq!(settings.editor_padding_x, Some(3));
    apply_setting_change(&state, "double-escape-action", "none", &mut settings);
    assert_eq!(settings.double_escape_action.as_deref(), Some("none"));
    apply_setting_change(&state, "autocomplete-max-items", "20", &mut settings);
    assert_eq!(settings.autocomplete_max_visible, Some(20));

    // HTTP idle timeout maps labels onto the numeric/`disabled` forms.
    apply_setting_change(&state, "http-idle-timeout", "disabled", &mut settings);
    assert_eq!(settings.http_idle_timeout_ms(), Some(0));
    apply_setting_change(&state, "http-idle-timeout", "1m", &mut settings);
    assert_eq!(settings.http_idle_timeout_ms(), Some(60_000));

    // Unknown keys are ignored rather than panicking.
    assert_eq!(
        apply_setting_change(&state, "nope", "x", &mut settings),
        None
    );
}

#[test]
fn add_user_message_renders_a_visible_user_bubble() {
    // The submit handler renders directly-sent prompts through this helper
    // (the harness emits no user `message_start` for them), so a silent
    // failure here would make every prompt vanish from the transcript.
    let chat = Arc::new(Container::new());
    add_user_message(&chat, "hello from the user");
    let rendered = crate::interactive_tui::collect_transcript_lines(&chat);
    let plain = strip_ansi(&rendered.join("\n"));
    assert!(
        plain.contains("hello from the user"),
        "user bubble must show the prompt text; got: {plain:?}"
    );
}

#[test]
fn verbose_overrides_quiet_startup_listing() {
    assert!(should_show_startup_listing(false, false));
    assert!(should_show_startup_listing(true, false));
    assert!(should_show_startup_listing(true, true));
    assert!(!should_show_startup_listing(false, true));
}

#[test]
fn resume_command_omits_the_default_session_dir() {
    let cwd = std::path::Path::new("/proj/demo");
    assert_eq!(format_resume_command("", cwd, None), None);
    assert_eq!(
        format_resume_command("abc-123", cwd, None).as_deref(),
        Some("rpi --session abc-123")
    );
    // The default dir carries no flag (mirrors upstream).
    let default = crate::session::default_session_dir(cwd);
    assert_eq!(
        format_resume_command("abc-123", cwd, Some(default.as_path())).as_deref(),
        Some("rpi --session abc-123")
    );
    // A custom dir is echoed, quoting when needed.
    let custom = std::path::Path::new("/tmp/my sessions");
    assert_eq!(
        format_resume_command("abc-123", cwd, Some(custom)).as_deref(),
        Some("rpi --session-dir \"/tmp/my sessions\" --session abc-123")
    );
}

#[test]
fn quote_shell_arg_quotes_only_when_needed() {
    assert_eq!(quote_shell_arg("plain"), "plain");
    assert_eq!(quote_shell_arg("with space"), "\"with space\"");
    assert_eq!(quote_shell_arg("a&b"), "\"a&b\"");
}

#[test]
fn trust_command_uses_the_session_cwd_after_process_chdir() {
    const CHILD_ENV: &str = "RPI_TEST_TRUST_COMMAND_CHILD";
    const SESSION_CWD_ENV: &str = "RPI_TEST_TRUST_COMMAND_SESSION_CWD";
    const TEST_NAME: &str =
        "interactive_tui::tests::trust_command_uses_the_session_cwd_after_process_chdir";

    if std::env::var_os(CHILD_ENV).is_some() {
        let session_cwd = std::path::PathBuf::from(
            std::env::var_os(SESSION_CWD_ENV).expect("child session cwd should be configured"),
        );
        let changed_cwd = std::env::current_dir().unwrap();

        set_project_trust_for_command(&session_cwd, Some(true)).unwrap();

        assert_eq!(
            crate::config::project_trust_decision(&session_cwd).unwrap(),
            Some(true)
        );
        assert_eq!(
            crate::config::project_trust_decision(&changed_cwd).unwrap(),
            None
        );
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let session_cwd = tmp.path().join("session-project");
    let changed_cwd = tmp.path().join("extension-cwd");
    let agent_dir = tmp.path().join("agent");
    std::fs::create_dir_all(&session_cwd).unwrap();
    std::fs::create_dir_all(&changed_cwd).unwrap();
    std::fs::create_dir_all(&agent_dir).unwrap();

    let status = std::process::Command::new(std::env::current_exe().unwrap())
        .arg("--exact")
        .arg(TEST_NAME)
        .arg("--nocapture")
        .env(CHILD_ENV, "1")
        .env(SESSION_CWD_ENV, &session_cwd)
        .env(crate::config::CONFIG_DIR_ENV, &agent_dir)
        .current_dir(&changed_cwd)
        .status()
        .unwrap();

    assert!(status.success(), "child test process failed: {status}");
}

#[test]
fn tui_startup_settings_prefer_rpi_project_fields_over_pi() {
    let global = crate::settings::Settings {
        editor_padding_x: Some(3),
        autocomplete_max_visible: Some(6),
        hide_thinking_block: Some(false),
        quiet_startup: Some(true),
        show_terminal_progress: Some(true),
        ..Default::default()
    };
    let rpi_project = crate::settings::Settings {
        editor_padding_x: Some(0),
        hide_thinking_block: Some(true),
        quiet_startup: Some(false),
        show_terminal_progress: Some(false),
        ..Default::default()
    };
    let pi_project = crate::settings::Settings {
        editor_padding_x: Some(9),
        autocomplete_max_visible: Some(12),
        quiet_startup: Some(true),
        ..Default::default()
    };

    assert_eq!(
        resolve_tui_startup_settings(&global, &[rpi_project, pi_project], true),
        TuiStartupSettings {
            editor_padding_x: 0,
            autocomplete_max_visible: 12,
            hide_thinking: true,
            quiet_startup: false,
            show_terminal_progress: false,
            show_images: true,
            cache_miss_notices: false,
        }
    );
}

#[test]
fn tui_startup_settings_fall_back_from_rpi_to_pi_per_field() {
    let global = crate::settings::Settings {
        quiet_startup: Some(false),
        ..Default::default()
    };
    let rpi_project = crate::settings::Settings::default();
    let pi_project = crate::settings::Settings {
        quiet_startup: Some(true),
        ..Default::default()
    };

    let resolved = resolve_tui_startup_settings(&global, &[rpi_project, pi_project], true);

    assert!(resolved.quiet_startup);
}

#[test]
fn tui_startup_settings_use_global_values_without_project_fields() {
    let global = crate::settings::Settings {
        editor_padding_x: Some(7),
        autocomplete_max_visible: Some(8),
        hide_thinking_block: Some(true),
        quiet_startup: Some(true),
        show_terminal_progress: Some(false),
        show_images: Some(false),
        show_cache_miss_notices: Some(true),
        ..Default::default()
    };

    assert_eq!(
        resolve_tui_startup_settings(&global, &[crate::settings::Settings::default()], true,),
        TuiStartupSettings {
            editor_padding_x: 7,
            autocomplete_max_visible: 8,
            hide_thinking: true,
            quiet_startup: true,
            show_terminal_progress: false,
            show_images: false,
            cache_miss_notices: true,
        }
    );
}

#[test]
fn tui_startup_settings_read_native_nested_terminal_block() {
    // upstream nests these under `terminal`; rpi's flat keys stay
    // compatible and the nested block is the fallback.
    let global = crate::settings::Settings {
        terminal: Some(crate::settings::TerminalSettings {
            show_images: Some(false),
            show_terminal_progress: Some(false),
            clear_on_shrink: None,
        }),
        ..Default::default()
    };
    let resolved =
        resolve_tui_startup_settings(&global, &[crate::settings::Settings::default()], true);
    assert!(!resolved.show_images);
    assert!(!resolved.show_terminal_progress);
}

#[test]
fn tui_startup_settings_flat_keys_win_over_nested_terminal_block() {
    let global = crate::settings::Settings {
        show_images: Some(true),
        terminal: Some(crate::settings::TerminalSettings {
            show_images: Some(false),
            show_terminal_progress: None,
            clear_on_shrink: None,
        }),
        ..Default::default()
    };
    let resolved =
        resolve_tui_startup_settings(&global, &[crate::settings::Settings::default()], true);
    assert!(resolved.show_images);
}

#[test]
fn tui_startup_settings_ignore_untrusted_project_values() {
    let global = crate::settings::Settings {
        quiet_startup: Some(false),
        show_terminal_progress: Some(true),
        ..Default::default()
    };
    let project = crate::settings::Settings {
        quiet_startup: Some(true),
        show_terminal_progress: Some(false),
        ..Default::default()
    };

    let resolved = resolve_tui_startup_settings(&global, &[project], false);

    assert!(!resolved.quiet_startup);
    assert!(resolved.show_terminal_progress);
}

#[test]
fn transcript_page_uses_viewport_with_overlap() {
    assert_eq!(transcript_page_size(24), 20);
    assert_eq!(transcript_page_size(4), 1);
    assert_eq!(transcript_page_size(0), 1);
}

#[test]
fn parse_user_bash_distinguishes_single_and_double_bang() {
    // `!cmd` runs and stays in context.
    assert_eq!(parse_user_bash("!ls -la"), Some(("ls -la", false)));
    // `!!cmd` runs but is excluded from context.
    assert_eq!(parse_user_bash("!!ls -la"), Some(("ls -la", true)));
    // Surrounding whitespace on the command is trimmed, the `!` prefix is not.
    assert_eq!(parse_user_bash("!  echo hi  "), Some(("echo hi", false)));
    assert_eq!(parse_user_bash("!!  echo hi"), Some(("echo hi", true)));
}

#[test]
fn parse_user_bash_ignores_bare_bang_and_plain_text() {
    // A bare `!` / `!!` has no command: fall through to the prompt path
    // instead of executing an empty shell line.
    assert_eq!(parse_user_bash("!"), None);
    assert_eq!(parse_user_bash("!!"), None);
    assert_eq!(parse_user_bash("!   "), None);
    assert_eq!(parse_user_bash("hello"), None);
    assert_eq!(parse_user_bash(""), None);
    // `/` keeps routing to the slash-command registry.
    assert_eq!(parse_user_bash("/model"), None);
}

#[test]
fn user_bash_run_slot_guards_and_cancels() {
    let state = test_tui_state();
    assert!(!state.user_bash_running());
    let cancel = state.begin_user_bash();
    assert!(state.user_bash_running());
    // Esc cancels without freeing the slot; the spawned task clears it when
    // the capture resolves (upstream's `isBashRunning`).
    assert!(state.cancel_user_bash());
    assert!(state.user_bash_running());
    assert!(cancel.is_cancelled());
    state.finish_user_bash();
    assert!(!state.user_bash_running());
    // Nothing to cancel once idle.
    assert!(!state.cancel_user_bash());
}

#[test]
fn key_repeat_is_dispatched_but_release_is_not() {
    assert!(should_dispatch_key(KeyEventKind::Press));
    assert!(should_dispatch_key(KeyEventKind::Repeat));
    assert!(!should_dispatch_key(KeyEventKind::Release));
}

#[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"),
        "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_with_capabilities(
        &chat,
        &["read".into(), "bash".into(), "web_fetch".into()],
        &["rust-review".into(), "release".into()],
        &[
            "/project/.rpi/SYSTEM.md".into(),
            "/project/AGENTS.md".into(),
        ],
    );

    let lines = chat.render(80);
    let all: String = lines.join("\n");
    // Welcome title is "rpi" (accent bold) + "interactive TUI" (muted),
    // joined by an ANSI reset — strip ANSI before checking the substring.
    let plain = strip_ansi(&all);
    assert!(
        plain.contains("rpi"),
        "Welcome message not in chat container: {:?}",
        lines
    );
    assert!(plain.contains("Tools (3)"), "Tool count missing: {plain}");
    assert!(
        plain.contains("read · bash · web_fetch"),
        "Tool names missing: {plain}"
    );
    assert!(plain.contains("Skills (2)"), "Skill count missing: {plain}");
    assert!(plain.contains("Context (2)"));
    assert!(plain.contains("/project/.rpi/SYSTEM.md"));
    assert!(plain.contains("/project/AGENTS.md"));
    assert!(
        plain.contains("rust-review · release"),
        "Skill names missing: {plain}"
    );
}

#[test]
fn reload_updates_context_header_and_context_panel_without_stale_paths() {
    use rpi_harness::types::AgentHarnessResources;
    let chat = Arc::new(Container::new());
    let old = AgentHarnessResources {
        context_files: vec!["/old/SYSTEM.md".into()],
        ..Default::default()
    };
    let listing = add_welcome_message_with_capabilities(&chat, &[], &[], &old.context_files);
    let shared = Arc::new(Mutex::new(old));
    let fresh = AgentHarnessResources {
        context_files: vec!["/new/APPEND_SYSTEM.md".into(), "/new/CLAUDE.md".into()],
        ..Default::default()
    };
    update_resource_listing(&shared, Some(&listing), fresh.clone());
    let header = strip_ansi(&chat.render(120).join("\n"));
    assert!(header.contains("Context (2)"));
    assert!(header.contains("/new/APPEND_SYSTEM.md"));
    assert!(!header.contains("/old/SYSTEM.md"));
    assert_eq!(*shared.lock().unwrap(), fresh);
    let panel = Arc::new(Container::new());
    show_context_panel(&panel, &shared.lock().unwrap());
    let output = strip_ansi(&panel.render(120).join("\n"));
    assert!(output.contains("/new/CLAUDE.md"));
    assert!(!output.contains("/old/SYSTEM.md"));

    update_resource_listing(&shared, Some(&listing), Default::default());
    assert!(!strip_ansi(&chat.render(120).join("\n")).contains("Context"));
    let panel = Arc::new(Container::new());
    show_context_panel(&panel, &shared.lock().unwrap());
    assert!(strip_ansi(&panel.render(120).join("\n")).contains("no context files loaded"));
}

#[test]
fn welcome_header_renders_the_brand_mark() {
    let chat = Arc::new(Container::new());
    add_welcome_message(&chat);
    let lines: Vec<String> = chat.render(80).iter().map(|l| strip_ansi(l)).collect();
    let all = lines.join("\n");

    // The three-bar mark: the bottom row carries all three bars, and the
    // wordmark sits on its baseline next to the middle bar.
    assert!(
        lines.iter().any(|l| l.contains("██ ██ ██")),
        "brand mark missing: {all}"
    );
    assert!(
        all.contains("rpi"),
        "the mark must carry the product name: {all}"
    );

    // Regression guard for the layout bug this replaced: `π` is East-Asian
    // Ambiguous — width 1 normally, width 2 under a CJK locale — which
    // walked the old box borders out of alignment depending on the user's
    // system. The crab is deliberately wide but unambiguous, and `crate::brand`
    // tests pin its width so the padding cannot silently drift.
    assert!(
        !all.contains('π'),
        "the header must not use east-asian-ambiguous glyphs: {all}"
    );
}

#[test]
fn update_notices_render_inside_the_transcript() {
    let chat = Arc::new(Container::new());
    let report = crate::updates::UpdateReport {
        notices: vec![crate::updates::UpdateNotice {
            name: "rpi".into(),
            current: "0.1.10".into(),
            latest: "0.1.11".into(),
            command: "rpi update".into(),
        }],
        warnings: vec![crate::updates::UpdateWarning {
            message: "The previously scheduled rpi update failed: access denied".into(),
            command: "rpi update".into(),
        }],
    };

    add_update_notices(&chat, &report);

    assert_eq!(chat.child_count(), 1);
    let plain = strip_ansi(&chat.render(80).join("\n"));
    assert!(plain.contains("Update Failed"), "{plain}");
    assert!(
        plain.contains("rpi update failed: access denied"),
        "{plain}"
    );
    assert!(plain.contains("Update Available"), "{plain}");
    assert!(plain.contains("New version 0.1.11 is available"), "{plain}");
    assert!(plain.contains("rpi update"), "{plain}");
}

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

    add_update_notices(&chat, &crate::updates::UpdateReport::default());

    assert_eq!(chat.child_count(), 0);
}

#[test]
fn package_updates_render_without_an_rpi_update() {
    let chat = Arc::new(Container::new());
    let package_notice = crate::updates::UpdateNotice {
        name: "rpi-im-message".into(),
        current: "0.1.9".into(),
        latest: "0.1.10".into(),
        command: "rpi install rpi-im-message --force".into(),
    };

    for include_rpi in [false, true] {
        chat.clear();
        let mut report = crate::updates::UpdateReport {
            notices: vec![package_notice.clone()],
            warnings: Vec::new(),
        };
        if include_rpi {
            report.notices.push(crate::updates::UpdateNotice {
                name: "rpi".into(),
                current: "0.3.20".into(),
                latest: "0.3.21".into(),
                command: "rpi update".into(),
            });
        }

        add_update_notices(&chat, &report);

        assert_eq!(chat.child_count(), 1);
        let plain = strip_ansi(&chat.render(80).join("\n"));
        assert!(plain.contains("Package Update Available"), "{plain}");
        assert!(plain.contains("rpi-im-message 0.1.9 -> 0.1.10"), "{plain}");
        assert!(plain.contains(&package_notice.command), "{plain}");
        assert_eq!(plain.contains("rpi update"), include_rpi, "{plain}");
    }
}

#[test]
fn welcome_capabilities_show_empty_state() {
    let plain = strip_ansi(&welcome_capability_line("Skills", &[]));
    assert_eq!(plain, "Skills (0) none");
}

#[test]
fn completed_stream_reconciles_the_final_tail_before_detaching() {
    let component = Arc::new(AssistantMessageComponent::new(
        AssistantMessageOptions::default(),
    ));
    component.set_streaming(true);
    component.update_blocks(&[AssistantBlock::Text("partial response".into())]);

    let current = Arc::new(Mutex::new(Some(component.clone())));
    let cached = Mutex::new("partial response".to_string());
    let mut final_message = AssistantMessage::empty(rpi_ai::Api::Faux, "faux", "faux-model", 0);
    final_message.content = vec![Content::text(
        "partial response with the previously missing final tail",
    )];
    final_message.stop_reason = rpi_ai::types::StopReason::Stop;

    reconcile_streamed_assistant_completion(&current, &cached, Some(&final_message));

    assert!(current.lock().unwrap().is_none());
    assert_eq!(
        cached.lock().unwrap().as_str(),
        "partial response with the previously missing final tail"
    );
    let rendered = strip_ansi(&component.render(100).join("\n"));
    assert!(
        rendered.contains("previously missing final tail"),
        "{rendered}"
    );
}

/// 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 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 cursor = editor_cursor_offset(&editor, &text);
    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(' ');
    }
    let new_cursor = start + top.text.len();
    editor.set_text(&replaced);
    set_editor_cursor_offset(&editor, &replaced, new_cursor);
    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 multiline_autocomplete_preserves_row_and_column() {
    let editor = Arc::new(Editor::simple());
    editor.set_text("first\n/mo");
    editor.set_cursor(1, 3);

    let text = editor.get_text();
    assert_eq!(editor_cursor_offset(&editor, &text), 9);

    let replaced = "first\n/model";
    editor.set_text(replaced);
    set_editor_cursor_offset(&editor, replaced, 12);
    assert_eq!(editor.cursor_position(), (1, 6));
}

#[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("/changelog", "/changelog");
    resolves_to("/hotkeys", "/hotkeys");
    resolves_to("/model", "/model");
    resolves_to("/m", "/model"); // alias
    resolves_to("/provider", "/provider");
    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("/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",
        "/changelog",
        "/model",
        "/provider",
        "/session",
        "/theme",
        "/compact",
        "/copy",
        "/hotkeys",
        "/tools",
        "/images",
        "/thinking",
        "/usage",
    ] {
        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: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: 5,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: 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());

    // A running bash panel owns the visible spinner. The global loader is
    // hidden until the last concurrent bash tool completes, then restored
    // while the agent remains in the Working state.
    assert!(state.try_start_working());
    assert!(
        !state.try_start_working(),
        "a second submit must be rejected"
    );
    state.set_status(RunStatus::Idle);
    state.set_status(RunStatus::Working);
    // The active loader now renders inside the editor's top border.
    assert!(state.editor.working().is_some());
    assert_eq!(state.status_container.child_count(), 0);
    assert!(state.footer.get_status().is_empty());
    state.show_retry(3, 10, 8_000);
    let retry_status = strip_ansi(&state.status_container.render(80).join("\n"));
    assert!(retry_status.contains("Retrying (3/10)"));
    state.set_status(RunStatus::Working);
    {
        let mut bash = state.bash_components.lock().unwrap();
        bash.insert(
            "bash-1".into(),
            Arc::new(BashExecutionComponent::new("one")),
        );
        bash.insert(
            "bash-2".into(),
            Arc::new(BashExecutionComponent::new("two")),
        );
    }
    state.sync_working_loader_with_bash();
    assert_eq!(state.status_container.child_count(), 0);
    state.bash_components.lock().unwrap().remove("bash-1");
    state.sync_working_loader_with_bash();
    assert_eq!(state.status_container.child_count(), 0);
    state.bash_components.lock().unwrap().remove("bash-2");
    state.sync_working_loader_with_bash();
    // The editor-border indicator stays visible across bash panels, so the
    // status container stays empty.
    assert_eq!(state.status_container.child_count(), 0);
    assert!(state.editor.working().is_some());

    state.set_status(RunStatus::Aborting);
    assert_eq!(state.status_container.child_count(), 0);
    assert!(!state.loader.is_running());
}

#[test]
fn fresh_launch_does_not_restore_old_history() {
    let fresh = Args::default();
    assert!(!launch_restores_history(&fresh));

    let continued = Args {
        continue_session: true,
        ..Args::default()
    };
    assert!(launch_restores_history(&continued));

    let selected = Args {
        session: Some("session-id".into()),
        ..Args::default()
    };
    assert!(launch_restores_history(&selected));
}

#[test]
fn context_badge_ignores_aborted_and_error_turns() {
    use rpi_ai::types::{Api, StopReason, Usage};

    let footer = Arc::new(FooterComponent::new());
    footer.set_context_window(100_000);

    // A real response fills in the percent (`?` -> `25.0%/100k`).
    let mut ok = rpi_ai::AssistantMessage::empty(Api::AnthropicMessages, "anthropic", "m", 0);
    ok.stop_reason = StopReason::Stop;
    ok.usage = Usage {
        input: 25_000,
        ..Usage::zero()
    };
    record_context_usage(&footer, &ok);
    let stats = strip_ansi(&footer.render(120).join("\n"));
    assert!(stats.contains("25.0%/100k"), "stats: {stats}");

    // An aborted turn must not clobber the last good value.
    let mut aborted = rpi_ai::AssistantMessage::empty(Api::AnthropicMessages, "anthropic", "m", 0);
    aborted.stop_reason = StopReason::Aborted;
    aborted.usage = Usage {
        input: 90_000,
        ..Usage::zero()
    };
    record_context_usage(&footer, &aborted);
    let stats = strip_ansi(&footer.render(120).join("\n"));
    assert!(stats.contains("25.0%/100k"), "stats: {stats}");

    // An errored turn likewise (its usage is not a real measurement).
    let mut errored = rpi_ai::AssistantMessage::empty(Api::AnthropicMessages, "anthropic", "m", 0);
    errored.stop_reason = StopReason::Error;
    errored.usage = Usage {
        input: 90_000,
        ..Usage::zero()
    };
    record_context_usage(&footer, &errored);
    let stats = strip_ansi(&footer.render(120).join("\n"));
    assert!(stats.contains("25.0%/100k"), "stats: {stats}");
}

#[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 model_selector_items_are_deduplicated_and_provider_qualified() {
    use rpi_ai::{Api, Model};

    let mut gateway = Model::new(
        "gpt-5.6-sol",
        "GPT 5.6 Sol",
        Api::OpenaiCompletions,
        "routeryo-copy",
        "https://gateway.example.com",
    );
    let duplicate = gateway.clone();
    let anthropic = Model::new(
        "claude-sonnet-5",
        "Claude Sonnet 5",
        Api::AnthropicMessages,
        "anthropic",
        "https://api.anthropic.com",
    );
    gateway.headers = Some(std::collections::BTreeMap::from([(
        "authorization".into(),
        "Bearer test".into(),
    )]));

    let items = model_selector_items(&[gateway, duplicate, anthropic], "gpt-5.6-sol");
    assert_eq!(items.len(), 2);
    // Value is provider-qualified so a bare id shared across endpoints resolves
    // to the right provider.
    assert_eq!(items[0].value, "routeryo-copy/gpt-5.6-sol");
    assert_eq!(items[0].label, "GPT 5.6 Sol");
    assert_eq!(
        items[0].description.as_deref(),
        Some("routeryo-copy/gpt-5.6-sol (current)")
    );
    assert_eq!(
        items[1].description.as_deref(),
        Some("anthropic/claude-sonnet-5")
    );
}

#[test]
fn model_selector_search_text_covers_provider_name_and_qualified_id() {
    use rpi_ai::{Api, Model};

    let anthropic = Model::new(
        "claude-sonnet-5",
        "Claude Sonnet 5",
        Api::AnthropicMessages,
        "anthropic",
        "https://api.anthropic.com",
    );
    let items = model_selector_items(&[anthropic], "");
    let search = items[0].search_key();
    // Mirrors native `getModelSelectorSearchText`: provider-prefixed first,
    // then the display name.
    assert!(search.starts_with("anthropic anthropic/claude-sonnet-5"));
    assert!(search.contains("Claude Sonnet 5"), "{search}");

    // A provider query and a display-name query both match through the
    // real fuzzy filter used by the searchable selector.
    use rpi_tui::fuzzy_filter;
    for query in ["anthropic", "sonnet", "Claude Sonnet", "claude-sonnet-5"] {
        let matched = fuzzy_filter(&items, query, |item| item.search_key());
        assert_eq!(matched.len(), 1, "query {query:?} matched nothing");
    }
}

#[test]
fn model_selector_match_accepts_bare_and_qualified_ids() {
    use rpi_ai::{Api, Model};

    let gateway = Model::new(
        "gpt-5.6-sol",
        "GPT 5.6 Sol",
        Api::OpenaiCompletions,
        "routeryo-copy",
        "https://gateway.example.com",
    );
    let anthropic = Model::new(
        "claude-sonnet-5",
        "Claude Sonnet 5",
        Api::AnthropicMessages,
        "anthropic",
        "https://api.anthropic.com",
    );
    let catalog = [gateway, anthropic];
    assert_eq!(
        find_model_selector_match(&catalog, "gpt-5.6-sol")
            .unwrap()
            .provider,
        "routeryo-copy"
    );
    assert_eq!(
        find_model_selector_match(&catalog, "routeryo-copy/gpt-5.6-sol")
            .unwrap()
            .id,
        "gpt-5.6-sol"
    );
    assert_eq!(
        find_model_selector_match(&catalog, "anthropic/claude-sonnet-5")
            .unwrap()
            .id,
        "claude-sonnet-5"
    );
    assert!(find_model_selector_match(&catalog, "other/gpt-5.6-sol").is_none());
}

#[test]
fn provider_input_canonicalization_exact_then_case_insensitive_unique() {
    use rpi_ai::{Api, Model};

    let anthropic = Model::new(
        "claude-sonnet-5",
        "Claude Sonnet 5",
        Api::AnthropicMessages,
        "anthropic",
        "https://api.anthropic.com",
    );
    let gateway = Model::new(
        "gpt-5.6-sol",
        "GPT 5.6 Sol",
        Api::OpenaiCompletions,
        "MyGateway",
        "https://gateway.example.com",
    );
    let catalog = [anthropic, gateway];

    assert_eq!(
        canonicalize_provider_input("anthropic", &catalog).unwrap(),
        "anthropic"
    );
    assert_eq!(
        canonicalize_provider_input("ANTHROPIC", &catalog).unwrap(),
        "anthropic"
    );
    assert_eq!(
        canonicalize_provider_input("mygateway", &catalog).unwrap(),
        "MyGateway"
    );
    assert!(canonicalize_provider_input("nope", &catalog).is_err());
}

#[test]
fn provider_form_saves_provider_to_models_json() {
    with_isolated_config_dir(|| {
        let form = ProviderFormState {
            step: ProviderFormStep::ModelName,
            id: "openrouter".into(),
            api: "openai-completions".into(),
            base_url: "https://openrouter.ai/api/v1".into(),
            api_key: "$OPENROUTER_API_KEY".into(),
            model_id: "claude-sonnet".into(),
            model_name: "Claude Sonnet".into(),
        };
        let note = save_provider_from_form(&form).unwrap();
        assert!(note.contains("openrouter"), "{note}");

        let cfg = crate::config::load_models_config().unwrap();
        let provider = cfg.providers.get("openrouter").expect("provider written");
        assert_eq!(provider.api.as_deref(), Some("openai-completions"));
        assert_eq!(
            provider.base_url.as_deref(),
            Some("https://openrouter.ai/api/v1")
        );
        assert_eq!(provider.api_key.as_deref(), Some("$OPENROUTER_API_KEY"));
        assert_eq!(provider.models.len(), 1);
        assert_eq!(provider.models[0].id, "claude-sonnet");
        assert_eq!(provider.models[0].name.as_deref(), Some("Claude Sonnet"));

        // The duplicate-id guard sees the provider we just wrote.
        assert!(provider_id_exists("openrouter"));
        assert!(!provider_id_exists("nope"));
    });
}

#[test]
fn provider_url_validation_requires_http_scheme() {
    assert!(is_valid_provider_url("https://api.example.com/v1"));
    assert!(is_valid_provider_url("http://localhost:8080"));
    assert!(!is_valid_provider_url("api.example.com/v1"));
    assert!(!is_valid_provider_url(""));
}

#[test]
fn remove_provider_deletes_from_models_json() {
    with_isolated_config_dir(|| {
        let form = ProviderFormState {
            step: ProviderFormStep::ModelName,
            id: "openrouter".into(),
            api: "openai-completions".into(),
            base_url: "https://openrouter.ai/api/v1".into(),
            api_key: "$OPENROUTER_API_KEY".into(),
            model_id: "claude-sonnet".into(),
            model_name: String::new(),
        };
        save_provider_from_form(&form).unwrap();
        assert!(provider_id_exists("openrouter"));

        let note = remove_provider("openrouter").unwrap();
        assert!(note.contains("openrouter"), "{note}");
        assert!(!provider_id_exists("openrouter"));

        // Built-ins / unknown ids cannot be removed.
        assert!(remove_provider("anthropic").is_err());
        assert!(remove_provider("nope").is_err());
    });
}

/// Isolate the config dir (and serialize against other env-touching tests)
/// while `body` runs, then restore the previous value.
fn with_isolated_config_dir<T>(body: impl FnOnce() -> T) -> T {
    let _guard = crate::config::test_support::env_lock().lock().unwrap();
    let prev = std::env::var_os(crate::config::CONFIG_DIR_ENV);
    let tmp = tempfile::tempdir().unwrap();
    std::env::set_var(crate::config::CONFIG_DIR_ENV, tmp.path());
    let result = body();
    match prev {
        Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
        None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
    }
    result
}

#[test]
fn provider_selector_items_cover_builtin_providers() {
    with_isolated_config_dir(|| {
        let items = provider_selector_items();
        let ids: Vec<&str> = items.iter().map(|item| item.value.as_str()).collect();
        assert!(
            ids.contains(&"anthropic"),
            "built-in anthropic provider missing: {ids:?}"
        );
        assert!(
            ids.contains(&"openai"),
            "built-in openai provider missing: {ids:?}"
        );
        // Every row advertises its model count, origin, and key status, so a
        // built-in catalog entry can't be mistaken for a configured one.
        assert!(items.iter().all(|item| {
            item.description
                .as_deref()
                .is_some_and(|d| d.contains("model(s)") && d.contains("内置") && d.contains("key"))
        }));
    });
}

#[test]
fn set_default_provider_persists_provider_and_a_matching_model() {
    with_isolated_config_dir(|| {
        let note = set_default_provider("openai").unwrap();
        assert!(
            note.contains("openai"),
            "note should name the provider: {note}"
        );

        let settings = crate::settings::load_settings().unwrap();
        assert_eq!(settings.default_provider.as_deref(), Some("openai"));
        assert!(
            settings.default_model.is_some(),
            "a matching default model must be saved so the choice resolves on restart"
        );

        // Unknown provider → error, and nothing is persisted.
        assert!(set_default_provider("does-not-exist").is_err());
    });
}

#[test]
fn assistant_error_text_keeps_terminal_provider_diagnostic_visible() {
    use rpi_ai::types::{AssistantMessage, AssistantRole, StopReason, Usage};

    let failed = AssistantMessage {
        role: AssistantRole,
        content: Vec::new(),
        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::Error,
        deferred: None,
        error_message: Some("upstream returned 401".into()),
        raw_stop_reason: None,
        end_turn: None,
        timestamp: 0,
    };
    assert_eq!(
        assistant_error_text(&failed).as_deref(),
        Some("upstream returned 401")
    );

    let mut no_detail = failed;
    no_detail.error_message = Some("  ".into());
    assert_eq!(
        assistant_error_text(&no_detail).as_deref(),
        Some("Provider request failed.")
    );

    let mut aborted = no_detail;
    aborted.stop_reason = StopReason::Aborted;
    aborted.error_message = Some("abort error: Request aborted".into());
    assert_eq!(
        assistant_error_text(&aborted).as_deref(),
        Some("abort error: Request aborted")
    );

    aborted.error_message = None;
    assert_eq!(
        assistant_error_text(&aborted).as_deref(),
        Some("Request aborted.")
    );
}

#[test]
fn sanitize_error_message_keeps_diagnostics_without_terminal_controls() {
    assert_eq!(
        sanitize_error_message("405\r\nMethod Not Allowed\x1b[2J"),
        "405\nMethod Not Allowed"
    );
    assert_eq!(sanitize_error_message("\0\tmessage"), "\tmessage");
    assert_eq!(sanitize_error_message("   "), "Provider request failed.");
    let long = "x".repeat(20_000);
    let cleaned = sanitize_error_message(&long);
    assert!(cleaned.chars().count() <= 16 * 1024 + 1);
    assert!(cleaned.ends_with('…'));
}

#[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_cycle_prev_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")];
    // Previous before "b" is "a"; before "a" wraps to "c".
    assert_eq!(cycle_prev_model(&catalog, "b").unwrap().id, "a");
    assert_eq!(cycle_prev_model(&catalog, "a").unwrap().id, "c");
    // An unknown current id falls back to the first model.
    assert_eq!(cycle_prev_model(&catalog, "zzz").unwrap().id, "a");
    // Empty catalog yields None.
    let empty: Vec<Model> = vec![];
    assert!(cycle_prev_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: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: 5,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: 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: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: 5,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: 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: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: 5,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: 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: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: 5,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: 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}"
    );
}

/// Build a `TuiState` for autocomplete tests (autocomplete providers are
/// installed by each test).
fn autocomplete_test_state(max_visible: usize) -> Arc<TuiState> {
    Arc::new(TuiState {
        current_assistant: Arc::new(std::sync::Mutex::new(None)),
        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
        hide_thinking: Arc::new(std::sync::Mutex::new(false)),
        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(false)),
        show_terminal_progress: true,
        status: std::sync::Mutex::new(RunStatus::Idle),
        ext_status: rpi_extensions::ExtensionStatusMailbox::new(),
        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
        editor_text: rpi_extensions::EditorTextMailbox::new(),
        auto_send: std::sync::Mutex::new(None),
        last_editor_text: std::sync::Mutex::new(String::new()),
        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
        js_preparation_cancel: std::sync::Mutex::new(None),
        user_bash_cancel: std::sync::Mutex::new(None),
        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
        footer: Arc::new(FooterComponent::new()),
        status_container: Arc::new(Container::new()),
        chat_container: Arc::new(Container::new()),
        loader: Arc::new(Loader::new()),
        editor: Arc::new(Editor::simple()),
        last_assistant_text: std::sync::Mutex::new(String::new()),
        active_selector: std::sync::Mutex::new(None),
        provider_form: std::sync::Mutex::new(None),
        active_provider_input: std::sync::Mutex::new(None),
        active_provider_select: std::sync::Mutex::new(None),
        active_extension_editor: std::sync::Mutex::new(None),
        active_extension_input: std::sync::Mutex::new(None),
        active_extension_cancel: std::sync::Mutex::new(None),
        autocomplete: AutocompleteManager::new(),
        autocomplete_container: Arc::new(Container::new()),
        autocomplete_max_visible: max_visible,
        autocomplete_selection: std::sync::Mutex::new(0),
        pending_images: std::sync::Mutex::new(Vec::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),
        cache_miss_notices: std::sync::Mutex::new(false),
        history: std::sync::Mutex::new(Vec::new()),
        history_index: std::sync::Mutex::new(-1),
        history_draft: std::sync::Mutex::new(None),
        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
        scoped_edit: std::sync::Mutex::new(None),
        markdown_transformer: Arc::new(std::sync::Mutex::new(None)),
        extension_claimed_keys: Mutex::new(Default::default()),
        extension_session: Arc::new(std::sync::Mutex::new(
            rpi_extensions::ExtensionSession::none(),
        )),
        search: Arc::new(AltScreenSearch::new()),
        search_bar: Arc::new(SearchBar::new()),
        pending_container: Arc::new(Container::new()),
        dequeue_hint: String::new(),
        pending_snapshot: std::sync::Mutex::new(
            rpi_harness::agent_harness::QueuedMessages::default(),
        ),
        selection_start: std::sync::Mutex::new(None),
        selection_end: std::sync::Mutex::new(None),
    })
}

#[test]
fn autocomplete_navigation_reaches_beyond_visible_window() {
    let state = autocomplete_test_state(5);
    let commands: Vec<rpi_tui::SlashCommand> = (0..7)
        .map(|i| rpi_tui::SlashCommand {
            name: format!("/choice{i}"),
            description: format!("choice {i}"),
        })
        .collect();
    state
        .autocomplete
        .set_provider(Arc::new(SlashCommandAutocompleteProvider::new(commands)));
    let editor = Arc::new(Editor::simple());
    editor.set_text("/");
    editor.set_cursor(0, 1);
    refresh_autocomplete(&state, &editor);

    // 5 × ↓ must move the highlight to index 5 (the 6th item), past the
    // 5-row visible window (previously it clamped at max_visible - 1 = 4).
    for _ in 0..5 {
        assert!(navigate_autocomplete(&state, &editor, 1));
    }
    assert_eq!(*state.autocomplete_selection.lock().unwrap(), 5);
    assert!(accept_top_suggestion(&state, &editor));
    assert!(
        editor.get_text().starts_with("/choice5"),
        "Tab should accept the highlighted 6th item, got {}",
        editor.get_text()
    );
}

#[test]
fn autocomplete_navigation_does_not_swallow_plain_draft_arrows() {
    let state = autocomplete_test_state(5);
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("docs")).unwrap();
    let mut combined = CombinedAutocompleteProvider::new();
    combined.add_provider(Arc::new(FilePathAutocompleteProvider::with_root(
        tmp.path().to_path_buf(),
    )));
    state.autocomplete.set_provider(Arc::new(combined));

    let editor = Arc::new(Editor::simple());
    editor.set_text("first line\nplease check docs");
    editor.set_cursor(1, 18);
    // A bare-word path completion (`docs`) must not consume ↑ — the editor
    // owns cursor movement outside explicit `/` or `@` completion.
    assert!(!navigate_autocomplete(&state, &editor, -1));
}

#[test]
fn autocomplete_navigation_handles_leading_at_file_completion() {
    let state = autocomplete_test_state(5);
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("docs_a")).unwrap();
    std::fs::create_dir_all(tmp.path().join("docs_b")).unwrap();
    state
        .autocomplete
        .set_provider(Arc::new(FilePathAutocompleteProvider::with_root(
            tmp.path().to_path_buf(),
        )));
    let editor = Arc::new(Editor::simple());
    editor.set_text("@do");
    editor.set_cursor(0, 3);
    refresh_autocomplete(&state, &editor);
    // The path provider keeps `@` and puts `start` after it; ↓ must still work.
    assert!(navigate_autocomplete(&state, &editor, 1));
    assert_eq!(*state.autocomplete_selection.lock().unwrap(), 1);
    assert!(accept_top_suggestion(&state, &editor));
    assert!(
        editor.get_text().starts_with("@docs_"),
        "@ plus the picked candidate must be inserted, got {}",
        editor.get_text()
    );
}

#[test]
fn autocomplete_navigation_handles_at_file_after_chinese_draft() {
    let state = autocomplete_test_state(5);
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("docs_a")).unwrap();
    std::fs::create_dir_all(tmp.path().join("docs_b")).unwrap();
    state
        .autocomplete
        .set_provider(Arc::new(FilePathAutocompleteProvider::with_root(
            tmp.path().to_path_buf(),
        )));
    let editor = Arc::new(Editor::simple());
    editor.set_text("请查看 @do");
    editor.set_cursor(0, 13);
    refresh_autocomplete(&state, &editor);
    assert!(navigate_autocomplete(&state, &editor, 1));
    assert!(accept_top_suggestion(&state, &editor));
    assert!(
        editor.get_text().starts_with("请查看 @docs_"),
        "draft, @, and the picked candidate must be preserved, got {}",
        editor.get_text()
    );
}

#[test]
fn configured_key_parser_supports_native_notation() {
    let combo = parse_configured_key("Ctrl+G").expect("ctrl+g should parse");
    assert_eq!(combo.code, KeyCode::Char('g'));
    assert!(combo.modifiers.contains(KeyModifiers::CONTROL));
    let combo = parse_configured_key("shift+tab").expect("shift+tab should parse");
    assert_eq!(combo.code, KeyCode::BackTab);
}

#[test]
fn double_escape_trigger_has_half_second_window() {
    let now = std::time::Instant::now();
    assert!(!double_escape_trigger(None, now));
    assert!(double_escape_trigger(
        Some(now - std::time::Duration::from_millis(500)),
        now
    ));
    assert!(!double_escape_trigger(
        Some(now - std::time::Duration::from_millis(501)),
        now
    ));
}

#[test]
fn ctrl_c_clears_first_and_only_exits_inside_the_window() {
    // upstream's `handleCtrlC`: a lone press clears the editor and never
    // quits by itself; only a second press within 500ms exits. It must not
    // abort — Esc owns that.
    let now = std::time::Instant::now();
    assert_eq!(ctrl_c_action(None, now), CtrlCAction::Clear);
    assert_eq!(
        ctrl_c_action(Some(now - std::time::Duration::from_millis(500)), now),
        CtrlCAction::Exit
    );
    // A slower second press is a fresh "clear", not a quit.
    assert_eq!(
        ctrl_c_action(Some(now - std::time::Duration::from_millis(501)), now),
        CtrlCAction::Clear
    );
}

#[test]
fn pasted_multi_line_block_becomes_one_prompt_not_many() {
    // End-to-end shape of the fix: replay the key stream a Windows paste
    // produces ("l1\nl2\nl3" + a trailing Enter) through the same pieces
    // the key loop uses — the burst discriminator for each Enter and the
    // editor for the text — and assert that *no* submit fired while the
    // block arrived, then exactly one submit on the user's own Enter.
    use std::sync::atomic::{AtomicUsize, Ordering};

    let editor = rpi_tui::Editor::simple();
    let submits = Arc::new(AtomicUsize::new(0));
    let submits_for_cb = submits.clone();
    editor.on_submit(Arc::new(move |_text: &str| {
        submits_for_cb.fetch_add(1, Ordering::SeqCst);
    }));

    // Every pasted key is delivered back-to-back, so `now` is unchanged and
    // the console queue is never empty until the paste is drained.
    let now = std::time::Instant::now();
    let mut last_text_key_at: Option<std::time::Instant> = None;
    let block = ["l1", "l2", "l3"];
    for (index, line) in block.iter().enumerate() {
        for ch in line.chars() {
            editor.insert(&ch.to_string());
            last_text_key_at = Some(now);
        }
        if index + 1 < block.len() {
            // The pasted newline: more input is still queued behind it.
            let more_queued = true;
            assert!(
                enter_is_paste_burst(last_text_key_at, now, more_queued),
                "pasted newline {index} must not submit"
            );
            editor.insert("\n");
            last_text_key_at = Some(now);
        }
    }
    assert_eq!(editor.get_text(), "l1\nl2\nl3");
    assert_eq!(submits.load(Ordering::SeqCst), 0, "paste must not submit");

    // The user's own Enter: a real gap, nothing queued.
    let typed_at = now + PASTE_BURST_GAP + std::time::Duration::from_millis(80);
    assert!(!enter_is_paste_burst(last_text_key_at, typed_at, false));
    editor.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Enter,
        KeyModifiers::NONE,
    ));
    assert_eq!(
        submits.load(Ordering::SeqCst),
        1,
        "typed Enter submits once"
    );
}

#[test]
fn pasted_win_crlf_text_has_no_stray_carriage_returns() {
    // A Windows paste delivers CRLF; the editor must fold it to LF so the
    // rendered block is clean and the cursor arithmetic stays sound.
    let editor = rpi_tui::Editor::simple();
    editor.insert("alpha\r\nbeta\r\n");
    assert_eq!(editor.get_text(), "alpha\nbeta\n");
    assert!(!editor.get_text().contains('\r'));
}

#[test]
fn pasted_enter_is_not_a_submit() {
    let now = std::time::Instant::now();

    // Queued input behind the Enter => paste, regardless of history.
    assert!(enter_is_paste_burst(None, now, true));

    // Enter immediately after pasted characters => paste (also covers a
    // paste whose final line ends with a newline, where nothing is queued).
    assert!(enter_is_paste_burst(
        Some(now - std::time::Duration::from_millis(1)),
        now,
        false
    ));
    assert!(enter_is_paste_burst(
        Some(now - (PASTE_BURST_GAP - std::time::Duration::from_millis(1))),
        now,
        false
    ));

    // A typed Enter: nothing queued and a real gap since the last key.
    assert!(!enter_is_paste_burst(None, now, false));
    assert!(!enter_is_paste_burst(
        Some(now - PASTE_BURST_GAP),
        now,
        false
    ));
    assert!(!enter_is_paste_burst(
        Some(now - std::time::Duration::from_millis(120)),
        now,
        false
    ));
}

#[test]
fn paste_probe_ignores_the_enter_keys_own_release() {
    use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
    let release =
        KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Release);

    // Windows queues press+release together over RDP: the release behind a
    // lone Enter must NOT count as queued paste content.
    let mut queued = vec![Event::Key(release)].into_iter();
    let (more, stashed) = probe_paste_input(None, || queued.next());
    assert!(!more, "a key release alone is not queued paste input");
    assert!(stashed.is_none());

    // A real follow-up key (the next pasted line) IS queued input and is
    // stashed for the caller instead of being lost.
    let next = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE);
    let mut queued = vec![Event::Key(release), Event::Key(next)].into_iter();
    let (more, stashed) = probe_paste_input(None, || queued.next());
    assert!(more, "a queued key press is paste continuation");
    assert!(matches!(stashed, Some(Event::Key(_))));

    // Nothing queued at all.
    let (more, stashed) = probe_paste_input(None, || None);
    assert!(!more);
    assert!(stashed.is_none());

    // An already-stashed event counts as queued input, without reading more.
    let (more, stashed) = probe_paste_input(Some(Event::Key(next)), || {
        panic!("must not read when an event is already stashed")
    });
    assert!(more);
    assert!(matches!(stashed, Some(Event::Key(_))));
}

// ---- ask_user TUI bridge ----

#[test]
fn ask_user_prompt_parser_supports_flat_and_questions_shapes() {
    let flat = rpi_extensions::UiDialogRequest {
        request_id: "r1".into(),
        tool_call_id: Some("c1".into()),
        ui: serde_json::json!({
            "kind": "selector",
            "id": "proxy_port",
            "header": "Proxy",
            "question": "端口?",
            "options": [{"title": "7890", "description": "text"}, {"title": "7897"}],
            "allowMultiple": true,
            "allowFreeform": false,
            "suggest": "1080"
        }),
        raw: serde_json::json!({}),
    };
    let prompt = parse_ask_user_prompt(&flat);
    assert_eq!(prompt.question_id, "proxy_port");
    assert_eq!(prompt.header.as_deref(), Some("Proxy"));
    assert_eq!(prompt.options.len(), 2);
    assert_eq!(prompt.options[0].1.as_deref(), Some("text"));
    assert!(prompt.allow_multiple);
    assert!(!prompt.allow_freeform);
    assert_eq!(prompt.suggest.as_deref(), Some("1080"));

    let alias = rpi_extensions::UiDialogRequest {
        ui: serde_json::json!({
            "questions": [{"id": "q", "question": "Q?", "options": []}]
        }),
        ..flat.clone()
    };
    let prompt = parse_ask_user_prompt(&alias);
    assert_eq!(prompt.question_id, "q");
    assert!(prompt.allow_freeform, "no options defaults to freeform");

    let confirm = rpi_extensions::UiDialogRequest {
        ui: serde_json::json!({"kind": "confirm", "question": "Go?"}),
        ..flat.clone()
    };
    let prompt = parse_ask_user_prompt(&confirm);
    assert_eq!(prompt.kind, "confirm");
    assert_eq!(prompt.options.len(), 2);
    assert_eq!(prompt.options[0].0, "Yes");
}

#[test]
fn ask_user_bridge_answers_and_cancels_by_request_id() {
    let mailbox = rpi_extensions::UiDialogMailbox::new();
    mailbox.attach();
    let bridge = AskUserBridge::new(mailbox.clone());

    // Two concurrent requests must not cross answers.
    mailbox
        .handle(serde_json::json!({
            "op": "open", "requestId": "r1", "toolCallId": "call-r1",
            "ui": {"kind": "input", "question": "Port?"}
        }))
        .unwrap();
    mailbox
        .handle(serde_json::json!({
            "op": "open", "requestId": "r2", "toolCallId": "call-r2",
            "ui": {"kind": "input", "question": "Level?"}
        }))
        .unwrap();

    let first = bridge.take_pending().expect("r1 visible");
    assert_eq!(first.request_id, "r1");
    assert!(
        bridge.take_pending().is_none(),
        "only one request occupies the input slot"
    );
    bridge.respond("r1", serde_json::json!({"text": "7897"}));
    assert_eq!(mailbox.poll("r1").unwrap()["answer"]["text"], "7897");

    let second = bridge.take_pending().expect("r2 visible");
    assert_eq!(second.request_id, "r2");
    bridge.cancel("r2");
    assert_eq!(mailbox.poll("r2").unwrap()["status"], "cancelled");

    // cancel_all drops anything still queued.
    mailbox
        .handle(serde_json::json!({
            "op": "open", "requestId": "r3",
            "ui": {"kind": "input", "question": "X?"}
        }))
        .unwrap();
    bridge.cancel_all();
    assert_eq!(mailbox.poll("r3").unwrap()["status"], "cancelled");

    // A detached mailbox rejects new prompts (headless contract).
    bridge.shutdown();
    assert!(mailbox
        .handle(serde_json::json!({
            "op": "open", "requestId": "r4", "ui": {"kind": "input"}
        }))
        .is_err());
}