arabica-cli 0.13.1

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

use std::collections::{BTreeMap, VecDeque};
use std::io;
use std::path::Path;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::host::HostModel;
use arabica_model::{ContentBlock, RuntimeItem, RuntimeRole};
use arabica_protocol::{
    Command, CommandEnvelope, CommandId, Event, EventEnvelope, ToolPermissionOutcome,
    ToolPermissionScope, ToolPermissionSource,
};
use arabica_provider::{ApiProviderConfig, ModelProgress, ModelProgressSink};
use arabica_runtime::BlendRoutingPolicy;
use arabica_runtime::{
    PermissionDecision, PermissionRequest, RunCancellation, RunControl, ToolPermissionGate,
};
use arabica_session::{DispatchControl, EventVisibility, FanOutObserver, SessionEventObserver};
use crossterm::SynchronizedUpdate as _;
use crossterm::event::{self, Event as InputEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::{DefaultTerminal, Frame, Terminal};
use similar::{ChangeTag, TextDiff};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use crate::checkpoint::{self, WriteCheckpoint};
use crate::context;
use crate::host::workspace_id_for;
use crate::interactive::{self, InteractiveOptions, InteractiveSession};

/// Diff lines shown before folding when verbose mode is off.
const DIFF_FOLD_LINES: usize = 12;

// ---------------------------------------------------------------------------
// Theme: semantic color roles for the transcript
//
// Every role uses named ANSI colors (or Color::Reset, the terminal's own
// foreground), never hardcoded RGB, so the terminal's configured theme
// maps them and light/dark terminals both stay readable. Roles:
//   base     — assistant prose (inherits the terminal foreground)
//   user     — the user's own messages
//   tool     — tool-call lines and permission prompts (distinct at a glance)
//   muted    — thinking, hints, status bar, folded output (recedes)
//   added / removed — diff insertions and deletions
//   artifact — results and products: ✓ completions, file summaries
//   error    — failures
// ---------------------------------------------------------------------------
mod theme {
    use ratatui::style::{Color, Modifier, Style};

    pub(crate) fn base() -> Style {
        Style::default().fg(Color::Reset)
    }

    pub(crate) fn user() -> Style {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    }

    pub(crate) fn tool() -> Style {
        Style::default().fg(Color::Yellow)
    }

    /// A finished tool call: green check.
    pub(crate) fn tool_ok() -> Style {
        Style::default().fg(Color::Green)
    }

    /// Dimmed terminal foreground rather than ANSI bright black, which
    /// several schemes (Solarized Dark among them) paint as the background.
    pub(crate) fn muted() -> Style {
        Style::default().add_modifier(Modifier::DIM)
    }

    pub(crate) fn added() -> Style {
        Style::default().fg(Color::Green)
    }

    pub(crate) fn removed() -> Style {
        Style::default().fg(Color::Red)
    }

    pub(crate) fn artifact() -> Style {
        Style::default().fg(Color::Cyan)
    }

    pub(crate) fn error() -> Style {
        Style::default().fg(Color::Red)
    }
}

// ---------------------------------------------------------------------------
// Buffered output helpers
// ---------------------------------------------------------------------------

/// Copies `line` into an owned `Line`, preserving both span styles and the
/// line style. `Line::from(spans)` would drop `line.style`, which is where
/// `wrap_styled`/`Line::styled` put the theme color of most transcript rows.
fn paint_row(line: &Line) -> Line<'static> {
    let mut rebuilt = Line::from(
        line.spans
            .iter()
            .map(|span| Span::styled(span.content.to_string(), span.style))
            .collect::<Vec<_>>(),
    );
    rebuilt.style = line.style;
    rebuilt
}

struct EditorLayout {
    rows: Vec<String>,
    cursor_row: usize,
    cursor_column: usize,
}

fn layout_editor(input: &str, cursor: usize, width: usize) -> EditorLayout {
    let width = width.max(1);
    let cursor = cursor.min(input.len());
    let prompt = if width >= 2 { "❯ " } else { "❯" };
    let indent = " ".repeat(2.min(width));
    let mut rows = vec![prompt.to_owned()];
    let mut row = 0;
    let mut column = UnicodeWidthStr::width(prompt).min(width);
    let mut byte_offset = 0;
    let mut cursor_position = (0, column);
    for grapheme in input.graphemes(true) {
        if grapheme == "\n" {
            if cursor == byte_offset {
                cursor_position = (row, column);
            }
            rows.push(indent.clone());
            row += 1;
            column = UnicodeWidthStr::width(indent.as_str());
            byte_offset += grapheme.len();
            if cursor == byte_offset {
                cursor_position = (row, column);
            }
            continue;
        }
        let grapheme_width = UnicodeWidthStr::width(grapheme);
        let row_indent = if row == 0 {
            UnicodeWidthStr::width(prompt)
        } else {
            UnicodeWidthStr::width(indent.as_str())
        };
        if column + grapheme_width > width && column > row_indent {
            rows.push(indent.clone());
            row += 1;
            column = UnicodeWidthStr::width(indent.as_str());
        }
        if cursor == byte_offset {
            cursor_position = (row, column);
        }
        rows[row].push_str(grapheme);
        column += grapheme_width;
        byte_offset += grapheme.len();
        if cursor == byte_offset {
            cursor_position = (row, column);
        }
    }
    EditorLayout {
        rows,
        cursor_row: cursor_position.0,
        cursor_column: cursor_position.1,
    }
}

fn editor_has_multiple_visual_rows(input: &str, cursor: usize, width: usize) -> bool {
    layout_editor(input, cursor, width).rows.len() > 1
}

fn composer_height(viewport_height: usize, editor_rows: usize) -> usize {
    editor_rows.min((viewport_height / 3).clamp(1, 8)).max(1)
}

fn visual_row_positions(input: &str, width: usize) -> Vec<(usize, usize, usize)> {
    let width = width.max(1);
    let prompt = if width >= 2 { "❯ " } else { "❯" };
    let indent = UnicodeWidthStr::width("  ").min(width);
    let mut positions = vec![(0, 0, UnicodeWidthStr::width(prompt).min(width))];
    let mut row = 0;
    let mut column = UnicodeWidthStr::width(prompt).min(width);
    let mut byte_offset = 0;
    for grapheme in input.graphemes(true) {
        if grapheme == "\n" {
            byte_offset += 1;
            row += 1;
            column = indent;
            positions.push((byte_offset, row, column));
            continue;
        }
        let grapheme_width = UnicodeWidthStr::width(grapheme);
        let row_indent = if row == 0 {
            UnicodeWidthStr::width(prompt).min(width)
        } else {
            indent
        };
        if column + grapheme_width > width && column > row_indent {
            row += 1;
            column = indent;
            if positions
                .last()
                .is_some_and(|position| position.0 == byte_offset)
            {
                *positions.last_mut().expect("checked above") = (byte_offset, row, column);
            } else {
                positions.push((byte_offset, row, column));
            }
        }
        byte_offset += grapheme.len();
        column += grapheme_width;
        positions.push((byte_offset, row, column));
    }
    positions
}

fn vertical_cursor_move(
    input: &str,
    cursor: usize,
    up: bool,
    goal_column: Option<usize>,
    width: usize,
) -> Option<(usize, usize)> {
    let positions = visual_row_positions(input, width);
    let current = positions
        .iter()
        .find(|position| position.0 == cursor.min(input.len()))
        .copied()?;
    let column = goal_column.unwrap_or(current.2);
    let target_row = if up {
        current.1.checked_sub(1)?
    } else {
        current.1 + 1
    };
    let target = positions
        .iter()
        .filter(|position| position.1 == target_row)
        .min_by_key(|position| (position.2.abs_diff(column), position.2 > column))?;
    Some((target.0, column))
}

/// Hard-wraps `text` at display width `width`, keeping style per source
/// line. Every returned Line is a separate scrollback row.
fn wrap_styled(text: &str, width: usize, style: Style) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    for raw in text.split('\n') {
        if raw.is_empty() {
            lines.push(Line::styled(String::new(), style));
            continue;
        }
        let mut current = String::new();
        let mut current_width = 0;
        for grapheme in raw.graphemes(true) {
            let w = UnicodeWidthStr::width(grapheme);
            if current_width + w > width && !current.is_empty() {
                lines.push(Line::styled(std::mem::take(&mut current), style));
                current_width = 0;
            }
            current.push_str(grapheme);
            current_width += w;
        }
        lines.push(Line::styled(current, style));
    }
    lines
}

/// Every row the session produced, grouped into blocks (one user message,
/// one tool line, one diff, one thinking summary...). The fullscreen
/// renderer paints from this buffer each frame; block navigation and
/// copy act on block indices.
#[derive(Default)]
struct Transcript {
    /// Original, unwrapped rows. Layout-dependent wrapping belongs to the
    /// renderer so resizing never changes copied or searched source text.
    lines: Vec<Line<'static>>,
    blocks: Vec<(usize, usize)>,
    copy_texts: Vec<Option<String>>,
}

impl Transcript {
    fn push_block(&mut self, lines: Vec<Line<'static>>) {
        let start = self.lines.len();
        self.lines.extend(lines);
        self.blocks.push((start, self.lines.len()));
        self.copy_texts.push(None);
    }

    fn push_block_with_copy(&mut self, lines: Vec<Line<'static>>, copy_text: String) {
        self.push_block(lines);
        *self.copy_texts.last_mut().expect("block just added") = Some(copy_text);
    }

    /// Drops every recorded row and block, for `/resume` switching to a
    /// different session whose history is replayed from its own store.
    fn clear(&mut self) {
        self.lines.clear();
        self.blocks.clear();
        self.copy_texts.clear();
    }
}

#[derive(Clone)]
struct DisplayRow {
    line: Line<'static>,
    block_index: usize,
    source_line: usize,
    byte_offset: usize,
}

fn wrap_line_for_display(
    line: &Line<'_>,
    width: usize,
    block_index: usize,
    source_line: usize,
) -> Vec<DisplayRow> {
    let width = width.max(1);
    let plain: String = line
        .spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect();
    if plain == "─" {
        return vec![DisplayRow {
            line: Line::styled("─".repeat(width), line.style),
            block_index,
            source_line,
            byte_offset: 0,
        }];
    }
    if plain.is_empty() {
        return vec![DisplayRow {
            line: paint_row(line),
            block_index,
            source_line,
            byte_offset: 0,
        }];
    }

    let mut rows = Vec::new();
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut row_width = 0;
    let mut byte_offset = 0;
    let mut row_start = 0;
    for span in &line.spans {
        for grapheme in span.content.graphemes(true) {
            let grapheme_width = UnicodeWidthStr::width(grapheme);
            if row_width > 0 && row_width + grapheme_width > width {
                let mut rendered = Line::from(std::mem::take(&mut spans));
                rendered.style = line.style;
                rows.push(DisplayRow {
                    line: rendered,
                    block_index,
                    source_line,
                    byte_offset: row_start,
                });
                row_width = 0;
                row_start = byte_offset;
            }
            match spans.last_mut() {
                Some(last) if last.style == span.style => last.content.to_mut().push_str(grapheme),
                _ => spans.push(Span::styled(grapheme.to_owned(), span.style)),
            }
            row_width += grapheme_width;
            byte_offset += grapheme.len();
        }
    }
    let mut rendered = Line::from(spans);
    rendered.style = line.style;
    rows.push(DisplayRow {
        line: rendered,
        block_index,
        source_line,
        byte_offset: row_start,
    });
    rows
}

fn display_rows(transcript: &Transcript, width: usize) -> Vec<DisplayRow> {
    let mut rows = Vec::new();
    for (block_index, (start, end)) in transcript.blocks.iter().enumerate() {
        for source_line in *start..*end {
            rows.extend(wrap_line_for_display(
                &transcript.lines[source_line],
                width,
                block_index,
                source_line,
            ));
        }
    }
    rows
}

/// Splits `text` into styled spans following the source line's span
/// layout: styles are copied from the original spans proportionally by
/// walking both texts in step. Used by search-hit rendering, which
/// rebuilds a row with highlight segments.
fn push_plain_spans(spans: &mut Vec<Span>, text: &str, source: &Line) {
    let source_text: Vec<char> = source
        .spans
        .iter()
        .flat_map(|span| span.content.chars().collect::<Vec<_>>())
        .collect();
    let mut styles = Vec::new();
    for span in &source.spans {
        for _ in 0..span.content.chars().count() {
            styles.push(span.style);
        }
    }
    for (offset, ch) in text.chars().enumerate() {
        let style = styles
            .get(source_text.len().saturating_sub(1).min(offset))
            .copied()
            .unwrap_or_default();
        match spans.last_mut() {
            Some(last) if last.style == style => {
                last.content.to_mut().push(ch);
            }
            _ => spans.push(Span::styled(ch.to_string(), style)),
        }
    }
}

/// Replaces a one-row block's line in place (the running ⏺ line flipping
/// to ✓/✗). Returns `false` when the block is not a single row; the caller
/// then prints the status as its own row.
fn flip_tool_line(transcript: &mut Transcript, block: usize, line: Line<'static>) -> bool {
    let (start, end) = match transcript.blocks.get(block) {
        Some(span) => *span,
        None => return false,
    };
    if end - start != 1 {
        return false;
    }
    transcript.lines[start] = line;
    transcript.copy_texts[block] = None;
    true
}

/// Minimal standard base64 encoder for OSC 52 clipboard payloads.
fn base64(data: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = u32::from(chunk[0]);
        let b1 = u32::from(*chunk.get(1).unwrap_or(&0));
        let b2 = u32::from(*chunk.get(2).unwrap_or(&0));
        let triple = (b0 << 16) | (b1 << 8) | b2;
        out.push(ALPHABET[(triple >> 18) as usize & 0x3f] as char);
        out.push(ALPHABET[(triple >> 12) as usize & 0x3f] as char);
        out.push(if chunk.len() > 1 {
            ALPHABET[(triple >> 6) as usize & 0x3f] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            ALPHABET[triple as usize & 0x3f] as char
        } else {
            '='
        });
    }
    out
}

/// Copies a block's plain text to the system clipboard: OSC 52 first (SSH
/// transparent), then the platform command as fallback (macOS `pbcopy`,
/// Linux `wl-copy`/`xclip`, Windows `clip.exe`). Returns the copied lines.
fn copy_block_to_clipboard(transcript: &Transcript, block: usize) -> std::io::Result<usize> {
    use std::io::Write;
    let (start, end) = match transcript.blocks.get(block) {
        Some(span) => *span,
        None => return Ok(0),
    };
    let text = transcript
        .copy_texts
        .get(block)
        .and_then(Option::as_ref)
        .cloned()
        .unwrap_or_else(|| {
            transcript.lines[start..end]
                .iter()
                .map(|line| {
                    line.spans
                        .iter()
                        .map(|span| span.content.to_string())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join("\n")
        });
    // OSC 52; terminals that disabled it simply ignore the sequence.
    let _ = write!(
        std::io::stdout(),
        "\x1b]52;c;{}\x07",
        base64(text.as_bytes())
    );
    #[cfg(target_os = "macos")]
    let command = "pbcopy";
    #[cfg(all(unix, not(target_os = "macos")))]
    let command = if std::env::var_os("WAYLAND_DISPLAY").is_some() {
        "wl-copy"
    } else {
        "xclip -selection clipboard"
    };
    #[cfg(windows)]
    let command = "clip";
    if let Ok(mut child) = std::process::Command::new(
        command
            .split_whitespace()
            .next()
            .expect("command has a program"),
    )
    .args(command.split_whitespace().skip(1))
    .stdin(std::process::Stdio::piped())
    .spawn()
    {
        if let Some(stdin) = child.stdin.as_mut() {
            let _ = stdin.write_all(text.as_bytes());
        }
        let _ = child.wait();
    }
    Ok(text.lines().count().max(1))
}

/// Moves the scroll anchor one block up or down. The highlight itself is
/// applied by the renderer (reverse video on the selected block), so no
/// in-place terminal surgery is needed in fullscreen mode.
fn navigate_blocks(transcript: &Transcript, app: &mut App, up: bool) {
    let count = transcript.blocks.len();
    if count == 0 {
        return;
    }
    let visible_rows = LAST_PANE_ROWS
        .load(std::sync::atomic::Ordering::Relaxed)
        .max(1);
    let was_pinned = app.scroll_pinned;
    let current = app.highlighted.unwrap_or(count - 1);
    let target = if up {
        current.saturating_sub(1)
    } else {
        (current + 1).min(count - 1)
    };
    app.highlighted = Some(target);
    // Scroll so the target block's first row sits one quarter down the
    // pane -- the same rule search jumps use, expressed in one place.
    let rows = display_rows(
        transcript,
        LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1),
    );
    let target_row = rows
        .iter()
        .position(|row| row.block_index == target)
        .unwrap_or(0);
    app.set_scroll_anchor(&rows, target_row.saturating_sub(visible_rows / 4));
    // Navigating to the last block when it already fills the pane means
    // "follow the bottom" again, the way every chat UI behaves.
    app.scroll_pinned = target == count - 1 && (target_row + visible_rows) >= rows.len();
    if was_pinned && !app.scroll_pinned {
        app.new_output_baseline = Some(transcript.blocks.len());
    } else if app.scroll_pinned {
        app.new_output_baseline = None;
    }
}

/// The index of the transcript row shown at the top of the history pane.
/// `scroll_pinned` follows the bottom; manual scroll, search jumps, and
/// block navigation all set `scroll_offset_rows`, which only ever needs
/// clamping here. This is the single source of truth for what "scrolled
/// to X" means -- the click-to-block mapper uses it too.
fn first_visible_row(app: &App, rows: &[DisplayRow], visible_rows: usize) -> usize {
    let max_scroll = rows.len().saturating_sub(visible_rows);
    if app.scroll_pinned {
        max_scroll
    } else {
        let anchored = app.scroll_anchor.and_then(|anchor| {
            rows.iter().position(|row| {
                row.block_index == anchor.block_index
                    && row.source_line == anchor.source_line
                    && row.byte_offset <= anchor.byte_offset
                    && anchor.byte_offset
                        < row.byte_offset
                            + row
                                .line
                                .spans
                                .iter()
                                .map(|span| span.content.len())
                                .sum::<usize>()
                                .max(1)
            })
        });
        anchored.unwrap_or(app.scroll_offset_rows).min(max_scroll)
    }
}

/// Scrolls the history pane by `delta` rows (negative scrolls up). Manual
/// scrolling releases any search anchor and stops bottom-following; reaching
/// the bottom re-engages follow so new output resumes auto-scrolling.
fn scroll_by(app: &mut App, transcript: &Transcript, visible_rows: usize, delta: isize) {
    let rows = display_rows(
        transcript,
        LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1),
    );
    let max_scroll = rows.len().saturating_sub(visible_rows) as isize;
    let current = first_visible_row(app, &rows, visible_rows) as isize;
    let next = (current + delta).clamp(0, max_scroll);
    if app.scroll_pinned && next < max_scroll {
        app.new_output_baseline = Some(transcript.blocks.len());
    }
    app.set_scroll_anchor(&rows, next as usize);
    app.scroll_pinned = next >= max_scroll;
    if app.scroll_pinned {
        app.new_output_baseline = None;
    }
    app.release_search_anchor();
}

fn print_block(transcript: &mut Transcript, text: &str, style: Style) {
    let lines = text
        .split('\n')
        .map(|line| Line::styled(line.to_owned(), style))
        .collect();
    transcript.push_block_with_copy(lines, text.to_owned());
}

/// One assistant text block: no prefix, just the words, terminal width.
fn print_text(transcript: &mut Transcript, text: &str) {
    print_block(transcript, text, theme::base())
}

fn print_dim(transcript: &mut Transcript, text: &str) {
    print_block(transcript, text, theme::muted())
}

/// Tool-call lines and permission prompts: the "something is happening"
/// color, distinct from prose and from results.
fn print_tool(transcript: &mut Transcript, text: &str) {
    print_block(transcript, text, theme::tool())
}

/// Results and products: completions, file summaries, command output.
fn print_artifact(transcript: &mut Transcript, text: &str) {
    print_block(transcript, text, theme::artifact())
}

fn print_error(transcript: &mut Transcript, text: &str) {
    print_block(transcript, text, theme::error())
}

/// Terminal width as of the last draw; input movement and history anchors use
/// it between frames. Defaults to 80 before the first frame.
static LAST_WIDTH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(80);

/// History-pane height as of the last draw, for scrolling between frames.
static LAST_PANE_ROWS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(18);

/// A user's message, prefixed so it stands out in the scrollback.
fn print_user(transcript: &mut Transcript, text: &str) {
    // Claude-style divider above each user message.
    transcript.push_block(vec![Line::styled("\u{2500}".to_owned(), theme::muted())]);
    let mut lines = Vec::new();
    for (index, raw) in text.split('\n').enumerate() {
        let prefix = if index == 0 { "> " } else { "  " };
        let spans = vec![
            Span::styled(prefix.to_owned(), theme::user()),
            Span::raw(raw.to_owned()),
        ];
        lines.push(Line::from(spans));
    }
    lines.push(Line::raw(String::new()));
    transcript.push_block_with_copy(lines, text.to_owned());
}

// ---------------------------------------------------------------------------
// Folded tool rendering (pure, unit-testable)
// ---------------------------------------------------------------------------

/// Tools whose arguments `tool_summary` names explicitly; any other tool
/// falls back to a truncated JSON preview.
pub(crate) fn summarizes_tool(name: &str) -> bool {
    matches!(
        name,
        "write_file"
            | "read_file"
            | "delete_file"
            | "list_dir"
            | "edit_files"
            | "grep"
            | "find_files"
            | "shell"
            | "memory_search"
    )
}

/// One-line summary of a tool call: what it acts on, not the full JSON.
pub(crate) fn tool_summary(name: &str, arguments: &serde_json::Value) -> String {
    let path = || {
        arguments
            .get("path")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_owned()
    };
    match name {
        "write_file" => format!(
            "{} ({} bytes)",
            path(),
            arguments
                .get("content")
                .and_then(serde_json::Value::as_str)
                .map(str::len)
                .unwrap_or(0)
        ),
        "read_file" | "delete_file" | "list_dir" => path(),
        "edit_files" => {
            let edits = arguments
                .get("edits")
                .and_then(serde_json::Value::as_array)
                .cloned()
                .unwrap_or_default();
            let files: Vec<String> = edits
                .iter()
                .filter_map(|edit| {
                    edit.get("path")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_owned)
                })
                .collect::<Vec<_>>();
            let mut unique = files.clone();
            unique.dedup();
            format!(
                "{} edit{} in {}",
                edits.len(),
                if edits.len() == 1 { "" } else { "s" },
                unique.join(", ")
            )
        }
        "grep" => arguments
            .get("pattern")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_owned(),
        "find_files" => arguments
            .get("pattern")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_owned(),
        "shell" => arguments
            .get("command")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_owned(),
        "memory_search" => arguments
            .get("query")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_owned(),
        _ => {
            let head = serde_json::to_string(arguments).unwrap_or_default();
            head.chars().take(60).collect()
        }
    }
}

/// Colored unified-diff lines for one file movement. Deletions are red,
/// insertions green, hunk headers cyan, context dim. `created` files diff
/// from empty so every added line shows as `+`.
fn movement_diff_lines(
    movement: &checkpoint::FileMovement,
    max_lines: usize,
) -> Vec<Line<'static>> {
    let before = movement
        .before
        .as_deref()
        .and_then(|bytes| std::str::from_utf8(bytes).ok());
    let after = movement
        .after
        .as_deref()
        .and_then(|bytes| std::str::from_utf8(bytes).ok());
    let (before, after) = match (before, after) {
        (Some(before), Some(after)) => (before, after),
        // Binary or missing content: show a byte-count note instead.
        _ => {
            let (from, to) = (
                movement.before.as_ref().map_or(0, Vec::len),
                movement.after.as_ref().map_or(0, Vec::len),
            );
            return vec![Line::styled(
                format!("    binary content, {from} → {to} bytes"),
                theme::muted(),
            )];
        }
    };
    let diff = TextDiff::from_lines(before, after);
    let mut lines = vec![Line::styled(
        format!("    {} ({})", movement.path, {
            let (added, removed) =
                diff.iter_all_changes()
                    .fold((0, 0), |(added, removed), change| match change.tag() {
                        ChangeTag::Insert => (added + 1, removed),
                        ChangeTag::Delete => (added, removed + 1),
                        ChangeTag::Equal => (added, removed),
                    });
            format!("+{added} -{removed}")
        }),
        theme::artifact(),
    )];
    let body = diff.unified_diff().context_radius(3).to_string();
    for (shown, row) in body.lines().enumerate() {
        if shown >= max_lines {
            lines.push(Line::styled(
                format!("    … {max_lines}+ lines, Ctrl+O for verbose"),
                theme::muted(),
            ));
            break;
        }
        let style = if row.starts_with("@@") {
            theme::muted()
        } else if row.starts_with('-') && !row.starts_with("---") {
            theme::removed()
        } else if row.starts_with('+') && !row.starts_with("+++") {
            theme::added()
        } else {
            theme::muted()
        };
        lines.push(Line::styled(format!("  {row}"), style));
    }
    lines
}

// ---------------------------------------------------------------------------
// Editor state and completion (kept from the full-screen TUI)
// ---------------------------------------------------------------------------

fn workspace_files(root: &Path) -> Vec<String> {
    let mut files = Vec::new();
    for entry in ignore::WalkBuilder::new(root).build().flatten() {
        if !entry.file_type().is_some_and(|kind| kind.is_file()) {
            continue;
        }
        if let Ok(path) = entry.path().strip_prefix(root)
            && let Some(path) = path.to_str()
        {
            files.push(path.to_owned());
        }
        if files.len() >= 10_000 {
            break;
        }
    }
    files.sort();
    files
}

fn configured_models(current: &str) -> Vec<String> {
    vec![current.to_owned()]
}

struct CompletionView {
    replace_start: usize,
    replace_end: usize,
    candidates: Vec<String>,
    selected: usize,
}

impl CompletionView {
    /// True when the token under completion is already one of the
    /// candidates (`/session` while `/sessions` is also offered): Enter then
    /// submits it instead of accepting the highlighted candidate.
    fn token_is_complete(&self, input: &str) -> bool {
        let end = self.replace_end.min(input.len()).max(self.replace_start);
        let token = &input[self.replace_start..end];
        self.candidates.iter().any(|candidate| candidate == token)
    }
}

/// The candidates that fit in `width` columns, scrolled so the selected one
/// stays visible, with `…` marking candidates cut off on either side.
fn completion_spans(completion: &CompletionView, width: usize) -> Vec<Span<'static>> {
    let label = |index: usize| {
        if index == completion.selected {
            format!(" [{}] ", completion.candidates[index])
        } else {
            format!(" {} ", completion.candidates[index])
        }
    };
    let widths: Vec<usize> = (0..completion.candidates.len())
        .map(|index| UnicodeWidthStr::width(label(index).as_str()))
        .collect();
    // Grow a window around the selection, reserving room for both markers.
    let budget = width.saturating_sub(2);
    let selected = completion.selected.min(widths.len().saturating_sub(1));
    let (mut start, mut end) = (selected, selected + 1);
    let mut used = widths.get(selected).copied().unwrap_or(0);
    loop {
        let mut grew = false;
        if end < widths.len() && used + widths[end] <= budget {
            used += widths[end];
            end += 1;
            grew = true;
        }
        if start > 0 && used + widths[start - 1] <= budget {
            start -= 1;
            used += widths[start];
            grew = true;
        }
        if !grew {
            break;
        }
    }
    let mut spans = Vec::new();
    if start > 0 {
        spans.push(Span::styled("…".to_owned(), theme::muted()));
    }
    for index in start..end {
        let style = if index == completion.selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            theme::muted()
        };
        spans.push(Span::styled(label(index), style));
    }
    if end < widths.len() {
        spans.push(Span::styled("…".to_owned(), theme::muted()));
    }
    spans
}

/// An active case-insensitive substring search over the transcript.
#[derive(Clone, Debug)]
struct Search {
    query: String,
    /// Index into the flattened match list the view is anchored to.
    current: usize,
    /// While set, the view stays locked to `current`'s match; scrolling or
    /// typing releases the lock (F3/Shift+F3 re-engages it).
    pinned: bool,
}

/// One match: (line index, byte range within the line's plain text).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct SearchHit {
    line: usize,
    start_byte: usize,
    end_byte: usize,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ScrollAnchor {
    block_index: usize,
    source_line: usize,
    byte_offset: usize,
}

/// Case-insensitive substring matches of `query` within a single line's
/// plain text (byte offsets, safe on char boundaries for ASCII queries and
/// computed on char boundaries for any query).
fn line_matches(line_text: &str, query: &str) -> Vec<(usize, usize)> {
    let lower_line = line_text.to_lowercase();
    let lower_query = query.to_lowercase();
    let mut hits = Vec::new();
    if lower_query.is_empty() {
        return hits;
    }
    let mut from = 0;
    while let Some(relative) = lower_line[from..].find(&lower_query) {
        let start = from + relative;
        let end = start + lower_query.len();
        // Byte offsets may split multi-byte chars after lowercasing; snap
        // both ends to char boundaries of the original text.
        let is_boundary = |b: usize| line_text.is_char_boundary(b);
        if is_boundary(start) && is_boundary(end) {
            hits.push((start, end));
        }
        from = end.max(start + 1);
    }
    hits
}

/// All hits of `query` across the transcript, in order.
fn search_hits(transcript: &Transcript, query: &str) -> Vec<SearchHit> {
    let mut hits = Vec::new();
    for (line_index, line) in transcript.lines.iter().enumerate() {
        let text: String = line
            .spans
            .iter()
            .map(|span| span.content.to_string())
            .collect();
        for (start, end) in line_matches(&text, query) {
            hits.push(SearchHit {
                line: line_index,
                start_byte: start,
                end_byte: end,
            });
        }
    }
    hits
}

fn display_hit_ranges(
    transcript: &Transcript,
    row: &DisplayRow,
    query: &str,
) -> Vec<(usize, usize)> {
    let source = &transcript.lines[row.source_line];
    let source_text: String = source
        .spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect();
    let display_text: String = row
        .line
        .spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect();
    let row_end = row.byte_offset + display_text.len();
    line_matches(&source_text, query)
        .into_iter()
        .filter_map(|(start, end)| {
            let visible_start = start.max(row.byte_offset);
            let visible_end = end.min(row_end);
            (visible_start < visible_end).then_some((
                visible_start - row.byte_offset,
                visible_end - row.byte_offset,
            ))
        })
        .collect()
}

const COMMANDS: &[&str] = &[
    "/context",
    "/diff",
    "/exit",
    "/help",
    "/model",
    "/policy",
    "/quit",
    "/resume",
    "/session",
    "/sessions",
    "/thinking",
    "/undo",
];
const THINKING_LEVELS: &[&str] = &[
    "default", "off", "on", "low", "medium", "high", "xhigh", "max",
];

fn completion_for(
    input: &str,
    cursor: usize,
    files: &[String],
    models: &[String],
    policies: &[String],
    thinking_levels: &[&str],
) -> Option<CompletionView> {
    let before = &input[..cursor];
    let word_start = before
        .char_indices()
        .rev()
        .find(|(_, ch)| ch.is_whitespace())
        .map_or(0, |(i, ch)| i + ch.len_utf8());
    let token = &before[word_start..];
    let found: Option<(usize, Vec<String>)> =
        if word_start == 0 && token.starts_with('/') && !token.contains(' ') {
            Some((
                word_start,
                COMMANDS
                    .iter()
                    .filter(|command| command.starts_with(token))
                    .map(|command| (*command).to_owned())
                    .collect(),
            ))
        } else if before.starts_with("/thinking ") && word_start == "/thinking ".len() {
            Some((
                word_start,
                thinking_levels
                    .iter()
                    .filter(|level| level.starts_with(token))
                    .map(|level| (*level).to_owned())
                    .collect(),
            ))
        } else if before.starts_with("/model ") && word_start == "/model ".len() {
            Some((
                word_start,
                models
                    .iter()
                    .filter(|model| model.to_lowercase().contains(&token.to_lowercase()))
                    .cloned()
                    .collect(),
            ))
        } else if before.starts_with("/policy ") && word_start == "/policy ".len() {
            Some((
                word_start,
                policies
                    .iter()
                    .filter(|policy| policy.to_lowercase().contains(&token.to_lowercase()))
                    .cloned()
                    .collect(),
            ))
        } else if let Some(query) = token.strip_prefix('@').map(str::to_lowercase) {
            let mut matches: Vec<_> = files
                .iter()
                .filter(|file| file.to_lowercase().contains(&query))
                .take(50)
                .map(|file| {
                    if file.contains(char::is_whitespace) {
                        format!("@\"{file}\"")
                    } else {
                        format!("@{file}")
                    }
                })
                .collect();
            matches.sort_by_key(|file| (!file[1..].to_lowercase().starts_with(&query), file.len()));
            Some((word_start, matches))
        } else {
            None
        };
    // No match anywhere, or a single candidate identical to the token,
    // offers nothing to choose.
    let (replace_start, candidates) = found?;
    if candidates.is_empty() || (candidates.len() == 1 && candidates[0] == token) {
        return None;
    }
    Some(CompletionView {
        replace_start,
        replace_end: cursor
            + input[cursor..]
                .find(char::is_whitespace)
                .unwrap_or(input.len() - cursor),
        candidates,
        selected: 0,
    })
}

fn permission_details(tool: &str, arguments: &serde_json::Value) -> String {
    if tool == "write_file"
        && let (Some(path), Some(content)) = (
            arguments.get("path").and_then(|v| v.as_str()),
            arguments.get("content").and_then(|v| v.as_str()),
        )
    {
        return format!("Path: {path}\n{content}");
    }
    if tool == "edit_files"
        && let Some(edits) = arguments.get("edits").and_then(|v| v.as_array())
    {
        return edits
            .iter()
            .map(|edit| {
                format!(
                    "{}: {} → {}",
                    edit.get("path").and_then(|v| v.as_str()).unwrap_or("?"),
                    edit.get("old_string")
                        .and_then(|v| v.as_str())
                        .unwrap_or(""),
                    edit.get("new_string")
                        .and_then(|v| v.as_str())
                        .unwrap_or(""),
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
    }
    if tool == "delete_file" {
        return format!(
            "Path: {}",
            arguments
                .get("path")
                .and_then(|v| v.as_str())
                .unwrap_or("?")
        );
    }
    String::new()
}

// ---------------------------------------------------------------------------
// App state
// ---------------------------------------------------------------------------

struct App {
    input: String,
    cursor: usize,
    vertical_column: Option<usize>,
    queued: VecDeque<String>,
    busy: bool,
    show_thinking: bool,
    verbose: bool,
    completion: Option<CompletionView>,
    /// Streaming text of the not-yet-newline-terminated assistant line.
    live: String,
    /// Streaming thinking for the current step, folded into one dim block
    /// once real output starts.
    live_reasoning: String,
    models: Vec<String>,
    policies: Vec<String>,
    thinking_levels: &'static [&'static str],
    status: String,
    /// When set, the next submitted input resolves a `/resume` listing.
    resume_pick: bool,
    /// Session ids behind the pending `/resume` listing, in display order.
    pick_entries: Option<Vec<String>>,
    file_index: Option<Vec<String>>,
    /// Selected row of the inline permission chooser while a decision is
    /// pending (0..4: allow once / allow session / deny once / deny session).
    permission_choice: usize,
    /// Block currently highlighted by up/down navigation, if any.
    highlighted: Option<usize>,
    /// False once the user scrolled the history pane away from the bottom;
    /// new output stops auto-following until they return.
    scroll_pinned: bool,
    /// Active history-pane search: the query and the match to keep in view.
    search: Option<Search>,
    /// Index of the first visible transcript row (0 = top of history).
    /// Manual scrolling always moves this; `scroll_pinned` short-circuits
    /// it back to the bottom when new output follows.
    scroll_offset_rows: usize,
    scroll_anchor: Option<ScrollAnchor>,
    /// Transcript block count when the user began reviewing history.
    new_output_baseline: Option<usize>,
    /// Set while a permission decision is pending: the tool label shown in
    /// the viewport chooser.
    permission_prompt: Option<String>,
    /// The transcript block of the currently-running tool line, so its
    /// completion flips that same line to ✓/✗ instead of printing a second
    /// row.
    running_tool: Option<usize>,
    /// True when the terminal reports Shift+Enter separately from Enter
    /// (kitty keyboard protocol); otherwise only Ctrl+J/Alt+Enter insert a
    /// newline and the hint says so.
    keyboard_enhanced: bool,
    /// When the pending permission chooser appeared. Decision keys are
    /// ignored until `PERMISSION_ARM_DELAY` has passed, so keystrokes typed
    /// for the queued draft cannot answer a prompt that opened mid-word.
    permission_shown_at: Option<std::time::Instant>,
}

/// How long the permission chooser ignores decision keys after it opens.
const PERMISSION_ARM_DELAY: Duration = Duration::from_millis(500);

/// The permission chooser's options, in navigation order.
const PERMISSION_OPTIONS: [&str; 4] = [
    "Allow once",
    "Allow this session",
    "Deny once",
    "Deny this session",
];

impl Default for App {
    fn default() -> Self {
        Self {
            input: String::new(),
            cursor: 0,
            vertical_column: None,
            queued: VecDeque::new(),
            busy: false,
            show_thinking: true,
            verbose: false,
            completion: None,
            live: String::new(),
            live_reasoning: String::new(),
            models: Vec::new(),
            policies: Vec::new(),
            thinking_levels: THINKING_LEVELS,
            status: "Ready".to_owned(),
            resume_pick: false,
            pick_entries: None,
            file_index: None,
            permission_choice: 0,
            highlighted: None,
            scroll_pinned: true,
            search: None,
            scroll_offset_rows: 0,
            scroll_anchor: None,
            new_output_baseline: None,
            permission_prompt: None,
            running_tool: None,
            keyboard_enhanced: false,
            permission_shown_at: None,
        }
    }
}

impl App {
    /// Starts (or restarts) a search with `query`, anchored at the first
    /// match.
    fn start_search(&mut self, transcript: &Transcript, query: String) {
        if query.is_empty() {
            self.search = None;
            return;
        }
        self.search = Some(Search {
            query,
            current: 0,
            pinned: true,
        });
        if self.scroll_pinned {
            self.new_output_baseline = Some(transcript.blocks.len());
        }
        self.jump_search_to_visible(transcript);
    }

    /// Moves to the next (down=false→previous) match.
    fn step_search(&mut self, transcript: &Transcript, forward: bool) {
        let Some(search) = self.search.as_mut() else {
            return;
        };
        let hits = search_hits(transcript, &search.query);
        if hits.is_empty() {
            return;
        }
        search.current = if forward {
            (search.current + 1) % hits.len()
        } else {
            search.current.checked_sub(1).unwrap_or(hits.len() - 1)
        };
        search.pinned = true;
        self.jump_search_to_visible(transcript);
    }

    /// Drops the search's hold on the scroll position without forgetting
    /// the query, so F3/Shift+F3 can re-anchor to another match later.
    fn release_search_anchor(&mut self) {
        if let Some(search) = self.search.as_mut() {
            search.pinned = false;
        }
    }

    /// Pins the scroll so the current match's row is on screen.
    fn jump_search_to_visible(&mut self, transcript: &Transcript) {
        let Some(search) = self.search.as_ref() else {
            return;
        };
        let hits = search_hits(transcript, &search.query);
        let Some(hit) = hits.get(search.current) else {
            return;
        };
        // Anchor the hit near the top of the pane (one row of context
        // above it), retaining the source text location across reflow.
        let width = LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1);
        let rows = display_rows(transcript, width);
        let hit_row = rows
            .iter()
            .position(|row| {
                if row.source_line != hit.line {
                    return false;
                }
                let row_text: String = row
                    .line
                    .spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect();
                hit.start_byte >= row.byte_offset
                    && hit.start_byte < row.byte_offset + row_text.len().max(1)
            })
            .unwrap_or(0);
        self.set_scroll_anchor(&rows, hit_row.saturating_sub(1));
        self.scroll_pinned = false;
    }

    fn set_scroll_anchor(&mut self, rows: &[DisplayRow], row_index: usize) {
        self.scroll_offset_rows = row_index;
        self.scroll_anchor = rows.get(row_index).map(|row| ScrollAnchor {
            block_index: row.block_index,
            source_line: row.source_line,
            byte_offset: row.byte_offset,
        });
    }

    fn new(session: &InteractiveSession) -> Self {
        let models = if session.model_configs.is_empty() {
            configured_models(&session.config.model)
        } else {
            session.model_configs.keys().cloned().collect()
        };
        Self {
            models,
            policies: session.blend_policies.keys().cloned().collect(),
            thinking_levels: crate::config::thinking_levels(session.config.api_type),
            ..Self::default()
        }
    }

    fn insert(&mut self, text: &str) {
        let cursor = self.cursor.min(self.input.len());
        self.input.insert_str(cursor, text);
        self.cursor += text.len();
        self.refresh_completion();
    }

    fn backspace(&mut self) {
        if self.cursor > 0 {
            let cursor = self.cursor.min(self.input.len());
            let remove = self.input[..cursor]
                .grapheme_indices(true)
                .next_back()
                .map_or(0, |(start, _)| cursor - start);
            self.input.replace_range(cursor - remove..cursor, "");
            self.cursor -= remove;
            self.refresh_completion();
        }
    }

    fn delete(&mut self) {
        let cursor = self.cursor.min(self.input.len());
        if cursor < self.input.len() {
            let remove = self.input[cursor..]
                .graphemes(true)
                .next()
                .map_or(0, str::len);
            self.input.replace_range(cursor..cursor + remove, "");
            self.refresh_completion();
        }
    }

    fn move_vertical(&mut self, up: bool) {
        let cursor = self.cursor.min(self.input.len());
        let Some((target_cursor, column)) = vertical_cursor_move(
            &self.input,
            cursor,
            up,
            self.vertical_column,
            LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(4),
        ) else {
            return;
        };
        self.cursor = target_cursor;
        self.vertical_column = Some(column);
        self.refresh_completion();
    }

    fn take_input(&mut self) -> String {
        self.cursor = 0;
        std::mem::take(&mut self.input)
    }

    fn refresh_completion(&mut self) {
        self.completion = completion_for(
            &self.input,
            self.cursor,
            self.file_index.as_deref().unwrap_or(&[]),
            &self.models,
            &self.policies,
            self.thinking_levels,
        )
        .filter(|_| !self.busy);
    }

    fn apply_completion(&mut self) {
        let Some(completion) = self.completion.as_ref() else {
            return;
        };
        let candidate = completion.candidates[completion.selected].clone();
        let start = completion.replace_start;
        let end = completion.replace_end.min(self.input.len()).max(start);
        self.input.replace_range(start..end, &candidate);
        self.cursor = start + candidate.len();
        self.completion = None;
    }
}

// ---------------------------------------------------------------------------
// Events from the running turn
// ---------------------------------------------------------------------------

enum UiEvent {
    Text(String),
    Reasoning(String),
    ToolStart {
        name: String,
        summary: String,
    },
    ToolDone {
        call_id: String,
        name: String,
        is_error: bool,
        result: String,
    },
}

#[derive(Default)]
struct StreamState {
    step_text: String,
    step_reasoning: String,
    displayed: String,
}

struct TuiObserver {
    state: Mutex<StreamState>,
    sender: tokio::sync::mpsc::UnboundedSender<UiEvent>,
}

impl TuiObserver {
    fn new(sender: tokio::sync::mpsc::UnboundedSender<UiEvent>) -> Arc<Self> {
        Arc::new(Self {
            state: Mutex::new(StreamState::default()),
            sender,
        })
    }

    fn sink(self: &Arc<Self>) -> ModelProgressSink {
        let observer = Arc::clone(self);
        ModelProgressSink::new(move |progress| {
            let mut state = observer.state.lock().expect("TUI progress lock poisoned");
            match progress {
                ModelProgress::Start => {
                    state.step_text.clear();
                    state.step_reasoning.clear();
                }
                ModelProgress::Message(text) => {
                    state.step_text.push_str(&text);
                    state.displayed.push_str(&text);
                    let _ = observer.sender.send(UiEvent::Text(text));
                }
                ModelProgress::Reasoning(text) => {
                    state.step_reasoning.push_str(&text);
                    let _ = observer.sender.send(UiEvent::Reasoning(text));
                }
            }
        })
    }
}

impl SessionEventObserver for TuiObserver {
    fn observe(&self, envelope: &EventEnvelope, _visibility: EventVisibility) {
        match &envelope.event {
            Event::ModelResponseItem {
                item: RuntimeItem::Message(message),
                ..
            } if message.role == RuntimeRole::Assistant => {
                let full = message
                    .content
                    .iter()
                    .filter_map(|block| match block {
                        ContentBlock::Text { text } => Some(text.as_str()),
                        _ => None,
                    })
                    .collect::<String>();
                let mut state = self.state.lock().expect("TUI progress lock poisoned");
                let extra = full
                    .strip_prefix(&state.step_text)
                    .unwrap_or(&full)
                    .to_owned();
                if !extra.is_empty() {
                    state.displayed.push_str(&extra);
                    let _ = self.sender.send(UiEvent::Text(extra));
                }
            }
            Event::ModelResponseItem {
                item: RuntimeItem::Reasoning(reasoning),
                ..
            } => {
                let full = reasoning.summary.join("\n\n");
                let state = self.state.lock().expect("TUI progress lock poisoned");
                let extra = full.strip_prefix(&state.step_reasoning).unwrap_or(&full);
                if !extra.is_empty() {
                    let _ = self.sender.send(UiEvent::Reasoning(extra.to_owned()));
                }
            }
            Event::ToolCallRequested {
                name, arguments, ..
            } => {
                let _ = self.sender.send(UiEvent::ToolStart {
                    name: name.clone(),
                    summary: tool_summary(name, arguments),
                });
            }
            Event::ToolCallCompleted {
                call_id,
                name,
                result,
                is_error,
                ..
            } => {
                let _ = self.sender.send(UiEvent::ToolDone {
                    call_id: call_id.clone(),
                    name: name.clone(),
                    is_error: *is_error,
                    result: result.clone(),
                });
            }
            Event::RunCompleted {
                output: Some(output),
            } => {
                let state = self.state.lock().expect("TUI progress lock poisoned");
                if !output.is_empty() && !state.displayed.ends_with(output) {
                    let _ = self.sender.send(UiEvent::Text(output.clone()));
                }
            }
            _ => {}
        }
    }
}

// ---------------------------------------------------------------------------
// Terminal plumbing
// ---------------------------------------------------------------------------

struct InputEvents {
    receiver: tokio::sync::mpsc::UnboundedReceiver<io::Result<InputEvent>>,
    stop: Arc<AtomicBool>,
}

impl Drop for InputEvents {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
    }
}

fn input_events() -> InputEvents {
    use std::sync::atomic::Ordering;
    let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
    let stop = Arc::new(AtomicBool::new(false));
    let thread_stop = Arc::clone(&stop);
    tokio::task::spawn_blocking(move || {
        while !thread_stop.load(Ordering::Relaxed) {
            match event::poll(Duration::from_millis(100)) {
                Ok(true) => {
                    let result = event::read();
                    let failed = result.is_err();
                    if sender.send(result).is_err() || failed {
                        break;
                    }
                }
                Ok(false) => {}
                Err(error) => {
                    let _ = sender.send(Err(error));
                    break;
                }
            }
        }
    });
    InputEvents { receiver, stop }
}

enum EditorAction {
    None,
    Submit(String),
    Exit,
}

/// The newest text of the streaming reply that fits in one `width`-column
/// row: the end of its last line, with a leading ellipsis when cut.
fn live_tail(live: &str, width: usize) -> String {
    let last_line = live
        .trim_end_matches('\n')
        .rsplit('\n')
        .next()
        .unwrap_or("");
    if UnicodeWidthStr::width(last_line) <= width {
        return last_line.to_owned();
    }
    let budget = width.saturating_sub(1);
    let mut used = 0;
    let mut start = last_line.len();
    for (index, ch) in last_line.char_indices().rev() {
        let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + ch_width > budget {
            break;
        }
        used += ch_width;
        start = index;
    }
    format!("…{}", &last_line[start..])
}

/// Restores the terminal even on early returns and errors.
struct InlineGuard {
    keyboard_enhanced: bool,
}

impl Drop for InlineGuard {
    fn drop(&mut self) {
        if self.keyboard_enhanced {
            let _ =
                crossterm::execute!(io::stdout(), crossterm::event::PopKeyboardEnhancementFlags);
        }
        let _ = disable_raw_mode();
        let _ = crossterm::execute!(
            io::stdout(),
            crossterm::event::DisableMouseCapture,
            crossterm::terminal::LeaveAlternateScreen,
            crossterm::cursor::Show
        );
        // The transcript lived in the alternate buffer; print the last
        // status so exiting does not feel like losing the session.
        println!();
    }
}

struct FullscreenLayout {
    sections: Vec<Rect>,
    editor: EditorLayout,
    divider_index: Option<usize>,
    tail_index: Option<usize>,
    input_index: usize,
    hints_index: Option<usize>,
    status_index: Option<usize>,
}

fn permission_lines(prompt: &str, selected: usize, width: usize) -> (bool, Vec<Line<'static>>) {
    let width = width.max(1);
    let option_width = PERMISSION_OPTIONS
        .iter()
        .enumerate()
        .map(|(index, label)| {
            let label = if index == selected {
                format!(" [{label}] ")
            } else {
                format!("  {label}  ")
            };
            UnicodeWidthStr::width(label.as_str())
        })
        .sum::<usize>();
    let horizontal_width = UnicodeWidthStr::width(prompt) + 2 + option_width;
    if horizontal_width <= width {
        let mut spans = vec![
            Span::styled(prompt.to_owned(), theme::tool()),
            Span::raw("  "),
        ];
        spans.extend(PERMISSION_OPTIONS.iter().enumerate().map(|(index, label)| {
            let label = if index == selected {
                format!(" [{label}] ")
            } else {
                format!("  {label}  ")
            };
            let style = if index == selected {
                Style::default().fg(Color::Black).bg(Color::Cyan)
            } else {
                theme::muted()
            };
            Span::styled(label, style)
        }));
        return (false, vec![Line::from(spans)]);
    }

    let mut lines = wrap_styled(prompt, width, theme::tool());
    for (index, label) in PERMISSION_OPTIONS.iter().enumerate() {
        let selected = index == selected;
        let marker = if selected { "> " } else { "  " };
        let style = if selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            theme::muted()
        };
        let option_lines = wrap_styled(label, width.saturating_sub(2).max(1), style);
        for (row, line) in option_lines.into_iter().enumerate() {
            let prefix = if row == 0 { marker } else { "  " };
            let mut spans = vec![Span::styled(prefix.to_owned(), style)];
            spans.extend(line.spans);
            lines.push(Line::from(spans));
        }
    }
    lines.extend(wrap_styled(
        "↑↓ choose · Enter · y/a/n/v · Esc · Ctrl+C",
        width,
        theme::muted(),
    ));
    (true, lines)
}

fn fullscreen_layout(area: Rect, app: &App) -> FullscreenLayout {
    let editor = layout_editor(&app.input, app.cursor, area.width as usize);
    let permission = app
        .permission_prompt
        .as_ref()
        .map(|prompt| permission_lines(prompt, app.permission_choice, area.width as usize));
    let permission_vertical = permission.as_ref().is_some_and(|(vertical, _)| *vertical);
    let permission_rows = permission
        .as_ref()
        .map(|(_, lines)| lines.len())
        .unwrap_or(1);
    let mut input_height = composer_height(area.height as usize, editor.rows.len());
    if permission_vertical {
        input_height = input_height.min(
            (area.height as usize)
                .saturating_sub(permission_rows)
                .max(1),
        );
    }
    let mut constraints = vec![Constraint::Min(1)];
    let mut next = 1;
    let has_permission = permission.is_some();
    let divider_index = if !permission_vertical && area.height >= 3 {
        let index = next;
        constraints.push(Constraint::Length(1));
        next += 1;
        Some(index)
    } else {
        None
    };
    let tail_index = if has_permission || area.height >= 4 {
        let index = next;
        constraints.push(Constraint::Length(if permission_vertical {
            permission_rows.min(area.height.saturating_sub(1) as usize) as u16
        } else {
            1
        }));
        next += 1;
        Some(index)
    } else {
        None
    };
    let input_index = next;
    constraints.push(Constraint::Length(input_height as u16));
    next += 1;
    let hints_index = if !permission_vertical && area.height as usize > next {
        let index = next;
        constraints.push(Constraint::Length(1));
        next += 1;
        Some(index)
    } else {
        None
    };
    let status_index = if !permission_vertical && area.height as usize > next {
        let index = next;
        constraints.push(Constraint::Length(1));
        Some(index)
    } else {
        None
    };
    FullscreenLayout {
        sections: Layout::vertical(constraints).split(area).to_vec(),
        editor,
        divider_index,
        tail_index,
        input_index,
        hints_index,
        status_index,
    }
}

/// Draws the bottom viewport: streaming tail, completion hint, input row,
/// status line.
fn draw(terminal: &mut DefaultTerminal, app: &App, transcript: &Transcript) -> io::Result<()> {
    let size = terminal.size().ok();
    let area = size
        .map(|size| Rect::new(0, 0, size.width, size.height))
        .unwrap_or(Rect::new(0, 0, 80, 24));
    LAST_WIDTH.store(area.width as usize, std::sync::atomic::Ordering::Relaxed);
    LAST_PANE_ROWS.store(
        fullscreen_layout(area, app).sections[0].height as usize,
        std::sync::atomic::Ordering::Relaxed,
    );
    // Fence the frame in a synchronized-update pair (CSI ?2026): the
    // terminal applies the whole repaint atomically, so fast frames never
    // tear mid-draw. Terminals without support recover via the spec's
    // timeout. Codex CLI and Claude Code fence the same way.
    io::stdout().sync_update(|_| {
        terminal
            .draw(|frame| render_fullscreen(frame, app, transcript))
            .map(|_| ())
    })?
}

/// Fullscreen layout: scrolling history pane on top, Claude-style divider
/// pinned above the bottom editor block, editor + hints + status at the
/// bottom. The highlight (reverse video) is applied here, at render time.
fn render_fullscreen(frame: &mut Frame, app: &App, transcript: &Transcript) {
    let area = frame.area();
    let layout = fullscreen_layout(area, app);
    let sections = &layout.sections;
    let editor = &layout.editor;
    let divider_index = layout.divider_index;
    let tail_index = layout.tail_index;
    let input_index = layout.input_index;
    let hints_index = layout.hints_index;
    let status_index = layout.status_index;

    // ---- history pane ----
    let visible_rows = sections[0].height as usize;
    // Reflow source rows for the current width. Transcript storage remains
    // independent of terminal size.
    let highlight = app.highlighted;
    let rows = display_rows(transcript, sections[0].width as usize);
    // Auto-follow the bottom unless the user scrolled away; every anchor
    // (search jump, block navigation, click) resolves through the same
    // first_visible_row so one coordinate system governs the pane.
    let total = rows.len();
    let offset = first_visible_row(app, &rows, visible_rows);
    let shown = &rows[offset.min(total)..(offset + visible_rows).min(total)];
    let search = app.search.as_ref();
    let lines: Vec<Line> = shown
        .iter()
        .map(|display_row| {
            let line = &display_row.line;
            let highlighted = highlight.is_some_and(|selected| selected == display_row.block_index);
            let hit_ranges: Vec<(usize, usize)> = search
                .map(|search| display_hit_ranges(transcript, display_row, &search.query))
                .unwrap_or_default();
            if !hit_ranges.is_empty() {
                // Rebuild spans, splitting any span text at match boundaries
                // so the hit substring gets the highlight style.
                let plain: String = line
                    .spans
                    .iter()
                    .map(|span| span.content.to_string())
                    .collect();
                let mut spans: Vec<Span> = Vec::new();
                let mut consumed = 0usize;
                for (start, end) in &hit_ranges {
                    if *start > consumed {
                        push_plain_spans(&mut spans, &plain[consumed..*start], line);
                    }
                    push_plain_spans(&mut spans, &plain[*start..*end], line);
                    let last = spans.last_mut().expect("pushed above");
                    last.style = last
                        .style
                        .add_modifier(ratatui::style::Modifier::BOLD)
                        .fg(Color::Black)
                        .bg(Color::Yellow);
                    consumed = *end;
                }
                push_plain_spans(&mut spans, &plain[consumed..], line);
                let mut rebuilt = Line::from(spans);
                rebuilt.style = line.style;
                if highlighted {
                    rebuilt.style = rebuilt.style.add_modifier(Modifier::REVERSED);
                }
                return rebuilt;
            }
            let mut row = paint_row(line);
            if highlighted {
                row.style = row.style.add_modifier(Modifier::REVERSED);
            }
            row
        })
        .collect();
    frame.render_widget(Paragraph::new(lines), sections[0]);

    // ---- divider ----
    if let Some(divider_index) = divider_index {
        let divider = "\u{2500}".repeat(sections[divider_index].width as usize);
        frame.render_widget(
            Paragraph::new(Line::styled(divider, theme::muted())),
            sections[divider_index],
        );
    }

    // ---- row: streaming tail / completion / permission prompt ----
    if let Some(tail_index) = tail_index
        && let Some(prompt) = &app.permission_prompt
    {
        let (_, lines) = permission_lines(
            prompt,
            app.permission_choice,
            sections[tail_index].width as usize,
        );
        frame.render_widget(Paragraph::new(lines), sections[tail_index]);
    } else if let Some(tail_index) = tail_index
        && let Some(completion) = &app.completion
    {
        let candidates = completion_spans(completion, sections[tail_index].width as usize);
        frame.render_widget(Paragraph::new(Line::from(candidates)), sections[tail_index]);
    } else if let Some(tail_index) = tail_index
        && app.busy
        && !app.live.is_empty()
    {
        // Assistant text streams here; thinking streams inside the
        // history pane below.
        let tail = live_tail(&app.live, sections[tail_index].width as usize);
        frame.render_widget(
            Paragraph::new(Line::styled(tail, theme::base())),
            sections[tail_index],
        );
    }

    // Streaming thinking grows inside the history pane: its tail renders
    // as the pane's bottom rows, dim, before being folded into a summary
    // block on flush.
    if app.busy && !app.live_reasoning.is_empty() {
        let width = sections[0].width.max(1) as usize;
        let pane_rows = sections[0].height as usize;
        let tail: String = {
            let budget = width
                .saturating_mul(pane_rows.saturating_sub(offset))
                .max(width);
            app.live_reasoning
                .chars()
                .rev()
                .take(budget * 2)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect()
        };
        let wrapped: Vec<Line> = wrap_styled(&tail, width, theme::muted())
            .into_iter()
            .take(pane_rows.saturating_sub(offset))
            .collect();
        let pane = sections[0];
        let tail_rows = wrapped.len() as u16;
        let tail_area = ratatui::layout::Rect {
            x: pane.x,
            y: pane.y + pane.height.saturating_sub(tail_rows),
            width: pane.width,
            height: tail_rows,
        };
        frame.render_widget(ratatui::widgets::Clear, tail_area);
        frame.render_widget(Paragraph::new(wrapped), tail_area);
    }

    // ---- input row ----
    let input_area = sections[input_index];
    let editor_start = if input_area.height == 0 {
        0
    } else {
        editor
            .cursor_row
            .saturating_add(1)
            .saturating_sub(input_area.height as usize)
    };
    let editor_end = (editor_start + input_area.height as usize).min(editor.rows.len());
    let editor_lines = editor.rows[editor_start..editor_end]
        .iter()
        .map(|row| {
            if let Some(content) = row.strip_prefix("❯ ") {
                Line::from(vec![
                    Span::styled("❯ ".to_owned(), theme::user()),
                    Span::raw(content.to_owned()),
                ])
            } else if let Some(content) = row.strip_prefix('❯') {
                Line::from(vec![
                    Span::styled("❯".to_owned(), theme::user()),
                    Span::raw(content.to_owned()),
                ])
            } else {
                let content = row
                    .strip_prefix("  ")
                    .or_else(|| row.strip_prefix(' '))
                    .unwrap_or(row);
                Line::from(vec![
                    Span::styled(row[..row.len() - content.len()].to_owned(), theme::user()),
                    Span::raw(content.to_owned()),
                ])
            }
        })
        .collect::<Vec<_>>();
    frame.render_widget(Paragraph::new(editor_lines), input_area);
    let cursor_x = (input_area.x as usize + editor.cursor_column)
        .min(area.width.saturating_sub(1) as usize) as u16;
    if input_area.height > 0 && app.permission_prompt.is_none() {
        let cursor_y = input_area.y + (editor.cursor_row - editor_start) as u16;
        frame.set_cursor_position((cursor_x, cursor_y));
    }

    // ---- hints row ----
    if let Some(hints_index) = hints_index {
        let width = sections[hints_index].width;
        let hints = if app.permission_prompt.is_some() {
            if width < 100 {
                " ↑↓ choose · Enter confirm · Esc deny · Ctrl+C cancel"
            } else {
                " ↑↓ choose · Enter confirm · y once · a session · n deny · v deny session · Esc deny · Ctrl+C cancel"
            }
        } else if app.completion.is_some() {
            " ↑↓ choose · Tab/Enter accept · Esc close"
        } else if app.resume_pick {
            " Enter a number or id prefix to resume · Esc cancel"
        } else if app.search.is_some() {
            " F3 next · Shift+F3 previous · Esc close"
        } else if app.highlighted.is_some() && !app.busy {
            " ↑↓ block · Enter/c copy · Ctrl+End latest · Esc close"
        } else if app.busy {
            " Esc/Ctrl+C cancel · type to queue · Ctrl+End latest"
        } else if width < 100 {
            if app.keyboard_enhanced {
                " Enter send · Shift+Enter newline · ↑↓ history · Ctrl+C clear/exit · Ctrl+End latest"
            } else {
                " Enter send · Ctrl+J newline · ↑↓ history · Ctrl+C clear/exit · Ctrl+End latest"
            }
        } else if app.keyboard_enhanced {
            " Enter send · Shift+Enter newline · ↑↓ history · Ctrl+C clear/exit · Ctrl+D delete/exit · Ctrl+A/E line · Ctrl+←/→ word · Ctrl+End latest · /help"
        } else {
            " Enter send · Ctrl+J newline · ↑↓ history · Ctrl+C clear/exit · Ctrl+D delete/exit · Ctrl+A/E line · Ctrl+←/→ word · Ctrl+End latest · /help"
        };
        frame.render_widget(
            Paragraph::new(Line::styled(hints, theme::muted())),
            sections[hints_index],
        );
    }

    // ---- status row ----
    if let Some(status_index) = status_index {
        let new_blocks = app
            .new_output_baseline
            .map(|baseline| transcript.blocks.len().saturating_sub(baseline))
            .unwrap_or(0);
        let new_output = if !app.scroll_pinned && new_blocks > 0 {
            format!(" · ↓ {new_blocks} new")
        } else {
            String::new()
        };
        let search_status = app
            .search
            .as_ref()
            .map(|search| {
                let hits = search_hits(transcript, &search.query);
                if hits.is_empty() {
                    " · no matches".to_owned()
                } else {
                    format!(
                        " · {}/{}",
                        search.current.min(hits.len().saturating_sub(1)) + 1,
                        hits.len()
                    )
                }
            })
            .unwrap_or_default();
        let queued_status = if app.queued.is_empty() {
            String::new()
        } else {
            format!(" · {} queued", app.queued.len())
        };
        let verbose_status = if app.verbose { " · verbose" } else { "" };
        let thinking_status = if app.show_thinking {
            ""
        } else {
            " · thinking hidden"
        };
        let status = format!(
            " {}{search_status}{queued_status}{verbose_status}{thinking_status}{new_output}",
            app.status
        );
        frame.render_widget(
            Paragraph::new(Line::styled(status, theme::muted())),
            sections[status_index],
        );
    }
}

// ---------------------------------------------------------------------------
// Turn execution
// ---------------------------------------------------------------------------

fn permission_decision(key: KeyEvent) -> Option<PermissionDecision> {
    match key.code {
        KeyCode::Char('y') => Some(PermissionDecision::allow_once()),
        KeyCode::Char('a') => Some(PermissionDecision::allow_for_session()),
        KeyCode::Char('v') => Some(PermissionDecision {
            outcome: ToolPermissionOutcome::Denied,
            scope: ToolPermissionScope::Session,
            source: ToolPermissionSource::User,
        }),
        KeyCode::Char('n') | KeyCode::Esc => Some(PermissionDecision::deny_once()),
        _ => None,
    }
}

/// The number of bytes of `live` that are safe to commit to the scrollback:
/// every complete line before the opening line of an unmatched ``` code
/// fence. Lines inside an open fence hold back until the fence closes, so
/// a half-streamed block never renders as garbled text (the Codex/pi/
/// Gemini streaming approach). Always a line boundary; `0` when nothing is
/// committable.
fn committable_prefix(live: &str) -> usize {
    let Some(last_newline) = live.rfind('\n') else {
        return 0;
    };
    let complete = &live[..last_newline + 1];
    let mut in_fence = false;
    let mut open_fence_end = 0;
    let mut offset = 0;
    for line in complete.split_inclusive('\n') {
        let line_len = line.len();
        if line.trim_start().starts_with("```") {
            in_fence = !in_fence;
            if in_fence {
                // Hold everything after this delimiter line until the
                // fence closes.
                open_fence_end = offset + line_len;
            }
        }
        offset += line_len;
    }
    if in_fence {
        open_fence_end
    } else {
        complete.len()
    }
}

/// Flushes any unterminated streaming line into the scrollback.
fn flush_live(transcript: &mut Transcript, app: &mut App) {
    if !app.live.is_empty() {
        let text = std::mem::take(&mut app.live);
        print_text(transcript, &text);
    }
}

/// Flushes the accumulated thinking block as one dim paragraph, prefixed
/// on its first line. Called when real output, a tool call, or the end of
/// the turn arrives -- thinking stays together instead of one row per
/// delta.
fn flush_reasoning(transcript: &mut Transcript, app: &mut App) {
    if !app.live_reasoning.is_empty() {
        let text = std::mem::take(&mut app.live_reasoning);
        if app.verbose {
            print_dim(transcript, &format!("· {text}"));
        } else {
            let words = text.split_whitespace().count();
            print_dim(transcript, &format!("· thinking · {words} words"));
        }
    }
}

/// The write-checkpoint for a finished call, for diff rendering.
fn checkpoint_for(
    journal: &std::sync::Arc<std::sync::Mutex<checkpoint::WriteJournal>>,
    call_id: &str,
) -> Option<WriteCheckpoint> {
    let journal = journal.lock().expect("write journal lock poisoned");
    journal.latest_for_call(call_id)
}

async fn run_turn(
    session: &mut InteractiveSession,
    app: &mut App,
    terminal: &mut DefaultTerminal,
    transcript: &mut Transcript,
    keys: &mut tokio::sync::mpsc::UnboundedReceiver<io::Result<InputEvent>>,
    text: String,
) -> Result<(), Box<dyn std::error::Error>> {
    app.busy = true;
    app.status = "Working".to_owned();
    app.refresh_completion();
    print_user(transcript, &text);
    draw(terminal, app, transcript)?;

    let (ui_tx, mut ui_rx) = tokio::sync::mpsc::unbounded_channel();
    let tui_observer = TuiObserver::new(ui_tx);
    interactive::set_progress(
        session.manager.runtime_mut().model_mut(),
        tui_observer.sink(),
    );
    let mut observers: Vec<Arc<dyn SessionEventObserver>> = vec![
        Arc::clone(&session.store) as Arc<dyn SessionEventObserver>,
        Arc::clone(&tui_observer) as Arc<dyn SessionEventObserver>,
    ];
    crate::evaluation::attach(&mut observers, &session.arabica_home);
    let observer: Arc<dyn SessionEventObserver> = Arc::new(FanOutObserver::new(observers));
    let cancellation = RunCancellation::new();
    let (permission_tx, mut permission_rx) =
        tokio::sync::mpsc::unbounded_channel::<PermissionRequest>();
    let control = DispatchControl {
        run: RunControl {
            cancellation: Some(cancellation.clone()),
            permissions: Some(ToolPermissionGate {
                policy: interactive::policy(),
                approver: Some(permission_tx),
            }),
        },
        observer: Some(observer),
    };
    let envelope = CommandEnvelope::new(
        CommandId::new(uuid::Uuid::now_v7().to_string()),
        Some(session.session_id.clone()),
        Command::MessageSend {
            images: Vec::new(),
            content: text,
        },
    );
    // Taken before dispatch's mutable borrow of the session: the loop
    // below reads write checkpoints while the run is in flight.
    let write_journal = session.manager.runtime().runner().write_journal();
    let dispatch = session.manager.dispatch(envelope, control);
    tokio::pin!(dispatch);
    let mut pending: Option<PermissionRequest> = None;
    let mut tick = tokio::time::interval(Duration::from_millis(40));
    let result = loop {
        tokio::select! {
            result = &mut dispatch => break result,
            Some(update) = ui_rx.recv() => {
                match update {
                    UiEvent::Text(text) => {
                        flush_reasoning(transcript, app);
                        app.live.push_str(&text);
                        // Completed lines go straight to the scrollback,
                        // except while a code fence is open: those lines
                        // hold back until the fence closes, so a half-
                        // streamed block never renders as broken text.
                        loop {
                            let end = committable_prefix(&app.live);
                            let Some(newline) = app.live[..end].find('\n') else {
                                break;
                            };
                            let line: String = app.live.drain(..newline + 1).collect();
                            print_text(transcript, line.trim_end_matches('\n'));
                        }
                    }
                    UiEvent::Reasoning(text) => {
                        if app.show_thinking {
                            flush_live(transcript, app);
                            app.live_reasoning.push_str(&text);
                        }
                    }
                    UiEvent::ToolStart { name, summary } => {
                        flush_reasoning(transcript, app);
                        flush_live(transcript, app);
                        let line = if summary.is_empty() {
                            format!("⏺ {name}")
                        } else {
                            format!("⏺ {name} · {summary}")
                        };
                        print_tool(transcript, &line);
                        app.running_tool = Some(transcript.blocks.len() - 1);
                    }
                    UiEvent::ToolDone {
                        call_id,
                        name,
                        is_error,
                        result,
                    } => {
                        flush_reasoning(transcript, app);
                        flush_live(transcript, app);
                        // Flip the running ⏺ line in place to ✓/✗ when it
                        // is still a single recorded row; otherwise print
                        // the status as its own row.
                        let status_line = if is_error {
                            Line::styled(format!("✗ {name}"), theme::removed())
                        } else {
                            Line::styled(format!("✓ {name}"), theme::tool_ok())
                        };
                        let mut printed_status = false;
                        if let Some(block) = app.running_tool.take()
                            && flip_tool_line(transcript, block, status_line.clone())
                        {
                            printed_status = true;
                        }
                        if is_error {
                            if !printed_status {
                                transcript.push_block(vec![status_line]);
                            }
                        } else if let Some(checkpoint) = checkpoint_for(&write_journal, &call_id) {
                            let max_lines = if app.verbose {
                                usize::MAX
                            } else {
                                DIFF_FOLD_LINES
                            };
                            for movement in &checkpoint.movements {
                                transcript
                                    .push_block(movement_diff_lines(movement, max_lines));
                            }
                        } else if !printed_status {
                            // No file movement to show: a quiet result line
                            // confirms the call landed.
                            print_artifact(transcript, &format!("  ✓ {name}"));
                        }
                        // Result preview under the status line, unless the
                        // result is trivial or a diff already told the story.
                        let already_shown = checkpoint_for(&write_journal, &call_id).is_some();
                        let preview = result.trim();
                        if !preview.is_empty()
                            && !already_shown
                            && preview != "ok"
                            && !preview.starts_with("wrote ")
                        {
                            let max_chars = if app.verbose {
                                8_000
                            } else {
                                400
                            };
                            let mut excerpt: String = preview.chars().take(max_chars).collect();
                            if preview.chars().count() > max_chars {
                                let total_lines = preview.lines().count();
                                excerpt.push_str(&format!(
                                    "\n  … truncated, {total_lines} lines total (Ctrl+O verbose)"
                                ));
                            }
                            print_block(
                                transcript,
                                &format!("  {excerpt}"),
                                theme::muted(),
                            );
                        }
                    }
                }
                draw(terminal, app, transcript)?;
            }
            Some(request) = permission_rx.recv(), if pending.is_none() => {
                flush_reasoning(transcript, app);
                flush_live(transcript, app);
                let details = permission_details(&request.call.name, &request.call.arguments);
                if app.running_tool.is_none() {
                    // The observer's ⏺ line already announced this call;
                    // only print one when there is none to flip later.
                    print_tool(transcript, &format!("⏺ {} · {}", request.call.name, tool_summary(&request.call.name, &request.call.arguments)));
                    app.running_tool = Some(transcript.blocks.len() - 1);
                }
                if !details.is_empty() {
                    print_dim(transcript, &details);
                }
                app.status = "Waiting for permission".to_owned();
                app.permission_choice = 0;
                app.permission_prompt = Some(format!("Permission for {}", request.call.name));
                app.permission_shown_at = Some(std::time::Instant::now());
                pending = Some(request);
                draw(terminal, app, transcript)?;
            }
            Some(key) = keys.recv() => {
                let key = key?;
                if pending.is_some() {
                    if let InputEvent::Key(key) = key && key.kind == KeyEventKind::Press {
                        let armed = app
                            .permission_shown_at
                            .is_none_or(|shown| shown.elapsed() >= PERMISSION_ARM_DELAY);
                        let decision = match key.code {
                            KeyCode::PageUp | KeyCode::PageDown => {
                                let pane_rows = LAST_PANE_ROWS
                                    .load(std::sync::atomic::Ordering::Relaxed)
                                    .max(1);
                                let page_delta = (pane_rows as isize - 1).max(1);
                                let delta = if key.code == KeyCode::PageUp {
                                    -page_delta
                                } else {
                                    page_delta
                                };
                                scroll_by(app, transcript, pane_rows, delta);
                                None
                            }
                            KeyCode::End if key.modifiers.contains(KeyModifiers::CONTROL) => {
                                app.scroll_pinned = true;
                                app.scroll_anchor = None;
                                app.new_output_baseline = None;
                                None
                            }
                            KeyCode::Up => {
                                app.permission_choice =
                                    (app.permission_choice + PERMISSION_OPTIONS.len() - 1)
                                        % PERMISSION_OPTIONS.len();
                                None
                            }
                            KeyCode::Down => {
                                app.permission_choice =
                                    (app.permission_choice + 1) % PERMISSION_OPTIONS.len();
                                None
                            }
                            KeyCode::Enter if !armed => None,
                            KeyCode::Enter => Some(match app.permission_choice {
                                1 => PermissionDecision::allow_for_session(),
                                2 => PermissionDecision::deny_once(),
                                3 => PermissionDecision {
                                    outcome: ToolPermissionOutcome::Denied,
                                    scope: ToolPermissionScope::Session,
                                    source: ToolPermissionSource::User,
                                },
                                _ => PermissionDecision::allow_once(),
                            }),
                            // Esc only denies, so it stays live while unarmed.
                            KeyCode::Esc => permission_decision(key),
                            _ if !armed => None,
                            _ => permission_decision(key),
                        };
                        if let Some(decision) = decision {
                            let _ = pending.take().expect("permission pending").reply.send(decision);
                            app.permission_prompt = None;
                            app.permission_shown_at = None;
                            app.permission_choice = 0;
                            app.status = "Working".to_owned();
                        } else if key.code == KeyCode::Char('c') && key.modifiers == KeyModifiers::CONTROL {
                            let _ = pending.take().expect("permission pending").reply.send(PermissionDecision::deny_once());
                            app.permission_prompt = None;
                            app.permission_shown_at = None;
                            app.permission_choice = 0;
                            cancellation.cancel();
                            app.status = "Cancelling".to_owned();
                        }
                    } else if let InputEvent::Mouse(mouse) = key {
                        use crossterm::event::MouseEventKind;
                        if matches!(mouse.kind, MouseEventKind::ScrollUp | MouseEventKind::ScrollDown) {
                            let pane_rows = LAST_PANE_ROWS
                                .load(std::sync::atomic::Ordering::Relaxed)
                                .max(1);
                            let delta = if mouse.kind == MouseEventKind::ScrollUp { -3 } else { 3 };
                            scroll_by(app, transcript, pane_rows, delta);
                        }
                    }
                } else if let InputEvent::Key(key) = key {
                    if key.kind == KeyEventKind::Press
                        && app.search.is_some()
                        && key.code == KeyCode::F(3)
                    {
                        app.step_search(transcript, !key.modifiers.contains(KeyModifiers::SHIFT));
                    } else if key.kind == KeyEventKind::Press
                        && key.code == KeyCode::End
                        && key.modifiers.contains(KeyModifiers::CONTROL)
                    {
                        app.scroll_pinned = true;
                        app.scroll_anchor = None;
                        app.new_output_baseline = None;
                        app.highlighted = None;
                    } else if key.kind == KeyEventKind::Press && key.code == KeyCode::Esc {
                        if !dismiss_temporary_state(app) {
                            cancellation.cancel();
                            app.status = "Cancelling".to_owned();
                        }
                    } else if key.kind == KeyEventKind::Press
                        && key.code == KeyCode::Char('c')
                        && key.modifiers == KeyModifiers::CONTROL
                    {
                        cancellation.cancel();
                        app.status = "Cancelling".to_owned();
                    } else if key.kind == KeyEventKind::Press && app.completion.is_none()
                        && (matches!(key.code, KeyCode::PageUp | KeyCode::PageDown)
                            || (matches!(key.code, KeyCode::Up | KeyCode::Down)
                                && !editor_has_multiple_visual_rows(
                                    &app.input,
                                    app.cursor,
                                    LAST_WIDTH
                                        .load(std::sync::atomic::Ordering::Relaxed)
                                        .max(1),
                                )))
                    {
                        // While a run is in flight the editor has nothing to
                        // do with these keys: they scroll the history pane
                        // and navigate blocks, exactly as when idle.
                        match key.code {
                            KeyCode::Up => navigate_blocks(transcript, app, true),
                            KeyCode::Down => navigate_blocks(transcript, app, false),
                            KeyCode::PageUp | KeyCode::PageDown => {
                                let pane_rows = LAST_PANE_ROWS
                                    .load(std::sync::atomic::Ordering::Relaxed)
                                    .max(1);
                                let page_delta = (pane_rows as isize - 1).max(1);
                                let delta = if key.code == KeyCode::PageUp {
                                    -page_delta
                                } else {
                                    page_delta
                                };
                                scroll_by(app, transcript, pane_rows, delta);
                            }
                            _ => {}
                        }
                    } else {
                        match handle_editor(app, InputEvent::Key(key)) {
                            EditorAction::Submit(text) => {
                                app.queued.push_back(text);
                                app.scroll_pinned = true;
                                app.scroll_anchor = None;
                                app.new_output_baseline = None;
                                app.highlighted = None;
                            }
                            EditorAction::None => {}
                            EditorAction::Exit => {}
                        }
                    }
                } else if let InputEvent::Mouse(mouse) = key {
                    // The wheel works mid-run too: reading back while the
                    // model streams is the main use of manual scrolling.
                    use crossterm::event::MouseEventKind;
                    if let MouseEventKind::ScrollUp | MouseEventKind::ScrollDown = mouse.kind {
                        let pane_rows = LAST_PANE_ROWS
                            .load(std::sync::atomic::Ordering::Relaxed)
                            .max(1);
                        let delta = if mouse.kind == MouseEventKind::ScrollUp { -3 } else { 3 };
                        scroll_by(app, transcript, pane_rows, delta);
                    }
                }
                draw(terminal, app, transcript)?;
            }
            _ = tick.tick() => draw(terminal, app, transcript)?,
        }
    };
    while let Ok(update) = ui_rx.try_recv() {
        if let UiEvent::Text(text) = update {
            app.live.push_str(&text);
        } else if app.show_thinking
            && let UiEvent::Reasoning(text) = update
        {
            app.live_reasoning.push_str(&text);
        }
    }
    flush_reasoning(transcript, app);
    flush_live(transcript, app);
    app.busy = false;
    app.permission_cleanup();
    match result {
        Ok(events) => {
            app.status = "Ready".to_owned();
            for event in events {
                match event.event {
                    Event::RunFailed { message } => {
                        app.status = "Failed".to_owned();
                        print_error(transcript, &format!("✗ {message}"));
                    }
                    Event::RunCancelled => {
                        app.status = "Cancelled".to_owned();
                        print_dim(transcript, "run cancelled");
                    }
                    _ => {}
                }
            }
        }
        Err(error) => {
            app.status = "Failed".to_owned();
            print_error(transcript, &error.to_string());
        }
    }
    draw(terminal, app, transcript)?;
    Ok(())
}

impl App {
    fn permission_cleanup(&mut self) {
        // Reserved for future pending-permission UI state.
    }
}

fn handle_editor(app: &mut App, event: InputEvent) -> EditorAction {
    if let InputEvent::Key(key) = &event {
        if !matches!(key.code, KeyCode::Up | KeyCode::Down) {
            app.vertical_column = None;
        }
    } else {
        app.vertical_column = None;
    }
    match event {
        InputEvent::Paste(text) => {
            app.insert(&text);
            EditorAction::None
        }
        InputEvent::Key(key) if key.kind == KeyEventKind::Press => match key {
            // View toggles work both idle and mid-run; they apply to output
            // printed after the toggle.
            KeyEvent {
                code: KeyCode::Char('o'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                app.verbose = !app.verbose;
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('t'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                app.show_thinking = !app.show_thinking;
                if !app.show_thinking {
                    app.live_reasoning.clear();
                }
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('c'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                if app.input.is_empty() {
                    return EditorAction::Exit;
                }
                app.input.clear();
                app.cursor = 0;
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('d'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                if app.input.is_empty() {
                    return EditorAction::Exit;
                }
                app.delete();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('a'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                app.cursor = app.input[..app.cursor.min(app.input.len())]
                    .rfind('\n')
                    .map_or(0, |index| index + 1);
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('e'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                app.cursor = cursor
                    + app.input[cursor..]
                        .find('\n')
                        .unwrap_or(app.input.len() - cursor);
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('u'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                let start = app.input[..cursor].rfind('\n').map_or(0, |index| index + 1);
                app.input.replace_range(start..cursor, "");
                app.cursor = start;
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('k'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                let end = cursor
                    + app.input[cursor..]
                        .find('\n')
                        .unwrap_or(app.input.len() - cursor);
                app.input.replace_range(cursor..end, "");
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Char('w'),
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                let before = &app.input[..cursor];
                let trimmed = before.trim_end();
                let start = trimmed
                    .rfind(char::is_whitespace)
                    .map_or(0, |index| index + 1);
                app.input.replace_range(start..cursor, "");
                app.cursor = start;
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Left,
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                let before = app.input[..cursor].trim_end();
                app.cursor = before
                    .rfind(char::is_whitespace)
                    .map_or(0, |index| index + 1);
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Right,
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                let after = &app.input[cursor..];
                let leading = after.len() - after.trim_start().len();
                let rest = &after[leading..];
                let word = rest.find(char::is_whitespace).unwrap_or(rest.len());
                app.cursor = cursor + leading + word;
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Up, ..
            } if app.completion.is_some() => {
                if let Some(completion) = app.completion.as_mut() {
                    completion.selected = completion.selected.saturating_sub(1);
                }
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Down,
                ..
            } if app.completion.is_some() => {
                if let Some(completion) = app.completion.as_mut() {
                    completion.selected =
                        (completion.selected + 1).min(completion.candidates.len() - 1);
                }
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Up, ..
            } if editor_has_multiple_visual_rows(
                &app.input,
                app.cursor,
                LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1),
            ) =>
            {
                app.move_vertical(true);
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Down,
                ..
            } if editor_has_multiple_visual_rows(
                &app.input,
                app.cursor,
                LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1),
            ) =>
            {
                app.move_vertical(false);
                EditorAction::None
            }
            KeyEvent {
                code: code @ (KeyCode::Enter | KeyCode::Tab),
                modifiers,
                ..
            } if app.completion.as_ref().is_some_and(|completion| {
                code == KeyCode::Tab || !completion.token_is_complete(&app.input)
            }) && !modifiers.contains(KeyModifiers::SHIFT)
                && !modifiers.contains(KeyModifiers::CONTROL) =>
            {
                app.apply_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Enter,
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::SHIFT)
                || modifiers.contains(KeyModifiers::ALT) =>
            {
                app.insert("\n");
                EditorAction::None
            }
            // Ctrl+J is a line feed in every terminal, so it is the newline
            // key that works without keyboard-protocol support.
            KeyEvent {
                code: KeyCode::Char('j'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                app.insert("\n");
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Enter,
                ..
            } => {
                let text = app.take_input();
                app.completion = None;
                EditorAction::Submit(text)
            }
            KeyEvent {
                code: KeyCode::Backspace,
                modifiers,
                ..
            } if modifiers.contains(KeyModifiers::CONTROL) => {
                let cursor = app.cursor.min(app.input.len());
                let before = &app.input[..cursor];
                let trimmed = before.trim_end();
                let start = trimmed
                    .rfind(char::is_whitespace)
                    .map_or(0, |index| index + 1);
                app.input.replace_range(start..cursor, "");
                app.cursor = start;
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Backspace,
                ..
            } => {
                app.backspace();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Delete,
                ..
            } => {
                app.delete();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Left,
                ..
            } => {
                if app.cursor > 0 {
                    let cursor = app.cursor.min(app.input.len());
                    app.cursor -= app.input[..cursor]
                        .grapheme_indices(true)
                        .next_back()
                        .map_or(0, |(start, _)| cursor - start);
                }
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Right,
                ..
            } => {
                if app.cursor < app.input.len() {
                    app.cursor += app.input[app.cursor..]
                        .graphemes(true)
                        .next()
                        .unwrap()
                        .len();
                }
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Home,
                ..
            } => {
                app.cursor = app.input[..app.cursor].rfind('\n').map_or(0, |i| i + 1);
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::End, ..
            } => {
                app.cursor += app.input[app.cursor..]
                    .find('\n')
                    .unwrap_or(app.input.len() - app.cursor);
                app.refresh_completion();
                EditorAction::None
            }
            KeyEvent {
                code: KeyCode::Esc, ..
            } => EditorAction::None,
            KeyEvent {
                code: KeyCode::Char(ch),
                modifiers,
                ..
            } if !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
                app.insert(&ch.to_string());
                EditorAction::None
            }
            _ => EditorAction::None,
        },
        _ => EditorAction::None,
    }
}

fn dismiss_temporary_state(app: &mut App) -> bool {
    if app.completion.take().is_some() {
        return true;
    }
    if app.resume_pick {
        app.resume_pick = false;
        app.pick_entries = None;
        return true;
    }
    if app.search.take().is_some() {
        return true;
    }
    app.highlighted.take().is_some()
}

// ---------------------------------------------------------------------------
// Slash commands (results are printed into the scrollback)
// ---------------------------------------------------------------------------

/// Returns true when the REPL should exit.
fn command(
    session: &mut InteractiveSession,
    app: &mut App,
    transcript: &mut Transcript,
    text: &str,
) -> bool {
    if matches!(text, "/exit" | "/quit") {
        return true;
    }
    match text {
        _ if is_find_command(text) => {
            let query = text.trim_start_matches("/find").trim().to_owned();
            if query.is_empty() {
                print_dim(
                    transcript,
                    "usage: /find <text>  (F3/Shift+F3 jump, Esc exits search)",
                );
            } else {
                app.start_search(transcript, query);
                let hits = app
                    .search
                    .as_ref()
                    .map(|search| search_hits(transcript, &search.query).len())
                    .unwrap_or(0);
                print_dim(
                    transcript,
                    &format!("search: {hits} matches (F3/Shift+F3 jump, Esc exits)"),
                );
            }
        }
        "/help" => {
            print_dim(
                transcript,
                "/help  /exit  /session  /sessions  /resume [id]  /find <text>  /context  /diff  /undo  /model [alias]  /policy [name]  /thinking [level]\nF3/Shift+F3 next/previous search result · Esc closes completion, search, then history selection · Ctrl+C clears the draft or exits when empty · Ctrl+D deletes forward or exits when empty · Ctrl+A/E line start/end · Ctrl+U/K delete to line edge · Ctrl+End latest · Ctrl+O verbose output · Ctrl+T show/hide thinking · @path mentions files\nHistory: PageUp/PageDown or mouse wheel scroll · click a block then Enter/c copies it · sending or queueing returns to latest\nPermission: Enter allows once by default · ↑↓ select · y/a allow once/session · n/v deny once/session · Esc denies once · Ctrl+C cancels the run · keys are ignored for a moment after a prompt opens",
            );
        }
        "/session" => {
            print_dim(
                transcript,
                &format!(
                    "session: {}\nworkspace: {}\nmodel: {}\nprovider: {}\nread only: {}\nshell: {}",
                    session.session_id,
                    session.runner_root.display(),
                    session.config.model,
                    session.config.api_type,
                    session.read_only,
                    session.allow_shell
                ),
            );
        }
        "/model" | "/policy" | "/thinking" => {
            print_dim(transcript, &session.selection_report());
        }
        "/diff" => {
            print_block(transcript, &session.write_report(), Style::default());
        }
        "/undo" => {
            let message = session.undo_last_write();
            print_artifact(transcript, &message);
        }
        "/context" => match context::report(session) {
            Ok(report) => {
                print_block(transcript, &report, theme::muted());
            }
            Err(error) => {
                print_error(transcript, &format!("context: {error}"));
            }
        },
        "/sessions" => match session.session_list() {
            Ok(lines) if lines.is_empty() => {
                print_dim(transcript, "no sessions found");
            }
            Ok(lines) => {
                print_dim(transcript, &lines.join("\n"));
            }
            Err(error) => {
                print_error(transcript, &error.to_string());
            }
        },
        "/resume" => {
            // List sessions and let the next input pick one.
            match session.session_list_entries() {
                Ok(entries) if entries.is_empty() => {
                    print_dim(transcript, "no sessions found");
                }
                Ok(entries) => {
                    let listing = entries
                        .iter()
                        .enumerate()
                        .map(|(index, entry)| format!("{:>3}. {}", index + 1, entry.line))
                        .collect::<Vec<_>>()
                        .join("\n");
                    print_dim(
                        transcript,
                        &format!("{listing}\nresume: type a number or id prefix (Esc cancels)"),
                    );
                    app.resume_pick = true;
                    app.pick_entries = Some(entries.into_iter().map(|entry| entry.id).collect());
                }
                Err(error) => {
                    print_error(transcript, &error.to_string());
                }
            }
        }
        _ if text.starts_with("/model ") => {
            let model = text.trim_start_matches("/model ").trim();
            if model.is_empty() {
                print_error(transcript, "usage: /model <name>");
            } else {
                match session.change_model(model) {
                    Ok(()) => {
                        print_tool(transcript, &format!("model: {model}"));
                    }
                    Err(error) => {
                        print_error(transcript, &error.to_string());
                    }
                }
            }
        }
        _ if text.starts_with("/policy ") => {
            let policy = text.trim_start_matches("/policy ").trim();
            match session.change_policy(policy) {
                Ok(()) => print_tool(transcript, &session.selection_report()),
                Err(error) => print_error(transcript, &error.to_string()),
            }
        }
        _ if text.starts_with("/thinking ") => {
            let level = text.trim_start_matches("/thinking ").trim();
            match session.change_thinking(level) {
                Ok(()) => {
                    print_tool(transcript, &format!("thinking: {level}"));
                }
                Err(error) => {
                    print_error(transcript, &error.to_string());
                }
            }
        }
        _ => {
            print_error(transcript, &format!("unknown command: {text}"));
        }
    }
    app.thinking_levels = crate::config::thinking_levels(session.config.api_type);
    false
}

/// How a line typed after a `/resume` listing resolves.
#[derive(Debug, PartialEq, Eq)]
enum ResumePick {
    Found(String),
    Ambiguous(String),
    OutOfRange(usize),
    /// Not a number and not an id prefix: ordinary input.
    NotAPick,
}

fn resolve_resume_pick(ids: &[String], text: &str) -> ResumePick {
    let trimmed = text.trim();
    if trimmed.is_empty() || trimmed.starts_with('/') {
        return ResumePick::NotAPick;
    }
    // A listed number wins; anything else is an id prefix first, since
    // time-ordered ids start with digits ("0190…").
    let number = trimmed.parse::<usize>().ok();
    if let Some(id) = number
        .and_then(|number| number.checked_sub(1))
        .and_then(|index| ids.get(index))
    {
        return ResumePick::Found(id.clone());
    }
    let mut matches = ids.iter().filter(|id| id.starts_with(trimmed));
    match (matches.next(), matches.next(), number) {
        (Some(id), None, _) => ResumePick::Found(id.clone()),
        (Some(_), Some(_), _) => ResumePick::Ambiguous(trimmed.to_owned()),
        (None, _, Some(number)) => ResumePick::OutOfRange(number),
        (None, _, None) => ResumePick::NotAPick,
    }
}

/// Replaces the session with `id`, keeping the terminal capabilities and
/// view toggles of the current app state.
async fn switch_session(
    session: &mut InteractiveSession,
    app: &mut App,
    transcript: &mut Transcript,
    id: &str,
) {
    match session.switch_to(id).await {
        Ok(next_session) => {
            *session = next_session;
            let mut next = App::new(session);
            next.keyboard_enhanced = app.keyboard_enhanced;
            next.verbose = app.verbose;
            next.show_thinking = app.show_thinking;
            next.file_index = Some(workspace_files(&session.runner_root));
            *app = next;
            transcript.clear();
            print_tool(transcript, &format!("session: {}", session.session_id));
            print_history(transcript, session);
        }
        Err(error) => print_error(transcript, &error.to_string()),
    }
}

fn is_find_command(text: &str) -> bool {
    let Some(suffix) = text.strip_prefix("/find") else {
        return false;
    };
    suffix.is_empty() || suffix.chars().next().is_some_and(char::is_whitespace)
}

// ---------------------------------------------------------------------------
// Entry points
// ---------------------------------------------------------------------------

fn print_history(transcript: &mut Transcript, session: &InteractiveSession) {
    let workspace = workspace_id_for(&session.runner_root);
    let stored = match session.session_store.read(&workspace, &session.session_id) {
        Ok(stored) => stored,
        Err(_) => return,
    };
    // Assistant responses arrive as many delta events; buffer each turn's
    // text so a reply renders as one paragraph, not one block per delta.
    // Thinking folds to a word-count summary, matching live rendering.
    let mut turns = 0usize;
    let mut pending_text = String::new();
    let mut pending_reasoning_words = 0usize;
    let mut pending_reasoning = false;
    // Running ⏺ lines by call id, flipped to ✓/✗ in place on completion
    // exactly as the live view does.
    let mut tool_blocks: BTreeMap<String, usize> = BTreeMap::new();
    for envelope in stored.events {
        match envelope.event {
            Event::MessageAccepted { content, .. } => {
                if !pending_text.is_empty() {
                    let text = std::mem::take(&mut pending_text);
                    print_text(transcript, text.trim());
                }
                if pending_reasoning {
                    print_dim(
                        transcript,
                        &format!("· thinking · {pending_reasoning_words} words"),
                    );
                    pending_reasoning = false;
                    pending_reasoning_words = 0;
                }
                print_user(transcript, &content);
                turns += 1;
            }
            Event::ModelResponseItem {
                item: RuntimeItem::Message(message),
                ..
            } if message.role == RuntimeRole::Assistant => {
                for block in &message.content {
                    if let ContentBlock::Text { text } = block {
                        pending_text.push_str(text);
                    }
                }
            }
            Event::ModelResponseItem {
                item: RuntimeItem::Reasoning(reasoning),
                ..
            } => {
                pending_reasoning_words += reasoning.summary.join(" ").split_whitespace().count();
                pending_reasoning = true;
            }
            Event::ToolCallRequested {
                call_id,
                name,
                arguments,
                ..
            } => {
                if !pending_text.is_empty() {
                    let text = std::mem::take(&mut pending_text);
                    print_text(transcript, text.trim());
                }
                if pending_reasoning {
                    print_dim(
                        transcript,
                        &format!("· thinking · {pending_reasoning_words} words"),
                    );
                    pending_reasoning = false;
                    pending_reasoning_words = 0;
                }
                print_tool(
                    transcript,
                    &format!("\u{23fa} {name} \u{b7} {}", tool_summary(&name, &arguments)),
                );
                tool_blocks.insert(call_id, transcript.blocks.len() - 1);
            }
            Event::ToolCallCompleted {
                call_id,
                name,
                is_error,
                ..
            } => {
                let status_line = if is_error {
                    Line::styled(format!("\u{2717} {name}"), theme::removed())
                } else {
                    Line::styled(format!("\u{2713} {name}"), theme::tool_ok())
                };
                let flipped = tool_blocks
                    .remove(&call_id)
                    .is_some_and(|block| flip_tool_line(transcript, block, status_line.clone()));
                if !flipped {
                    transcript.push_block(vec![status_line]);
                }
            }
            Event::ModelResponseCompleted { .. } => {
                if !pending_text.is_empty() {
                    let text = std::mem::take(&mut pending_text);
                    print_text(transcript, text.trim());
                }
                if pending_reasoning {
                    print_dim(
                        transcript,
                        &format!("· thinking · {pending_reasoning_words} words"),
                    );
                    pending_reasoning = false;
                    pending_reasoning_words = 0;
                }
            }
            _ => {}
        }
    }
    if !pending_text.is_empty() {
        let text = std::mem::take(&mut pending_text);
        print_text(transcript, text.trim());
    }
    if turns > 0 {
        print_dim(
            transcript,
            &format!("\u{2014} resumed session, {turns} earlier messages \u{2014}"),
        );
    }
}

async fn run_inner(
    config: ApiProviderConfig,
    options: InteractiveOptions,
) -> Result<i32, Box<dyn std::error::Error>> {
    let model = HostModel::Api(arabica_provider::ApiModelProvider::new(config.clone())?);
    run_inner_with_model(config, model, None, options).await
}

async fn run_inner_with_model(
    config: ApiProviderConfig,
    model: HostModel,
    blend_policy: Option<BlendRoutingPolicy>,
    options: InteractiveOptions,
) -> Result<i32, Box<dyn std::error::Error>> {
    run_inner_with_model_configs(config, model, blend_policy, BTreeMap::new(), options).await
}

async fn run_inner_with_model_configs(
    config: ApiProviderConfig,
    model: HostModel,
    blend_policy: Option<BlendRoutingPolicy>,
    model_configs: BTreeMap<String, ApiProviderConfig>,
    options: InteractiveOptions,
) -> Result<i32, Box<dyn std::error::Error>> {
    let mut session = InteractiveSession::open_with_model_configs(
        config,
        model,
        blend_policy,
        model_configs,
        options,
    )
    .await?;
    let mut app = App::new(&session);
    app.status = format!("session {}", session.session_id);

    enable_raw_mode()?;
    // Without the kitty keyboard protocol most terminals send Shift+Enter
    // as a bare carriage return, indistinguishable from Enter.
    let keyboard_enhanced = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false);
    let _guard = InlineGuard { keyboard_enhanced };
    app.keyboard_enhanced = keyboard_enhanced;
    crossterm::execute!(
        io::stdout(),
        crossterm::terminal::EnterAlternateScreen,
        crossterm::event::EnableBracketedPaste,
        crossterm::event::EnableMouseCapture
    )?;
    if keyboard_enhanced {
        crossterm::execute!(
            io::stdout(),
            crossterm::event::PushKeyboardEnhancementFlags(
                crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
            )
        )?;
    }
    let backend = ratatui::backend::CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend)?;

    let mut transcript = Transcript::default();
    // Startup banner: the Arabica mark in block characters, then the
    // brand line. Committed as one block so block navigation treats it
    // like any other content.
    transcript.push_block(vec![
        Line::styled(
            " \u{2591}\u{2592}\u{2593} \u{2591}\u{2592}\u{2593}   \u{2591}\u{2592}\u{2593}\u{2593}",
            theme::tool(),
        ),
        Line::styled(
            " \u{2593}\u{2592}\u{2591} \u{2593}\u{2592}\u{2591}   \u{2592}\u{2591}\u{2591}  arabica",
            theme::tool(),
        ),
        Line::styled(
            "  \u{2591}\u{2592}\u{2593}   \u{2591}\u{2592}    \u{2593}\u{2593}\u{2592}  a coding agent in your terminal",
            theme::muted(),
        ),
        Line::raw(String::new()),
    ]);
    print_history(&mut transcript, &session);
    app.file_index = Some(workspace_files(&session.runner_root));
    draw(&mut terminal, &app, &transcript)?;

    let mut keys = input_events();
    loop {
        let next = if let Some(text) = app.queued.pop_front() {
            Some(text)
        } else {
            let key = keys
                .receiver
                .recv()
                .await
                .ok_or("terminal input closed")??;
            // Scroll keys land here only when the editor does not consume
            // them (handled below); scrolling moves the history pane while
            // the input stays pinned. Any typed character snaps back to
            // the bottom.
            if let InputEvent::Mouse(mouse) = &key {
                use crossterm::event::{MouseEvent, MouseEventKind};
                let MouseEvent { kind, .. } = mouse;
                let mut dirty = false;
                let pane_rows = LAST_PANE_ROWS
                    .load(std::sync::atomic::Ordering::Relaxed)
                    .max(1);
                match kind {
                    MouseEventKind::ScrollUp => {
                        scroll_by(&mut app, &transcript, pane_rows, -3);
                        dirty = true;
                    }
                    MouseEventKind::ScrollDown => {
                        scroll_by(&mut app, &transcript, pane_rows, 3);
                        dirty = true;
                    }
                    MouseEventKind::Down(_button) => {
                        // Click a history row: highlight its block. Clicks
                        // elsewhere (e.g. the editor) just restore focus.
                        let rows = display_rows(
                            &transcript,
                            LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1),
                        );
                        let total = rows.len();
                        if (mouse.row as usize) < pane_rows && total > 0 {
                            let first_visible =
                                first_visible_row(&app, &rows, pane_rows.min(total));
                            let clicked_line =
                                (first_visible + mouse.row as usize).min(total.saturating_sub(1));
                            app.highlighted = Some(rows[clicked_line].block_index);
                            if app.scroll_pinned {
                                app.new_output_baseline = Some(transcript.blocks.len());
                            }
                            app.scroll_pinned = false;
                            dirty = true;
                        }
                    }
                    _ => {}
                }
                if dirty {
                    draw(&mut terminal, &app, &transcript)?;
                }
                continue;
            }
            if !app.busy
                && app.permission_prompt.is_none()
                && let InputEvent::Key(key) = &key
                && key.kind == KeyEventKind::Press
            {
                if key.code == KeyCode::End && key.modifiers.contains(KeyModifiers::CONTROL) {
                    app.scroll_pinned = true;
                    app.scroll_anchor = None;
                    app.highlighted = None;
                    app.new_output_baseline = None;
                    draw(&mut terminal, &app, &transcript)?;
                    continue;
                }
                // Search navigation has dedicated keys so every ordinary
                // character remains available to the draft editor.
                if app.search.is_some() && key.code == KeyCode::F(3) {
                    app.step_search(&transcript, !key.modifiers.contains(KeyModifiers::SHIFT));
                    draw(&mut terminal, &app, &transcript)?;
                    continue;
                }
                // Escape dismisses one transient state at a time.
                if key.code == KeyCode::Esc && dismiss_temporary_state(&mut app) {
                    draw(&mut terminal, &app, &transcript)?;
                    continue;
                }
                // Wheel-free environments: PageUp/PageDown page the pane.
                if app.completion.is_none()
                    && matches!(key.code, KeyCode::PageUp | KeyCode::PageDown)
                {
                    let pane_rows = LAST_PANE_ROWS
                        .load(std::sync::atomic::Ordering::Relaxed)
                        .max(1);
                    let page_delta = (pane_rows as isize - 1).max(1);
                    let delta = if key.code == KeyCode::PageUp {
                        -page_delta
                    } else {
                        page_delta
                    };
                    scroll_by(&mut app, &transcript, pane_rows, delta);
                    draw(&mut terminal, &app, &transcript)?;
                    continue;
                }
                if matches!(key.code, KeyCode::Up | KeyCode::Down)
                    && app.completion.is_none()
                    && !editor_has_multiple_visual_rows(
                        &app.input,
                        app.cursor,
                        LAST_WIDTH.load(std::sync::atomic::Ordering::Relaxed).max(1),
                    )
                {
                    // A multiline draft owns Up/Down for cursor movement;
                    // otherwise they navigate transcript blocks.
                    navigate_blocks(&transcript, &mut app, key.code == KeyCode::Up);
                    draw(&mut terminal, &app, &transcript)?;
                    continue;
                }
            }
            // With a block highlighted, Enter or c copies it.
            if app.input.is_empty()
                && app.completion.is_none()
                && !app.busy
                && let InputEvent::Key(key) = &key
                && key.kind == KeyEventKind::Press
                && app.highlighted.is_some()
                && (key.code == KeyCode::Enter
                    || (key.code == KeyCode::Char('c') && key.modifiers.is_empty()))
            {
                let block = app.highlighted.expect("checked above");
                let copied = match copy_block_to_clipboard(&transcript, block) {
                    Ok(copied) => copied,
                    Err(error) => {
                        print_error(&mut transcript, &error.to_string());
                        0
                    }
                };
                if copied > 0 {
                    print_dim(
                        &mut transcript,
                        &format!("  \u{29c9} copied {copied} lines"),
                    );
                }
                draw(&mut terminal, &app, &transcript)?;
                continue;
            }
            match handle_editor(&mut app, key) {
                EditorAction::None => None,
                EditorAction::Submit(text) => Some(text),
                EditorAction::Exit => break,
            }
        };
        if let Some(text) = next {
            if app.resume_pick {
                // Resolve the pending /resume selection. Input that cannot
                // be a pick (a command, or prose matching no session)
                // cancels the pick and is handled as usual, so it is never
                // swallowed.
                let ids = app.pick_entries.clone().unwrap_or_default();
                match resolve_resume_pick(&ids, &text) {
                    ResumePick::Found(id) => {
                        app.resume_pick = false;
                        app.pick_entries = None;
                        switch_session(&mut session, &mut app, &mut transcript, &id).await;
                        draw(&mut terminal, &app, &transcript)?;
                        continue;
                    }
                    ResumePick::Ambiguous(prefix) => {
                        print_error(
                            &mut transcript,
                            &format!(
                                "'{prefix}' matches more than one session; type more of the id"
                            ),
                        );
                        draw(&mut terminal, &app, &transcript)?;
                        continue;
                    }
                    ResumePick::OutOfRange(number) => {
                        print_error(
                            &mut transcript,
                            &format!("no session numbered {number}; pick 1-{}", ids.len()),
                        );
                        draw(&mut terminal, &app, &transcript)?;
                        continue;
                    }
                    ResumePick::NotAPick => {
                        app.resume_pick = false;
                        app.pick_entries = None;
                        print_dim(&mut transcript, "resume cancelled");
                    }
                }
            }
            if let Some(target) = text.strip_prefix("/resume ").map(str::trim)
                && !target.is_empty()
            {
                match session.session_list_entries() {
                    Ok(entries) => {
                        let ids: Vec<String> = entries.into_iter().map(|entry| entry.id).collect();
                        match resolve_resume_pick(&ids, target) {
                            ResumePick::Found(id) => {
                                switch_session(&mut session, &mut app, &mut transcript, &id).await;
                            }
                            ResumePick::Ambiguous(prefix) => print_error(
                                &mut transcript,
                                &format!(
                                    "'{prefix}' matches more than one session; type more of the id"
                                ),
                            ),
                            ResumePick::OutOfRange(_) | ResumePick::NotAPick => print_error(
                                &mut transcript,
                                &format!("no session matches '{target}' (see /sessions)"),
                            ),
                        }
                    }
                    Err(error) => print_error(&mut transcript, &error.to_string()),
                }
                draw(&mut terminal, &app, &transcript)?;
                continue;
            }
            if text.starts_with('/') {
                if command(&mut session, &mut app, &mut transcript, &text) {
                    break;
                }
            } else if !text.trim().is_empty() {
                app.scroll_pinned = true;
                app.scroll_anchor = None;
                app.new_output_baseline = None;
                app.highlighted = None;
                run_turn(
                    &mut session,
                    &mut app,
                    &mut terminal,
                    &mut transcript,
                    &mut keys.receiver,
                    text,
                )
                .await?;
            }
        }
        draw(&mut terminal, &app, &transcript)?;
    }
    Ok(0)
}

pub async fn run(config: ApiProviderConfig, options: InteractiveOptions) -> i32 {
    if options.allow_shell && options.read_only {
        eprintln!("error: --allow-shell and --read-only are mutually exclusive");
        return 2;
    }
    match run_inner(config, options).await {
        Ok(code) => code,
        Err(error) => {
            eprintln!("error: {error}");
            1
        }
    }
}

pub async fn run_with_model(
    config: ApiProviderConfig,
    model: HostModel,
    blend_policy: Option<BlendRoutingPolicy>,
    options: InteractiveOptions,
) -> i32 {
    run_with_model_configs(config, model, blend_policy, BTreeMap::new(), options).await
}

pub async fn run_with_model_configs(
    config: ApiProviderConfig,
    model: HostModel,
    blend_policy: Option<BlendRoutingPolicy>,
    model_configs: BTreeMap<String, ApiProviderConfig>,
    options: InteractiveOptions,
) -> i32 {
    if options.allow_shell && options.read_only {
        eprintln!("error: --allow-shell and --read-only are mutually exclusive");
        return 2;
    }
    match run_inner_with_model_configs(config, model, blend_policy, model_configs, options).await {
        Ok(code) => code,
        Err(error) => {
            eprintln!("error: {error}");
            1
        }
    }
}

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

    #[test]
    fn live_tail_shows_the_newest_text_of_the_last_line() {
        assert_eq!(live_tail("short", 10), "short");
        assert_eq!(live_tail("first\nsecond\n", 10), "second");
        assert_eq!(live_tail("abcdefghijkl", 5), "…ijkl");
        assert_eq!(live_tail("前文字符", 5), "…字符");
    }

    #[test]
    fn committable_prefix_holds_back_open_fences() {
        // Plain prose: every complete line commits immediately.
        assert_eq!(
            committable_prefix("hello\nworld\npartial"),
            "hello\nworld\n".len()
        );
        assert_eq!(committable_prefix("no newline yet"), 0);

        // A fence opens: prose before it commits, everything after holds.
        let text = "Look:\n```rust\nfn main() {}\nstill inside\n";
        assert_eq!(committable_prefix(text), "Look:\n```rust\n".len());

        // Once the fence closes, everything commits again.
        let closed = "Look:\n```rust\ncode\n```\nafter\nmore\n";
        assert_eq!(committable_prefix(closed), closed.len());

        // Two fences on and off.
        let twice = "```\na\n```\ntext\n```\nb\n";
        assert_eq!(committable_prefix(twice), "```\na\n```\ntext\n```\n".len());

        // Indented fence delimiters still count.
        assert_eq!(committable_prefix("  ```\nbody\n"), "  ```\n".len());
    }

    #[test]
    fn line_matches_finds_all_case_insensitive_hits() {
        assert_eq!(
            line_matches("Hello hello HELLO", "hello"),
            vec![(0, 5), (6, 11), (12, 17)]
        );
        assert!(line_matches("nothing", "xyz").is_empty());
        assert!(line_matches("anything", "").is_empty());
        // Unicode-safe: byte offsets land on char boundaries.
        // Lowercasing can change byte lengths ("É" 2B -> "é" 2B stays, but
        // offsets still shift); assert boundaries only.
        let hits = line_matches("héllo HÉLLO", "héllo");
        assert_eq!(hits.len(), 2);
    }

    #[test]
    fn search_hits_walks_all_lines_in_order() {
        let mut transcript = Transcript::default();
        transcript.push_block(vec![Line::raw("alpha bravo")]);
        transcript.push_block(vec![Line::raw("bravo alpha"), Line::raw("none here")]);
        let hits = search_hits(&transcript, "alpha");
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0].line, 0);
        assert_eq!(hits[1].line, 1);
    }

    #[test]
    fn permission_choices_name_their_scope_and_default_to_allow_once() {
        let app = App::default();
        assert_eq!(app.permission_choice, 0);
        assert_eq!(
            PERMISSION_OPTIONS,
            [
                "Allow once",
                "Allow this session",
                "Deny once",
                "Deny this session",
            ]
        );

        let cases = [
            (
                KeyCode::Char('y'),
                ToolPermissionOutcome::Allowed,
                ToolPermissionScope::Once,
            ),
            (
                KeyCode::Char('a'),
                ToolPermissionOutcome::Allowed,
                ToolPermissionScope::Session,
            ),
            (
                KeyCode::Char('n'),
                ToolPermissionOutcome::Denied,
                ToolPermissionScope::Once,
            ),
            (
                KeyCode::Esc,
                ToolPermissionOutcome::Denied,
                ToolPermissionScope::Once,
            ),
            (
                KeyCode::Char('v'),
                ToolPermissionOutcome::Denied,
                ToolPermissionScope::Session,
            ),
        ];
        for (code, outcome, scope) in cases {
            let decision = permission_decision(KeyEvent::new(code, KeyModifiers::NONE)).unwrap();
            assert_eq!(decision.outcome, outcome);
            assert_eq!(decision.scope, scope);
        }
    }

    #[test]
    fn permission_choices_stack_on_narrow_terminals_and_stay_visible() {
        let prompt = "Permission for write_file";
        let (vertical, lines) = permission_lines(prompt, 0, 28);
        assert!(vertical);
        let content = lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>();
        let joined = content.join("\n");
        for label in [
            prompt,
            "Allow once",
            "Allow this session",
            "Deny once",
            "Deny this session",
            "Enter",
            "Ctrl+C",
        ] {
            assert!(joined.contains(label), "missing {label:?} in {joined:?}");
        }

        let app = App {
            permission_prompt: Some(prompt.to_owned()),
            ..Default::default()
        };
        let layout = fullscreen_layout(Rect::new(0, 0, 28, 18), &app);
        let tail = layout
            .tail_index
            .expect("permission chooser has a fixed area");
        assert_eq!(layout.sections[tail].height as usize, lines.len());
        let backend = ratatui::backend::TestBackend::new(28, 18);
        let mut terminal = Terminal::new(backend).unwrap();
        let transcript = Transcript::default();
        terminal
            .draw(|frame| render_fullscreen(frame, &app, &transcript))
            .unwrap();
    }

    #[test]
    fn base64_encodes_the_standard_alphabet() {
        assert_eq!(base64(b""), "");
        assert_eq!(base64(b"f"), "Zg==");
        assert_eq!(base64(b"fo"), "Zm8=");
        assert_eq!(base64(b"foo"), "Zm9v");
        assert_eq!(base64(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn flip_tool_line_replaces_single_row_blocks_only() {
        let mut transcript = Transcript::default();
        transcript.push_block(vec![Line::styled(
            "⏺ read_file a.txt".to_owned(),
            theme::tool(),
        )]);
        transcript.push_block(vec![Line::raw("diff line 1"), Line::raw("diff line 2")]);
        assert!(flip_tool_line(
            &mut transcript,
            0,
            Line::styled("✓ read_file a.txt".to_owned(), theme::tool_ok())
        ));
        assert_eq!(transcript.lines[0].spans[0].content, "✓ read_file a.txt");
        // Multi-row blocks are refused so row counts stay stable.
        assert!(!flip_tool_line(&mut transcript, 1, Line::raw("nope")));
        assert_eq!(transcript.lines[1].spans[0].content, "diff line 1");
        assert!(!flip_tool_line(
            &mut transcript,
            99,
            Line::raw("out of range")
        ));
    }

    #[test]
    fn editor_handles_multiline_and_unicode_backspace() {
        let mut app = App::default();
        app.insert("你好");
        app.insert("\nworld");
        app.backspace();
        assert_eq!(app.input, "你好\nworl");
        app.cursor = "你".len();
        app.backspace();
        assert_eq!(app.input, "好\nworl");
        app.cursor = 0;
    }

    #[test]
    fn cursor_column_uses_only_text_before_the_cursor_on_its_line() {
        assert_eq!(layout_editor("hello world", 7, 40).cursor_column, 9);
        assert_eq!(layout_editor("first\nsecond", 9, 40).cursor_column, 5);
    }

    #[test]
    fn editor_supports_terminal_shortcuts() {
        let key = |ch| InputEvent::Key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL));
        let mut app = App::default();
        app.insert("hello world");
        assert!(matches!(
            handle_editor(&mut app, key('a')),
            EditorAction::None
        ));
        assert_eq!(app.cursor, 0);
        assert!(matches!(
            handle_editor(&mut app, key('e')),
            EditorAction::None
        ));
        assert_eq!(app.cursor, app.input.len());
        assert!(matches!(
            handle_editor(&mut app, key('w')),
            EditorAction::None
        ));
        assert_eq!(app.input, "hello ");
        assert!(matches!(
            handle_editor(&mut app, key('k')),
            EditorAction::None
        ));
        assert_eq!(app.input, "hello ");
        app.cursor = 5;
        assert!(matches!(
            handle_editor(&mut app, key('u')),
            EditorAction::None
        ));
        assert_eq!(app.input, " ");
        app.insert("x");
        app.cursor = 0;
        assert!(matches!(
            handle_editor(&mut app, key('d')),
            EditorAction::None
        ));
        assert_eq!(app.input, " ");
        assert!(matches!(
            handle_editor(&mut app, key('c')),
            EditorAction::None
        ));
        assert!(app.input.is_empty());
        assert!(matches!(
            handle_editor(&mut app, key('d')),
            EditorAction::Exit
        ));
    }

    #[test]
    fn multiline_editor_moves_vertically_and_keeps_its_column() {
        let mut app = App::default();
        app.insert("first line\nx\nlast line");
        app.cursor = app.input.len() - 2;

        assert!(matches!(
            handle_editor(
                &mut app,
                InputEvent::Key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE))
            ),
            EditorAction::None
        ));
        assert_eq!(&app.input[app.cursor..], "\nlast line");
        assert_eq!(app.input[..app.cursor].rsplit('\n').next(), Some("x"));

        assert!(matches!(
            handle_editor(
                &mut app,
                InputEvent::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE))
            ),
            EditorAction::None
        ));
        assert_eq!(&app.input[app.cursor..], "ne");
        assert_eq!(app.input[..app.cursor].rsplit('\n').next(), Some("last li"));
    }

    #[test]
    fn completion_for_slash_and_file_tokens() {
        let files = vec!["src/main.rs".to_owned()];
        let models = vec!["m1".to_owned(), "m2".to_owned()];
        let slash = completion_for("/con", 4, &files, &models, &[], THINKING_LEVELS).unwrap();
        assert_eq!(slash.candidates, vec!["/context"]);
        let none = completion_for("/help", 5, &files, &models, &[], THINKING_LEVELS);
        assert!(none.is_none());
        let file = completion_for("@ma", 3, &files, &models, &[], THINKING_LEVELS).unwrap();
        assert_eq!(file.candidates, vec!["@src/main.rs"]);
        let model = completion_for("/model ", 7, &files, &models, &[], THINKING_LEVELS).unwrap();
        assert_eq!(model.candidates.len(), 2);
        let policies = vec!["routine".to_owned(), "precise".to_owned()];
        let policy = completion_for(
            "/policy pre",
            11,
            &files,
            &models,
            &policies,
            THINKING_LEVELS,
        )
        .unwrap();
        assert_eq!(policy.candidates, vec!["precise"]);
    }

    #[test]
    fn find_command_accepts_a_query_argument_without_matching_prefixes() {
        assert!(is_find_command("/find"));
        assert!(is_find_command("/find needle text"));
        assert!(!is_find_command("/findneedle"));
        assert!(!is_find_command("/finder"));
    }

    #[test]
    fn apply_completion_replaces_the_token() {
        let mut app = App {
            models: vec!["alpha".to_owned()],
            ..Default::default()
        };
        app.insert("/model al");
        assert!(app.completion.is_some());
        app.apply_completion();
        assert_eq!(app.input, "/model alpha");
    }

    #[test]
    fn search_letters_remain_editable_and_escape_preserves_the_draft() {
        let mut app = App {
            search: Some(Search {
                query: "match".to_owned(),
                current: 0,
                pinned: false,
            }),
            ..Default::default()
        };
        assert!(matches!(
            handle_editor(
                &mut app,
                InputEvent::Key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE))
            ),
            EditorAction::None
        ));
        assert_eq!(app.input, "n");
        assert!(matches!(
            handle_editor(
                &mut app,
                InputEvent::Key(KeyEvent::new(KeyCode::Char('N'), KeyModifiers::SHIFT))
            ),
            EditorAction::None
        ));
        assert_eq!(app.input, "nN");
        assert!(matches!(
            handle_editor(
                &mut app,
                InputEvent::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
            ),
            EditorAction::None
        ));
        assert_eq!(app.input, "nN");
    }

    #[test]
    fn escape_dismisses_completion_search_and_history_one_at_a_time() {
        let mut app = App {
            input: "keep this".to_owned(),
            completion: Some(CompletionView {
                replace_start: 0,
                replace_end: 4,
                candidates: vec!["kept".to_owned()],
                selected: 0,
            }),
            search: Some(Search {
                query: "match".to_owned(),
                current: 0,
                pinned: false,
            }),
            highlighted: Some(2),
            ..Default::default()
        };
        assert!(dismiss_temporary_state(&mut app));
        assert!(app.completion.is_none());
        assert!(app.search.is_some());
        assert!(app.highlighted.is_some());
        assert!(dismiss_temporary_state(&mut app));
        assert!(app.search.is_none());
        assert!(app.highlighted.is_some());
        assert!(dismiss_temporary_state(&mut app));
        assert!(app.highlighted.is_none());
        assert!(!dismiss_temporary_state(&mut app));
        assert_eq!(app.input, "keep this");
    }

    #[test]
    fn horizontal_cursor_motion_refreshes_completion_range() {
        let mut app = App {
            models: vec!["alpha".to_owned(), "alps".to_owned()],
            ..Default::default()
        };
        app.insert("/model alp");
        assert!(app.completion.is_some());
        handle_editor(
            &mut app,
            InputEvent::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)),
        );
        let completion = app.completion.as_ref().unwrap();
        assert_eq!(completion.replace_end, app.input.len());
        assert_eq!(completion.candidates, vec!["alpha", "alps"]);
    }

    #[test]
    fn control_right_counts_skipped_spaces() {
        let mut app = App::default();
        app.insert("word   next");
        app.cursor = "word".len();
        handle_editor(
            &mut app,
            InputEvent::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL)),
        );
        assert_eq!(app.cursor, app.input.len());
    }

    #[test]
    fn tool_summary_names_the_target() {
        assert_eq!(
            tool_summary("write_file", &json!({"path": "a.txt", "content": "hello"})),
            "a.txt (5 bytes)"
        );
        assert_eq!(
            tool_summary(
                "edit_files",
                &json!({"edits": [
                    {"path": "a.txt", "old_string": "x", "new_string": "y"},
                    {"path": "a.txt", "old_string": "y", "new_string": "z"},
                    {"path": "b.txt", "old_string": "1", "new_string": "2"}
                ]})
            ),
            "3 edits in a.txt, b.txt"
        );
        assert_eq!(
            tool_summary("delete_file", &json!({"path": "b.txt"})),
            "b.txt"
        );
        assert_eq!(
            tool_summary("shell", &json!({"command": "cargo test"})),
            "cargo test"
        );
    }

    #[test]
    fn movement_diff_lines_color_and_fold() {
        let movement = checkpoint::FileMovement {
            path: "note.txt".to_owned(),
            before: Some(b"alpha\nbeta\n".to_vec()),
            after: Some(b"alpha\ngamma\n".to_vec()),
        };
        let lines = movement_diff_lines(&movement, usize::MAX);
        assert!(lines[0].spans[0].content.contains("note.txt"), "{lines:?}");
        assert!(lines[0].spans[0].content.contains("+1 -1"), "{lines:?}");
        let rendered: Vec<String> = lines
            .iter()
            .map(|line| line.spans.iter().map(|span| span.content.clone()).collect())
            .collect();
        assert!(
            rendered.iter().any(|line| line.contains("-beta")),
            "{rendered:?}"
        );
        assert!(
            rendered.iter().any(|line| line.contains("+gamma")),
            "{rendered:?}"
        );

        // Folding truncates the body and says how to expand it.
        let long = checkpoint::FileMovement {
            path: "big.txt".to_owned(),
            before: Some(Vec::new()),
            after: Some("line\n".repeat(50).into_bytes()),
        };
        let folded = movement_diff_lines(&long, 5);
        assert!(folded.len() < 10, "{folded:?}");
        let rendered: String = folded
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.clone())
                    .collect::<String>()
            })
            .collect();
        assert!(rendered.contains("Ctrl+O"), "{rendered}");
    }

    #[test]
    fn wrap_styled_respects_display_width() {
        // Wide CJK characters count as two columns.
        let lines = wrap_styled("你好世界x", 5, Style::default());
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert_eq!(lines[0].spans[0].content, "你好");
        assert_eq!(lines[1].spans[0].content, "世界x");
    }

    #[test]
    fn unicode_wrap_keeps_combining_and_emoji_graphemes_intact() {
        let text = "A界e\u{301}👩\u{200d}💻B";
        let lines = wrap_styled(text, 4, Style::default());
        assert!(lines.iter().all(|line| {
            let plain: String = line
                .spans
                .iter()
                .map(|span| span.content.as_ref())
                .collect();
            UnicodeWidthStr::width(plain.as_str()) <= 4
        }));
        let rendered: String = lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect();
        assert_eq!(rendered, text);
        assert!(lines.iter().any(|line| {
            line.spans
                .iter()
                .any(|span| span.content.contains("👩\u{200d}💻"))
        }));
    }

    #[test]
    fn editor_expands_and_tracks_cursor_through_wrapped_unicode_text() {
        let input = "a界bc\ne\u{301}👩\u{200d}💻";
        let layout = layout_editor(input, input.len(), 6);
        assert_eq!(layout.rows.len(), 3);
        assert_eq!(layout.cursor_row, 2);
        assert_eq!(layout.cursor_column, 5);
    }

    #[test]
    fn composer_grows_to_eight_rows_or_one_third_of_the_viewport() {
        assert_eq!(composer_height(24, 20), 8);
        assert_eq!(composer_height(9, 20), 3);
        assert_eq!(composer_height(2, 20), 1);
        assert_eq!(composer_height(24, 2), 2);
    }

    #[test]
    fn fullscreen_render_handles_tiny_and_normal_terminal_sizes() {
        let mut transcript = Transcript::default();
        print_text(
            &mut transcript,
            "a long history line that must reflow as the terminal changes width",
        );
        let app = App {
            input: "a long draft that wraps over several lines\nwith another line".to_owned(),
            cursor: 5,
            ..Default::default()
        };
        for (width, height) in [(1, 1), (8, 2), (12, 4), (80, 24)] {
            let backend = ratatui::backend::TestBackend::new(width, height);
            let mut terminal = Terminal::new(backend).unwrap();
            terminal
                .draw(|frame| render_fullscreen(frame, &app, &transcript))
                .unwrap();
        }
    }

    #[test]
    fn editor_vertical_motion_follows_wrapped_rows_and_keeps_goal_column() {
        let input = "abcdefghi\nx\n123456789";
        let (cursor, column) = vertical_cursor_move(input, 3, false, None, 8).unwrap();
        assert_eq!((cursor, column), (9, 5));
        let (cursor, column) = vertical_cursor_move(input, cursor, false, Some(column), 8).unwrap();
        assert_eq!((cursor, column), (11, 5));
        let (cursor, column) = vertical_cursor_move(input, cursor, false, Some(column), 8).unwrap();
        assert_eq!((cursor, column), (15, 5));
    }

    #[test]
    fn editor_moves_and_deletes_by_grapheme_cluster() {
        let mut app = App::default();
        app.insert("e\u{301}👩\u{200d}💻");
        handle_editor(
            &mut app,
            InputEvent::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)),
        );
        assert_eq!(&app.input[app.cursor..], "👩\u{200d}💻");
        app.delete();
        assert_eq!(app.input, "e\u{301}");
        app.backspace();
        assert!(app.input.is_empty());
    }

    #[test]
    fn resize_reflows_history_without_losing_the_reading_anchor() {
        let mut transcript = Transcript::default();
        transcript.push_block(vec![Line::raw("abcdefghijklmnopqrstuvwxyz")]);
        let narrow = display_rows(&transcript, 10);
        let wide = display_rows(&transcript, 20);
        assert_eq!(narrow.len(), 3);
        assert_eq!(wide.len(), 2);
        let mut app = App::default();
        app.set_scroll_anchor(&narrow, 2);
        app.scroll_pinned = false;
        let visible = first_visible_row(&app, &wide, 1);
        assert_eq!(wide[visible].byte_offset, 20);
    }

    #[test]
    fn search_highlight_continues_across_reflowed_rows() {
        let mut transcript = Transcript::default();
        transcript.push_block(vec![Line::raw("abcdefgh")]);
        let rows = display_rows(&transcript, 5);
        assert_eq!(
            display_hit_ranges(&transcript, &rows[0], "def"),
            vec![(3, 5)]
        );
        assert_eq!(
            display_hit_ranges(&transcript, &rows[1], "def"),
            vec![(0, 1)]
        );
    }

    #[test]
    fn user_message_copy_text_keeps_source_newlines_without_display_prefixes() {
        let mut transcript = Transcript::default();
        print_user(&mut transcript, "first\nsecond");
        assert_eq!(transcript.copy_texts[1].as_deref(), Some("first\nsecond"));
        assert_eq!(transcript.lines[1].spans[0].content, "> ");
        assert_eq!(transcript.lines[2].spans[0].content, "  ");
    }

    #[test]
    fn paint_row_keeps_the_line_style_and_highlight_extends_it() {
        // Transcript rows carry their theme color as a line style (that is
        // what Line::styled/wrap_styled produce); the renderer must keep it
        // when rebuilding rows for Paragraph, which reads only spans.
        let source = Line::styled("plan.".to_owned(), theme::tool());
        let row = paint_row(&source);
        assert_eq!(row.style.fg, Some(Color::Yellow));

        let mut highlighted = paint_row(&source);
        highlighted.style = highlighted.style.add_modifier(Modifier::REVERSED);
        assert_eq!(
            highlighted.style.add_modifier,
            Modifier::REVERSED,
            "highlight extends, not replaces, the style"
        );
        assert_eq!(highlighted.style.fg, Some(Color::Yellow));
    }

    /// A transcript of `blocks` one-row blocks, pane shows `visible`.
    fn scrolled_transcript(blocks: usize) -> Transcript {
        let mut transcript = Transcript::default();
        for index in 0..blocks {
            transcript.push_block(vec![Line::raw(format!("row {index}"))]);
        }
        transcript
    }

    #[test]
    fn scroll_by_moves_from_the_bottom_and_re_engages_follow_at_the_bottom() {
        // 100 rows, 10 visible: pinned at the bottom (offset 90).
        let transcript = scrolled_transcript(100);
        let rows = display_rows(&transcript, 80);
        let mut app = App::default();
        let visible = 10;
        assert_eq!(first_visible_row(&app, &rows, visible), 90);

        // One wheel up: three rows up, follow off.
        scroll_by(&mut app, &transcript, visible, -3);
        assert_eq!(first_visible_row(&app, &rows, visible), 87);
        assert!(!app.scroll_pinned);

        // More up, never past the top.
        scroll_by(&mut app, &transcript, visible, -1000);
        assert_eq!(first_visible_row(&app, &rows, visible), 0);
        scroll_by(&mut app, &transcript, visible, -3);
        assert_eq!(first_visible_row(&app, &rows, visible), 0);

        // Down past the bottom: clamps and re-engages follow.
        scroll_by(&mut app, &transcript, visible, 1000);
        assert_eq!(first_visible_row(&app, &rows, visible), 90);
        assert!(app.scroll_pinned);
    }

    #[test]
    fn navigate_blocks_scrolls_the_target_into_view_and_lands_on_follow() {
        let transcript = scrolled_transcript(30);
        let rows = display_rows(&transcript, 80);
        let mut app = App::default();
        // With no highlight, Up starts from the last block (29).
        navigate_blocks(&transcript, &mut app, true);
        assert_eq!(app.highlighted, Some(28));
        // The target block's first row lands one quarter down the pane
        // (LAST_PANE_ROWS defaults to 18: offset 24), and the renderer's
        // clamp folds that into the last screenful (offset 12), putting
        // block 28 in view -- never a mirrored position from the bottom.
        let visible = 18;
        assert_eq!(app.scroll_offset_rows, 24);
        assert_eq!(first_visible_row(&app, &rows, visible), 12);
        assert!(!app.scroll_pinned);

        // Walking all the way back down to the last block re-pins follow.
        for _ in 0..29 {
            navigate_blocks(&transcript, &mut app, false);
        }
        assert_eq!(app.highlighted, Some(29));
        assert!(app.scroll_pinned);
    }

    #[test]
    fn search_anchor_moves_with_the_hit_and_manual_scroll_releases_it() {
        // Two unique queries so hits are unambiguous across 100 rows.
        let mut transcript = scrolled_transcript(100);
        transcript.push_block(vec![Line::raw("needle alpha")]);
        transcript.push_block(vec![Line::raw("filler")]);
        transcript.push_block(vec![Line::raw("needle beta")]);
        let mut app = App::default();
        let rows = display_rows(&transcript, 80);
        app.start_search(&transcript, "needle".to_owned());
        // First hit is "needle alpha" (line 100); anchored one row above.
        assert_eq!(app.scroll_offset_rows, 99);

        // n steps to "needle beta" (line 102) and re-anchors there.
        app.step_search(&transcript, true);
        assert_eq!(app.scroll_offset_rows, 101);
        assert!(app.search.as_ref().is_some_and(|search| search.pinned));

        // Wheel scroll releases the anchor; the view moves with the wheel
        // (the anchor was clamped to the last screenful at 103-10=93).
        scroll_by(&mut app, &transcript, 10, -3);
        assert!(app.search.as_ref().is_some_and(|search| !search.pinned));
        assert_eq!(first_visible_row(&app, &rows, 10), 90);

        // n re-engages the anchor, wrapping from the last hit back to the
        // first ("needle alpha", anchored one row above it).
        app.step_search(&transcript, true);
        assert_eq!(app.scroll_offset_rows, 99);
        assert!(app.search.as_ref().is_some_and(|search| search.pinned));
    }

    #[test]
    fn enter_submits_a_command_that_is_already_complete() {
        let enter = || InputEvent::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let tab = || InputEvent::Key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
        let mut app = App::default();
        app.insert("/session");
        assert!(app.completion.is_some(), "/sessions is still offered");
        assert!(matches!(
            handle_editor(&mut app, enter()),
            EditorAction::Submit(text) if text == "/session"
        ));
        assert!(app.completion.is_none());

        // A partial token still completes on Enter, and Tab always does.
        app.insert("/ses");
        assert!(matches!(
            handle_editor(&mut app, enter()),
            EditorAction::None
        ));
        assert_eq!(app.input, "/session");
        app.insert("s");
        app.input = "/sessio".to_owned();
        app.cursor = app.input.len();
        app.refresh_completion();
        assert!(matches!(handle_editor(&mut app, tab()), EditorAction::None));
        assert!(app.input.starts_with("/session"));
    }

    #[test]
    fn completion_row_keeps_the_selection_visible() {
        let completion = CompletionView {
            replace_start: 0,
            replace_end: 1,
            candidates: (0..30).map(|index| format!("@file{index:02}.rs")).collect(),
            selected: 25,
        };
        let spans = completion_spans(&completion, 40);
        let text: String = spans.iter().map(|span| span.content.as_ref()).collect();
        assert!(text.contains("[@file25.rs]"), "{text}");
        assert!(text.starts_with('…') && text.ends_with('…'), "{text}");
        assert!(UnicodeWidthStr::width(text.as_str()) <= 40, "{text}");

        let first = CompletionView {
            selected: 0,
            ..completion
        };
        let text: String = completion_spans(&first, 40)
            .iter()
            .map(|span| span.content.as_ref())
            .collect();
        assert!(text.starts_with(" [@file00.rs]"), "{text}");
    }

    #[test]
    fn resume_pick_resolves_numbers_prefixes_and_ordinary_input() {
        let ids = vec![
            "0190aaaa".to_owned(),
            "0190aabb".to_owned(),
            "0191cccc".to_owned(),
        ];
        assert_eq!(
            resolve_resume_pick(&ids, "2"),
            ResumePick::Found("0190aabb".to_owned())
        );
        assert_eq!(resolve_resume_pick(&ids, "9"), ResumePick::OutOfRange(9));
        // "0" is no listed number but prefixes every time-ordered id.
        assert_eq!(
            resolve_resume_pick(&ids, "0"),
            ResumePick::Ambiguous("0".to_owned())
        );
        assert_eq!(
            resolve_resume_pick(&ids, "0191"),
            ResumePick::Found("0191cccc".to_owned())
        );
        assert_eq!(
            resolve_resume_pick(&ids, "0190aa"),
            ResumePick::Ambiguous("0190aa".to_owned())
        );
        assert_eq!(
            resolve_resume_pick(&ids, "fix the tests"),
            ResumePick::NotAPick
        );
        assert_eq!(resolve_resume_pick(&ids, "/help"), ResumePick::NotAPick);
        assert_eq!(resolve_resume_pick(&ids, "  "), ResumePick::NotAPick);
    }

    #[test]
    fn escape_cancels_a_pending_resume_pick() {
        let mut app = App {
            resume_pick: true,
            pick_entries: Some(vec!["0190aaaa".to_owned()]),
            ..Default::default()
        };
        assert!(dismiss_temporary_state(&mut app));
        assert!(!app.resume_pick);
        assert!(app.pick_entries.is_none());
    }

    #[test]
    fn view_toggles_work_from_the_editor() {
        let key = |ch| InputEvent::Key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL));
        let mut app = App {
            live_reasoning: "partial thought".to_owned(),
            ..Default::default()
        };
        handle_editor(&mut app, key('o'));
        assert!(app.verbose);
        handle_editor(&mut app, key('t'));
        assert!(!app.show_thinking);
        assert!(
            app.live_reasoning.is_empty(),
            "hidden thinking stops streaming"
        );
        assert!(app.input.is_empty(), "toggles never type into the draft");
        handle_editor(&mut app, key('t'));
        assert!(app.show_thinking);
    }
}