mars-terminal 0.3.2

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

use anyhow::Result;
use crossterm::event::{
    KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal};

use crate::{
    agent::{self, AgentEvent},
    buffer::{Buffer, BufferId},
    config::{self, chord_of, KeyBindings, KeyChord},
    layout::PaneLayout,
    mode::Mode,
    palette::{self, Action, BarMode, ItemKind, Palette},
    pane::{Pane, PaneContent, PaneId},
    project,
    tab::{Tab, TabId},
    terminal::{self, Term, TermEvent, TermId},
    tuning::{self, Tuning},
    ui,
};

/// One unit of user input, source-agnostic: the real TTY in standalone mode,
/// or deserialized frames from a session client.
pub enum InputEvent {
    Key(KeyEvent),
    Mouse(MouseEvent),
    Paste(String),
    /// New client viewport size — handled by the session server (standalone
    /// mode relies on ratatui autoresize).
    Resize(u16, u16),
}

/// The left file-tree sidebar's state (@ / C-x d).
pub struct FileTree {
    /// Directory the tree is rooted at (`../` re-roots to the parent).
    pub root: std::path::PathBuf,
    /// Folders the user has expanded (full paths).
    pub expanded: std::collections::HashSet<std::path::PathBuf>,
    pub selected: usize,
    /// Type-to-filter query; non-empty switches the sidebar to a fuzzy shortlist.
    pub filter: String,
}

/// One flattened, visible line in the tree sidebar.
pub struct TreeRow {
    pub path: std::path::PathBuf,
    pub label: String,
    pub depth: usize,
    pub is_dir: bool,
    pub expanded: bool,
    /// The `../` go-up row.
    pub updir: bool,
}

/// A minibuffer prompt (find-file, switch-buffer, incremental search).
#[derive(Clone)]
pub struct Prompt {
    pub label: String,
    pub input: String,
    pub kind: PromptKind,
}

#[derive(Clone, PartialEq)]
pub enum PromptKind {
    SaveAs,
    GotoLine,
    RenameTab,
    RenamePane,
    RenameSession,
    /// Live incremental search (C-s / C-r navigate, Enter accepts, C-g restores).
    Search,
    /// Query-replace, stage 1: the string to find.
    ReplaceFrom,
    /// Query-replace, stage 2: the replacement string.
    ReplaceTo,
    /// Query-replace, stage 3: interactive y/n/! all/q stepping through matches.
    QueryReplace,
    /// Quit with modified buffers: s = save all & quit, q = quit anyway.
    ConfirmQuit,
    /// Confirm a destructive agent-proposed action: y runs it, anything else cancels.
    ConfirmAction(Action),
}

/// Per-terminal watch state (W6): the daemon summarizes a watched pane when it
/// goes quiet or its process exits — even while you're detached.
#[derive(Default)]
pub struct WatchState {
    pub watched: bool,
    pub last_output_tick: u64,
    /// Quiet/exit already fired → don't re-fire until new output arrives.
    pub triggered: bool,
    /// The last one-line verdict (kept for the W7 reattach diff later).
    pub verdict: Option<String>,
    /// `frame_tick` when the current run's output first began (0 = idle) — for the
    /// away-digest duration ("build took 4m12s").
    pub run_started_tick: u64,
}

/// Why a watch fired.
#[derive(Clone, Copy)]
pub enum WatchReason { Exit, Quiet }

/// Pull the selected cells from a terminal screen as text — reading order,
/// trailing spaces trimmed per row (linear/text-flow, like a normal terminal
/// copy). `a`/`b` are normalized (a ≤ b) screen cells; `last_col` bounds
/// intermediate full rows. Free function so it's unit-testable off a real screen.
pub(crate) fn selection_text_from_screen(
    screen: &vt100::Screen,
    a: (u16, u16),
    b: (u16, u16),
    last_col: u16,
) -> String {
    let mut out = String::new();
    for row in a.0..=b.0 {
        let c0 = if row == a.0 { a.1 } else { 0 };
        let c1 = if row == b.0 { b.1 } else { last_col };
        let mut line = String::new();
        for col in c0..=c1 {
            let ch = screen.cell(row, col).map(|c| c.contents()).unwrap_or_default();
            line.push_str(if ch.is_empty() { " " } else { &ch });
        }
        out.push_str(line.trim_end());
        if row < b.0 {
            out.push('\n');
        }
    }
    out
}

/// A live mouse drag-selection inside a terminal pane. Cells are in the pane's
/// visible screen coordinates (row, col); `ox`/`oy` map a screen cell to the
/// absolute terminal position, `vw`/`vh` bound it. Copied to the clipboard on
/// release; highlighted while dragging.
#[derive(Clone, Copy)]
pub struct TermSel {
    pub tid: TermId,
    pub ox: u16,
    pub oy: u16,
    pub vw: u16,
    pub vh: u16,
    pub anchor: (u16, u16),
    pub end: (u16, u16),
}

/// Coalesces consecutive edits into one undo step: a run of typed characters is
/// one undo, a run of backspaces another; any motion or command breaks the run so
/// the next keystroke starts a fresh checkpoint.
#[derive(Clone, Copy, PartialEq)]
enum EditRun { None, Insert, Delete }

/// A pull-rendered proactive notice — the agent's only path to the screen. The
/// renderer reads it; the agent never pushes. Failures sort before info.
pub struct Notice {
    pub text: String,
    pub kind: NoticeKind,
}

#[derive(PartialEq, PartialOrd, Eq, Ord)]
pub enum NoticeKind { Failure, Info }

/// A cheap counts-and-flags snapshot taken at detach; diffed at reattach (W7).
/// Deterministic — the facts (what exited, what changed) are the value; no LLM.
#[derive(Default)]
pub struct Snapshot {
    dirty: std::collections::HashSet<String>,
}

/// One notable thing the daemon observed — accumulated always, rendered as the
/// reattach "Away Digest" (the events since detach). Deterministic by
/// construction; the LLM only ever fills a watch verdict's `text`, via the
/// existing `watch_summary → chat → AgentConfig` seam — so a keyless (or future
/// broker-proxied) box still produces the full digest. This is also the episodic
/// Tier-1 log the memory system will later read.
#[derive(Clone)]
pub struct AwayEvent {
    pub tick: u64,
    pub kind: AwayKind,
    pub text: String,
    /// Run duration in ticks, when known (verdict events).
    pub dur_ticks: Option<u64>,
}

/// Digest section — failures first.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AwayKind { NeedsYou, Done, Context }

pub struct App {
    pub buffers: HashMap<BufferId, Buffer>,
    pub panes: HashMap<PaneId, Pane>,
    pub tabs: Vec<Tab>,
    pub active_tab: usize,
    pub mode: Mode,
    pub palette: Option<Palette>,
    pub status_msg: Option<String>,
    pub should_quit: bool,
    pub keys: KeyBindings,
    pub frecency: HashMap<String, u32>,
    // ── Non-modal editing state ──
    pub pending_prefix: Vec<KeyChord>,
    /// frame_tick when the prefix was armed — which-key pops after a short delay.
    pub prefix_tick: u64,
    pub prompt: Option<Prompt>,
    pub kill_ring: Vec<String>,
    /// (buffer, start char idx, len, kill_ring index) of the last yank — M-y target.
    last_yank: Option<(BufferId, usize, usize, usize)>,
    // ── Incremental search ──
    pub search_origin: Option<(usize, usize)>,
    /// Highlighted matches as (row, col, len) — rendered like selections.
    pub search_hl: Vec<(usize, usize, usize)>,
    /// Teleport labels over matches (row, col, label) while picking (Tab).
    pub search_labels: Vec<(usize, usize, char)>,
    /// True when the next key selects a labeled match instead of extending the query.
    pub search_pick: bool,
    // ── Command bar ──
    /// Mode to return to when the bar closes (Terminal keeps its focus).
    pub bar_return: Mode,
    /// Per-action bar-invocation counts — drives the graduation nudge.
    pub bar_uses: HashMap<String, u32>,
    // ── Mouse ──
    /// Pane screen rects from the last render (pane_id, rect).
    pub pane_rects: Vec<(PaneId, Rect)>,
    /// Focused pane's cursor screen position from the last render — anchors the
    /// W3 shell-translate overlay.
    pub cursor_screen: Option<(u16, u16)>,
    // ── System clipboard (None if unavailable, e.g. headless) ──
    clipboard: Option<arboard::Clipboard>,
    // ── Behavioral tuning knobs (~/.config/mars/tuning.json) ──
    pub tuning: Tuning,
    /// Show the MARS banner in the empty scratch until the first keypress.
    pub show_splash: bool,
    /// Directory new terminals open in — the parent of the first opened file.
    startup_cwd: Option<std::path::PathBuf>,
    /// Directory `mars` was launched from — the terminal's cwd when no file set one.
    run_cwd: Option<std::path::PathBuf>,
    /// Lazily-built project file index (feeds the tree's type-to-filter).
    project_index: Option<project::Index>,
    /// How often each file has been opened — ranks the filter shortlist.
    pub file_frecency: HashMap<String, u32>,
    /// Left file-tree sidebar (@ / C-x d); visible whenever `tree_open`.
    pub file_tree: Option<FileTree>,
    pub tree_open: bool,
    /// Flattened visible rows, recomputed on every tree mutation.
    pub tree_rows: Vec<TreeRow>,
    // ── Session (daemon) state ──
    /// Set when running inside a session daemon (`mars --session <name>`).
    pub session_name: Option<String>,
    /// Action::Detach sets this; the session server consumes it.
    pub detach_requested: bool,
    /// Action::RenameSession sets this; the session server consumes it.
    pub rename_session_to: Option<String>,
    // ── LLM agent ──
    pub agent_tx: mpsc::Sender<AgentEvent>,
    pub agent_rx: mpsc::Receiver<AgentEvent>,
    pub agent_pending: bool,
    /// The in-progress streamed reply (rendered live in the ask panel); the
    /// final `Answer` event replaces it with the directive-parsed text.
    pub agent_partial: Option<String>,
    /// Transient notices only (errors, no-key) — answers live in the history.
    pub agent_answer: Option<String>,
    /// Confirm-gated action the model proposed (RUN:/TYPE: directive).
    pub agent_directive: Option<agent::AgentDirective>,
    /// The selection (buf, start, end) captured when an agent query was asked —
    /// the target a proposed refactor would replace.
    pub refactor_target: Option<(BufferId, usize, usize)>,
    /// A code-block the agent returned to replace `refactor_target` (confirm-gated).
    pub refactor_replacement: Option<String>,
    /// The last question asked, replayed verbatim when the model emits a `NEED:`.
    last_question: String,
    /// How many `NEED:` expansions this ask has done (hard cap 1 — never a loop).
    need_depth: u8,
    // ── Watch / notices (W6) ──
    /// Per-terminal watch state, keyed by TermId.
    pub watches: HashMap<TermId, WatchState>,
    /// Proactive notices the renderer reads (failures first). The agent can only append.
    pub notices: Vec<Notice>,
    /// An exit trigger queued from the term_rx drain, fired next tick.
    pending_watch: Option<(TermId, WatchReason)>,
    /// State captured at detach; diffed on reattach for the "where was I?" briefing (W7).
    detach_snapshot: Option<Snapshot>,
    /// Append-only ring of notable events (bounded) — the Away Digest source.
    pub away_log: Vec<AwayEvent>,
    /// `frame_tick` at the last detach — the start of the "while away" window.
    detach_tick: Option<u64>,
    /// Window start for a re-summonable digest ("away digest" action).
    pub digest_from_tick: Option<u64>,
    /// The conversation: ("user"/"assistant", text). Survives bar close; C-l clears.
    pub agent_history: Vec<(String, String)>,
    /// Ask-panel scroll: lines scrolled up from the bottom of the transcript.
    pub ask_scroll: usize,
    /// Auto-naming state: one request in flight; tabs already tried.
    pub bg_busy: bool,
    auto_name_attempted: std::collections::HashSet<TabId>,
    /// Shell composer: the query is a ready-to-run command (translated or
    /// typed literally with no key) — the next Enter runs it.
    pub shell_ready: bool,
    /// Eval instrumentation: the `call_id` of the pending shell translation and the
    /// English request that produced it, so accept/edit/reject is logged (and the
    /// accepted command is remembered for corrective memory).
    translate_call_id: Option<u64>,
    translate_request: Option<String>,
    /// Session auto-naming: fired once per still-numeric session.
    session_name_attempted: bool,
    /// Undo coalescing: the kind of edit run currently in progress.
    edit_run: EditRun,
    /// One-shot bypass for the live-terminal close gate: set by the confirm
    /// prompt's `y`, consumed by the close_* functions (so the confirmed action
    /// doesn't re-prompt).
    close_confirmed: bool,
    /// One-shot "always confirm this close, even with no live terminal" — set by
    /// space-warp's d/q/0 (destructive keys adjacent to navigation), consumed at
    /// the top of every close_* fn so it never leaks to a later close.
    force_close_confirm: bool,
    // ── Query-replace (M-%) ──
    replace_from: String,
    replace_to: String,
    /// Char index of the match currently being offered.
    replace_idx: Option<usize>,
    /// Whether the one undo checkpoint for this replace has been taken.
    replace_checkpointed: bool,
    /// Live terminal mouse drag-selection (copied on release).
    pub term_sel: Option<TermSel>,
    pub frame_tick: u64,
    /// Render only when something visible changed. Set on input and by `tick()`
    /// when it moves visible state (terminal output, agent events, the spinner,
    /// a pending which-key panel). Keeps an idle screen from flushing 60×/s —
    /// invisible locally, but pure noise (and input contention) over SSH.
    pub needs_redraw: bool,
    // ── Terminal panes ──
    pub terms: HashMap<TermId, Term>,
    pub term_tx: mpsc::Sender<TermEvent>,
    pub term_rx: mpsc::Receiver<TermEvent>,
    next_buffer_id: usize,
    next_pane_id: usize,
    next_tab_id: usize,
    next_term_id: usize,
}

impl App {
    pub fn new(file: Option<String>) -> Result<Self> {
        let keys = config::load();
        let state = PersistedState::load();
        let (agent_tx, agent_rx) = mpsc::channel();
        let (term_tx, term_rx) = mpsc::channel();
        let mut app = App {
            buffers: HashMap::new(),
            panes: HashMap::new(),
            tabs: vec![],
            active_tab: 0,
            mode: Mode::Edit,
            palette: None,
            status_msg: None,
            should_quit: false,
            keys,
            frecency: state.frecency,
            pending_prefix: Vec::new(),
            prefix_tick: 0,
            prompt: None,
            kill_ring: Vec::new(),
            last_yank: None,
            search_origin: None,
            search_hl: Vec::new(),
            search_labels: Vec::new(),
            search_pick: false,
            bar_return: Mode::Edit,
            bar_uses: state.bar_uses,
            pane_rects: Vec::new(),
            cursor_screen: None,
            // Env gate keeps selfchecks from touching the user's real clipboard.
            clipboard: if std::env::var("MARS_NO_SYSTEM_CLIPBOARD").is_ok()
                || std::env::var("ARES_NO_SYSTEM_CLIPBOARD").is_ok()
            {
                None
            } else {
                arboard::Clipboard::new().ok()
            },
            tuning: tuning::load(),
            show_splash: file.is_none(),
            startup_cwd: file
                .as_ref()
                .and_then(|f| std::path::Path::new(f).parent().map(|p| p.to_path_buf()))
                .filter(|p| !p.as_os_str().is_empty()),
            run_cwd: std::env::current_dir().ok(),
            project_index: None,
            file_frecency: state.file_frecency,
            file_tree: None,
            tree_open: false,
            tree_rows: Vec::new(),
            session_name: None,
            detach_requested: false,
            rename_session_to: None,
            agent_tx,
            agent_rx,
            agent_pending: false,
            agent_partial: None,
            agent_answer: None,
            agent_directive: None,
            refactor_target: None,
            refactor_replacement: None,
            last_question: String::new(),
            need_depth: 0,
            watches: HashMap::new(),
            notices: Vec::new(),
            pending_watch: None,
            detach_snapshot: None,
            away_log: Vec::new(),
            detach_tick: None,
            digest_from_tick: None,
            agent_history: Vec::new(),
            ask_scroll: 0,
            bg_busy: false,
            auto_name_attempted: std::collections::HashSet::new(),
            shell_ready: false,
            translate_call_id: None,
            translate_request: None,
            session_name_attempted: false,
            close_confirmed: false,
            force_close_confirm: false,
            term_sel: None,
            needs_redraw: true, // draw the first frame
            edit_run: EditRun::None,
            replace_from: String::new(),
            replace_to: String::new(),
            replace_idx: None,
            replace_checkpointed: false,
            frame_tick: 0,
            terms: HashMap::new(),
            term_tx,
            term_rx,
            next_buffer_id: 0,
            next_pane_id: 0,
            next_tab_id: 0,
            next_term_id: 0,
        };
        let buf_id = match file {
            Some(ref path) => app.open_file(path)?,
            None => app.new_scratch(),
        };
        let pane_id = app.alloc_pane(buf_id);
        let tab = Tab::new(app.alloc_tab_id(), "1".into(), pane_id);
        app.tabs.push(tab);
        Ok(app)
    }

    // ── ID allocators ────────────────────────────────────────────────────────

    fn alloc_buf_id(&mut self) -> BufferId {
        let id = self.next_buffer_id;
        self.next_buffer_id += 1;
        id
    }
    fn alloc_pane_id(&mut self) -> PaneId {
        let id = self.next_pane_id;
        self.next_pane_id += 1;
        id
    }
    fn alloc_tab_id(&mut self) -> TabId {
        let id = self.next_tab_id;
        self.next_tab_id += 1;
        id
    }

    // ── Buffer management ────────────────────────────────────────────────────

    pub fn new_scratch(&mut self) -> BufferId {
        let id = self.alloc_buf_id();
        self.buffers.insert(id, Buffer::new_scratch(id));
        id
    }

    pub fn open_file(&mut self, path: &str) -> Result<BufferId> {
        let id = self.alloc_buf_id();
        let buf = Buffer::from_file(id, std::path::PathBuf::from(path))?;
        self.buffers.insert(id, buf);
        // First file opened sets the cwd new terminals inherit.
        if self.startup_cwd.is_none() {
            self.startup_cwd = std::path::Path::new(path)
                .parent()
                .map(|p| p.to_path_buf())
                .filter(|p| !p.as_os_str().is_empty());
        }
        *self.file_frecency.entry(path.to_string()).or_insert(0) += 1;
        Ok(id)
    }

    /// Seed the project index directly (selfcheck only — bypasses the fs walk).
    pub fn set_project_index_for_test(&mut self, root: std::path::PathBuf, files: Vec<String>) {
        self.project_index = Some(project::Index { root, files });
    }

    /// Build the project index on first use (lazy); returns its root + files.
    fn ensure_project_index(&mut self) -> &project::Index {
        if self.project_index.is_none() {
            let root = self
                .startup_cwd
                .clone()
                .unwrap_or_else(|| std::path::PathBuf::from("."));
            let root = project::project_root(&root);
            let idx = project::Index::build(
                root,
                self.tuning.project_index_max,
                &self.tuning.project_ignore,
            );
            self.project_index = Some(idx);
        }
        self.project_index.as_ref().unwrap()
    }

    // ── Pane management ──────────────────────────────────────────────────────

    fn alloc_pane(&mut self, buffer_id: BufferId) -> PaneId {
        let id = self.alloc_pane_id();
        self.panes.insert(id, Pane::new(buffer_id));
        id
    }

    // ── Focus helpers ────────────────────────────────────────────────────────

    pub fn tab(&self) -> &Tab {
        &self.tabs[self.active_tab]
    }
    pub fn tab_mut(&mut self) -> &mut Tab {
        &mut self.tabs[self.active_tab]
    }
    pub fn focused_pane_id(&self) -> PaneId {
        self.tabs[self.active_tab].focused_pane
    }
    pub fn focused_pane(&self) -> &Pane {
        let id = self.focused_pane_id();
        self.panes.get(&id).unwrap()
    }
    pub fn focused_pane_mut(&mut self) -> &mut Pane {
        let id = self.focused_pane_id();
        self.panes.get_mut(&id).unwrap()
    }
    pub fn focused_buf_id(&self) -> BufferId {
        match self.focused_pane().content {
            PaneContent::Editor(buf_id) => buf_id,
            PaneContent::Terminal(_) => {
                // Return first available buffer id for terminal panes
                *self.buffers.keys().next().unwrap_or(&0)
            }
        }
    }
    pub fn focused_buf(&self) -> &Buffer {
        let id = self.focused_buf_id();
        self.buffers.get(&id).unwrap()
    }
    pub fn focused_buf_mut(&mut self) -> &mut Buffer {
        let id = self.focused_buf_id();
        self.buffers.get_mut(&id).unwrap()
    }

    // ── Cursor movement ──────────────────────────────────────────────────────

    pub fn move_up(&mut self) {
        let pane = self.focused_pane();
        if let PaneContent::Terminal(_) = pane.content { return; }
        let (row, affinity, buf_id) = (pane.cursor_row, pane.col_affinity, match pane.content { PaneContent::Editor(id) => id, _ => return });
        if row == 0 {
            return;
        }
        let new_row = row - 1;
        let len = self.buffers[&buf_id].line_len(new_row);
        let p = self.focused_pane_mut();
        p.cursor_row = new_row;
        p.cursor_col = affinity.min(len);
    }

    pub fn move_down(&mut self) {
        let pane = self.focused_pane();
        if let PaneContent::Terminal(_) = pane.content { return; }
        let (row, affinity, buf_id) = (pane.cursor_row, pane.col_affinity, match pane.content { PaneContent::Editor(id) => id, _ => return });
        let line_count = self.buffers[&buf_id].line_count();
        if row + 1 >= line_count {
            return;
        }
        let new_row = row + 1;
        let len = self.buffers[&buf_id].line_len(new_row);
        let p = self.focused_pane_mut();
        p.cursor_row = new_row;
        p.cursor_col = affinity.min(len);
    }

    pub fn move_left(&mut self) {
        let (row, col) = { let p = self.focused_pane(); (p.cursor_row, p.cursor_col) };
        if col > 0 {
            let p = self.focused_pane_mut();
            p.cursor_col = col - 1;
            p.col_affinity = p.cursor_col;
        } else if row > 0 {
            // Wrap to the end of the previous line.
            let buf_id = match self.focused_pane().content { PaneContent::Editor(id) => id, _ => return };
            let prev_len = self.buffers[&buf_id].line_len(row - 1);
            let p = self.focused_pane_mut();
            p.cursor_row = row - 1;
            p.cursor_col = prev_len;
            p.col_affinity = prev_len;
        }
    }

    pub fn move_right(&mut self) {
        let pane = self.focused_pane();
        if let PaneContent::Terminal(_) = pane.content { return; }
        let (row, col, buf_id) = (pane.cursor_row, pane.cursor_col, match pane.content { PaneContent::Editor(id) => id, _ => return });
        let len = self.buffers[&buf_id].line_len(row);
        if col < len {
            let p = self.focused_pane_mut();
            p.cursor_col = col + 1;
            p.col_affinity = p.cursor_col;
        } else {
            // Wrap to the start of the next line, if there is one.
            let last = self.buffers[&buf_id].line_count().saturating_sub(1);
            if row < last {
                let p = self.focused_pane_mut();
                p.cursor_row = row + 1;
                p.cursor_col = 0;
                p.col_affinity = 0;
            }
        }
    }

    pub fn move_line_start(&mut self) {
        let p = self.focused_pane_mut();
        p.cursor_col = 0;
        p.col_affinity = 0;
    }

    pub fn move_line_end(&mut self) {
        let pane = self.focused_pane();
        if let PaneContent::Terminal(_) = pane.content { return; }
        let (row, buf_id) = (pane.cursor_row, match pane.content { PaneContent::Editor(id) => id, _ => return });
        let len = self.buffers[&buf_id].line_len(row);
        let p = self.focused_pane_mut();
        p.cursor_col = len;
        p.col_affinity = len;
    }

    pub fn move_file_start(&mut self) {
        let p = self.focused_pane_mut();
        p.cursor_row = 0;
        p.cursor_col = 0;
        p.col_affinity = 0;
    }

    pub fn move_file_end(&mut self) {
        let pane = self.focused_pane();
        if let PaneContent::Terminal(_) = pane.content { return; }
        let buf_id = match pane.content { PaneContent::Editor(id) => id, _ => return };
        let line_count = self.buffers[&buf_id].line_count();
        let last = line_count.saturating_sub(1);
        let len = self.buffers[&buf_id].line_len(last);
        let p = self.focused_pane_mut();
        p.cursor_row = last;
        p.cursor_col = len;
        p.col_affinity = len;
    }

    // ── Text editing ─────────────────────────────────────────────────────────

    fn insert_char_at_cursor(&mut self, c: char) {
        let pane = self.focused_pane();
        let buf_id = match pane.content { PaneContent::Editor(id) => id, _ => return };
        let (row, col) = (pane.cursor_row, pane.cursor_col);
        let char_idx = self.buffers[&buf_id].char_at(row, col);
        {
            let buf = self.buffers.get_mut(&buf_id).unwrap();
            buf.rope.insert_char(char_idx, c);
            buf.modified = true;
        }
        let p = self.focused_pane_mut();
        if c == '\n' {
            p.cursor_row += 1;
            p.cursor_col = 0;
        } else {
            p.cursor_col += 1;
        }
        p.col_affinity = p.cursor_col;
    }

    /// After a newline, copy the previous line's leading whitespace so the cursor
    /// lands at the same indent (the near-universal editor expectation).
    fn auto_indent(&mut self) {
        let (row, buf_id) = match self.editor_pos() { Some((r, _, id)) => (r, id), None => return };
        if row == 0 {
            return;
        }
        let indent: String = self.buffers[&buf_id]
            .rope
            .line(row - 1)
            .chars()
            .take_while(|c| *c == ' ' || *c == '\t')
            .collect();
        for c in indent.chars() {
            self.insert_char_at_cursor(c);
        }
    }

    fn delete_before_cursor(&mut self) {
        let pane = self.focused_pane();
        let buf_id = match pane.content { PaneContent::Editor(id) => id, _ => return };
        let (row, col) = (pane.cursor_row, pane.cursor_col);
        if col == 0 && row == 0 {
            return;
        }
        let char_idx = self.buffers[&buf_id].char_at(row, col);
        if char_idx == 0 {
            return;
        }
        let new_pos = if col > 0 {
            (row, col - 1)
        } else {
            let prev_len = self.buffers[&buf_id].line_len(row - 1);
            (row - 1, prev_len)
        };
        {
            let buf = self.buffers.get_mut(&buf_id).unwrap();
            buf.rope.remove(char_idx - 1..char_idx);
            buf.modified = true;
        }
        let p = self.focused_pane_mut();
        p.cursor_row = new_pos.0;
        p.cursor_col = new_pos.1;
        p.col_affinity = new_pos.1;
    }

    // ── Position helpers ─────────────────────────────────────────────────────

    /// (row, col, buffer) for the focused pane, or None if it hosts a terminal.
    fn editor_pos(&self) -> Option<(usize, usize, BufferId)> {
        let p = self.focused_pane();
        match p.content {
            PaneContent::Editor(id) => Some((p.cursor_row, p.cursor_col, id)),
            PaneContent::Terminal(_) => None,
        }
    }

    fn rowcol_of(&self, buf_id: BufferId, idx: usize) -> (usize, usize) {
        let rope = &self.buffers[&buf_id].rope;
        let idx = idx.min(rope.len_chars());
        let line = rope.char_to_line(idx);
        (line, idx - rope.line_to_char(line))
    }

    fn set_cursor(&mut self, row: usize, col: usize) {
        let p = self.focused_pane_mut();
        p.cursor_row = row;
        p.cursor_col = col;
        p.col_affinity = col;
    }

    // ── Selection ────────────────────────────────────────────────────────────

    fn clear_selection(&mut self) {
        let id = self.focused_pane_id();
        if let Some(p) = self.panes.get_mut(&id) { p.selection_anchor = None; }
    }

    fn begin_or_keep_selection(&mut self) {
        let (r, c) = { let p = self.focused_pane(); (p.cursor_row, p.cursor_col) };
        let p = self.focused_pane_mut();
        if p.selection_anchor.is_none() { p.selection_anchor = Some((r, c)); }
    }

    pub fn selection_range(&self) -> Option<(BufferId, usize, usize)> {
        let p = self.focused_pane();
        let anchor = p.selection_anchor?;
        let buf_id = match p.content { PaneContent::Editor(id) => id, _ => return None };
        let buf = &self.buffers[&buf_id];
        let a = buf.char_at(anchor.0, anchor.1);
        let b = buf.char_at(p.cursor_row, p.cursor_col);
        let (s, e) = if a <= b { (a, b) } else { (b, a) };
        if s == e { None } else { Some((buf_id, s, e)) }
    }

    // Selection-aware movement wrappers.
    fn move_left_sel(&mut self, extend: bool)  { if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); } self.move_left(); }
    fn move_right_sel(&mut self, extend: bool) { if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); } self.move_right(); }
    fn move_up_sel(&mut self, extend: bool)    { if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); } self.move_up(); }
    fn move_down_sel(&mut self, extend: bool)  { if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); } self.move_down(); }
    fn move_line_start_sel(&mut self, extend: bool) { if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); } self.move_line_start(); }
    fn move_line_end_sel(&mut self, extend: bool)   { if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); } self.move_line_end(); }

    /// One page ≈ viewport height minus overlap (fallback before first render).
    fn page_len(&self) -> usize {
        let h = self.focused_pane().view_h;
        if h == 0 { 18 } else { h.saturating_sub(self.tuning.page_overlap).max(1) }
    }
    fn page_up(&mut self) {
        self.clear_selection();
        for _ in 0..self.page_len() { self.move_up(); }
    }
    fn page_down(&mut self) {
        self.clear_selection();
        for _ in 0..self.page_len() { self.move_down(); }
    }

    // ── Word motion (M-f / M-b) ──────────────────────────────────────────────

    fn move_word_forward(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let (len, mut idx) = {
            let b = &self.buffers[&buf_id];
            (b.rope.len_chars(), b.char_at(row, col))
        };
        let is_word = |c: char| c.is_alphanumeric() || c == '_';
        {
            let rope = &self.buffers[&buf_id].rope;
            while idx < len && !is_word(rope.char(idx)) { idx += 1; }
            while idx < len && is_word(rope.char(idx)) { idx += 1; }
        }
        let (r, c) = self.rowcol_of(buf_id, idx);
        self.set_cursor(r, c);
    }

    fn move_word_backward(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let mut idx = self.buffers[&buf_id].char_at(row, col);
        let is_word = |c: char| c.is_alphanumeric() || c == '_';
        {
            let rope = &self.buffers[&buf_id].rope;
            while idx > 0 && !is_word(rope.char(idx - 1)) { idx -= 1; }
            while idx > 0 && is_word(rope.char(idx - 1)) { idx -= 1; }
        }
        let (r, c) = self.rowcol_of(buf_id, idx);
        self.set_cursor(r, c);
    }

    // ── Code-token motion (⌘←/→) ─────────────────────────────────────────────
    // A token is a maximal run of one class — word (alnum/`_`) or punctuation —
    // with whitespace skipped. So `foo.bar(baz)` stops at foo · . · bar · ( · baz
    // · ), which tracks how code reads (identifiers and operators as atoms).

    /// 0 = whitespace, 1 = word (alnum/underscore), 2 = punctuation.
    fn token_class(c: char) -> u8 {
        if c.is_whitespace() { 0 } else if c.is_alphanumeric() || c == '_' { 1 } else { 2 }
    }

    pub fn move_token_forward(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let (len, mut idx) = {
            let b = &self.buffers[&buf_id];
            (b.rope.len_chars(), b.char_at(row, col))
        };
        {
            let rope = &self.buffers[&buf_id].rope;
            // Consume the current token's run, then any whitespace, landing on the
            // start of the next token.
            if idx < len {
                let c0 = Self::token_class(rope.char(idx));
                if c0 != 0 {
                    while idx < len && Self::token_class(rope.char(idx)) == c0 { idx += 1; }
                }
            }
            while idx < len && Self::token_class(rope.char(idx)) == 0 { idx += 1; }
        }
        let (r, c) = self.rowcol_of(buf_id, idx);
        self.set_cursor(r, c);
    }

    pub fn move_token_backward(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let mut idx = self.buffers[&buf_id].char_at(row, col);
        {
            let rope = &self.buffers[&buf_id].rope;
            while idx > 0 && Self::token_class(rope.char(idx - 1)) == 0 { idx -= 1; }
            if idx > 0 {
                let c0 = Self::token_class(rope.char(idx - 1));
                while idx > 0 && Self::token_class(rope.char(idx - 1)) == c0 { idx -= 1; }
            }
        }
        let (r, c) = self.rowcol_of(buf_id, idx);
        self.set_cursor(r, c);
    }

    fn move_token_sel(&mut self, forward: bool, extend: bool) {
        if extend { self.begin_or_keep_selection(); } else { self.clear_selection(); }
        if forward { self.move_token_forward(); } else { self.move_token_backward(); }
    }

    // ── Structural jumps (C-x [ ] { } m) ─────────────────────────────────────

    fn line_is_blank(b: &Buffer, r: usize) -> bool {
        b.rope.line(r).chars().all(|c| c.is_whitespace())
    }

    /// Jump to the next/prev blank line — fly between code blocks.
    pub fn jump_block(&mut self, forward: bool) {
        let (row, _c, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let n = self.buffers[&buf_id].line_count();
        let target = {
            let b = &self.buffers[&buf_id];
            if forward {
                let mut r = row + 1;
                while r < n && Self::line_is_blank(b, r) { r += 1; }
                while r < n && !Self::line_is_blank(b, r) { r += 1; }
                r.min(n.saturating_sub(1))
            } else {
                let mut r = row.saturating_sub(1);
                while r > 0 && Self::line_is_blank(b, r) { r -= 1; }
                while r > 0 && !Self::line_is_blank(b, r) { r -= 1; }
                r
            }
        };
        self.clear_selection();
        self.set_cursor(target, 0);
    }

    /// Jump to the next/prev top-level definition (column-0 keyword heuristic).
    pub fn jump_symbol(&mut self, forward: bool) {
        let (row, _c, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let n = self.buffers[&buf_id].line_count();
        const KWS: &[&str] = &[
            "fn ", "pub fn", "pub(", "pub struct", "pub enum", "def ", "class ", "impl",
            "struct ", "enum ", "trait ", "mod ", "type ", "func ", "function ",
            "interface ", "async fn", "export ", "const fn",
        ];
        let is_def = |b: &Buffer, r: usize| -> bool {
            let line: String = b.rope.line(r).chars().collect();
            let t = line.trim_start();
            KWS.iter().any(|k| t.starts_with(k))
        };
        let target = {
            let b = &self.buffers[&buf_id];
            if forward {
                let mut r = row + 1;
                while r < n && !is_def(b, r) { r += 1; }
                (r < n).then_some(r)
            } else if row == 0 {
                None
            } else {
                let mut r = row - 1;
                loop {
                    if is_def(b, r) { break Some(r); }
                    if r == 0 { break None; }
                    r -= 1;
                }
            }
        };
        if let Some(r) = target {
            self.clear_selection();
            self.set_cursor(r, 0);
        }
    }

    /// Jump to the bracket matching the one at (or just before) the cursor.
    pub fn match_bracket(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        const OPENS: [char; 3] = ['(', '[', '{'];
        const CLOSES: [char; 3] = [')', ']', '}'];
        let target = {
            let rope = &self.buffers[&buf_id].rope;
            let len = rope.len_chars();
            let cur = self.buffers[&buf_id].char_at(row, col);
            // Find a bracket: the char under the cursor, scanning to end of line;
            // else the char just before the cursor.
            let mut found = None;
            let mut j = cur;
            while j < len {
                let c = rope.char(j);
                if c == '\n' { break; }
                if OPENS.contains(&c) || CLOSES.contains(&c) { found = Some((j, c)); break; }
                j += 1;
            }
            if found.is_none() && cur > 0 {
                let c = rope.char(cur - 1);
                if OPENS.contains(&c) || CLOSES.contains(&c) { found = Some((cur - 1, c)); }
            }
            found.and_then(|(pos, c)| {
                if let Some(oi) = OPENS.iter().position(|&o| o == c) {
                    let (open, close) = (c, CLOSES[oi]);
                    let mut depth = 1i32;
                    let mut k = pos + 1;
                    while k < len {
                        let ch = rope.char(k);
                        if ch == open { depth += 1; }
                        else if ch == close { depth -= 1; if depth == 0 { return Some(k); } }
                        k += 1;
                    }
                    None
                } else if let Some(ci) = CLOSES.iter().position(|&cc| cc == c) {
                    let (open, close) = (OPENS[ci], c);
                    let mut depth = 1i32;
                    let mut k = pos;
                    while k > 0 {
                        k -= 1;
                        let ch = rope.char(k);
                        if ch == close { depth += 1; }
                        else if ch == open { depth -= 1; if depth == 0 { return Some(k); } }
                    }
                    None
                } else {
                    None
                }
            })
        };
        if let Some(idx) = target {
            let (r, c) = self.rowcol_of(buf_id, idx);
            self.clear_selection();
            self.set_cursor(r, c);
        }
    }

    // ── Kill-ring editing (C-d / C-k / C-w / M-w / C-y) ──────────────────────

    /// Every kill/copy lands in the kill-ring AND the system clipboard —
    /// copy in Ares, paste in the browser.
    fn push_kill(&mut self, text: String) {
        if let Some(cb) = self.clipboard.as_mut() {
            let _ = cb.set_text(text.clone());
        }
        self.kill_ring.push(text);
    }

    /// Insert a block of text at the cursor (one undo chunk, replaces selection).
    fn insert_text(&mut self, text: &str) {
        if self.editor_pos().is_none() {
            return;
        }
        self.focused_buf_mut().checkpoint();
        self.delete_selection();
        for ch in text.chars() {
            self.insert_char_at_cursor(ch);
        }
    }

    /// C-v — paste from the system clipboard (kill-ring head as fallback).
    fn paste_clipboard(&mut self) {
        let text = self
            .clipboard
            .as_mut()
            .and_then(|cb| cb.get_text().ok())
            .filter(|t| !t.is_empty())
            .or_else(|| self.kill_ring.last().cloned());
        match text {
            Some(t) => self.insert_text(&t),
            None => self.status_msg = Some("Clipboard empty".into()),
        }
    }

    /// Bracketed paste from the host terminal (Cmd+V etc.) — routed by mode.
    pub fn paste_text(&mut self, s: &str) {
        match self.mode {
            Mode::Terminal => {
                if let PaneContent::Terminal(tid) = self.focused_pane().content {
                    if let Some(t) = self.terms.get_mut(&tid) {
                        // Re-wrap if the inner app requested bracketed paste.
                        let wrap = t.screen().bracketed_paste();
                        if wrap { t.send_bytes(b"\x1b[200~"); }
                        t.send_bytes(s.as_bytes());
                        if wrap { t.send_bytes(b"\x1b[201~"); }
                    }
                }
            }
            Mode::Bar => {
                let clean: String = s.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect();
                if let Some(p) = self.palette.as_mut() {
                    p.query.push_str(&clean);
                }
            }
            Mode::Prompt => {
                let clean: String = s.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect();
                let is_search = if let Some(p) = self.prompt.as_mut() {
                    p.input.push_str(&clean);
                    p.kind == PromptKind::Search
                } else {
                    false
                };
                if is_search {
                    let q = self.prompt.as_ref().map(|p| p.input.clone()).unwrap_or_default();
                    self.update_isearch(&q);
                }
            }
            _ => self.insert_text(s),
        }
    }

    fn delete_char_forward(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let buf = self.buffers.get_mut(&buf_id).unwrap();
        let idx = buf.char_at(row, col);
        if idx < buf.rope.len_chars() {
            buf.checkpoint();
            buf.rope.remove(idx..idx + 1);
            buf.modified = true;
        }
    }

    fn kill_line(&mut self) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let killed = {
            let buf = self.buffers.get_mut(&buf_id).unwrap();
            buf.checkpoint();
            let start = buf.char_at(row, col);
            let eol = buf.line_len(row);
            let end = if col >= eol { (start + 1).min(buf.rope.len_chars()) } else { buf.char_at(row, eol) };
            if end > start {
                let k = buf.rope.slice(start..end).to_string();
                buf.rope.remove(start..end);
                buf.modified = true;
                k
            } else {
                String::new()
            }
        };
        if !killed.is_empty() { self.push_kill(killed); }
    }

    fn kill_region(&mut self) {
        if let Some((buf_id, s, e)) = self.selection_range() {
            let killed = {
                let buf = self.buffers.get_mut(&buf_id).unwrap();
                buf.checkpoint();
                let k = buf.rope.slice(s..e).to_string();
                buf.rope.remove(s..e);
                buf.modified = true;
                k
            };
            self.push_kill(killed);
            let (r, c) = self.rowcol_of(buf_id, s);
            self.set_cursor(r, c);
            self.clear_selection();
        }
    }

    fn copy_region(&mut self) {
        if let Some((buf_id, s, e)) = self.selection_range() {
            let text = self.buffers[&buf_id].rope.slice(s..e).to_string();
            self.push_kill(text);
            self.status_msg = Some("Copied".into());
        } else if let Some((row, _, buf_id)) = self.editor_pos() {
            // No selection → copy the whole current line (VS Code behavior).
            let line = self.buffers[&buf_id].line_str(row);
            if !line.is_empty() {
                self.push_kill(line);
                self.status_msg = Some("Copied line".into());
            }
        }
        self.clear_selection();
    }

    fn yank(&mut self) {
        if let Some(text) = self.kill_ring.last().cloned() {
            let start = match self.editor_pos() {
                Some((r, c, id)) => (id, self.buffers[&id].char_at(r, c)),
                None => return,
            };
            self.focused_buf_mut().checkpoint();
            for ch in text.chars() { self.insert_char_at_cursor(ch); }
            self.last_yank =
                Some((start.0, start.1, text.chars().count(), self.kill_ring.len() - 1));
        }
    }

    /// M-y — replace the text just yanked with the previous kill (rotating).
    fn yank_pop(&mut self) {
        let (buf_id, start, len, ridx) = match self.last_yank {
            Some(x) => x,
            None => {
                self.status_msg = Some("Previous command was not a yank".into());
                return;
            }
        };
        // Only valid while the cursor still sits at the end of the yanked text.
        let at_end = self
            .editor_pos()
            .map(|(r, c, id)| id == buf_id && self.buffers[&id].char_at(r, c) == start + len)
            .unwrap_or(false);
        if !at_end || self.kill_ring.len() < 2 {
            self.status_msg = Some("Previous command was not a yank".into());
            return;
        }
        let new_ridx = if ridx == 0 { self.kill_ring.len() - 1 } else { ridx - 1 };
        let text = self.kill_ring[new_ridx].clone();
        {
            let buf = self.buffers.get_mut(&buf_id).unwrap();
            buf.rope.remove(start..start + len);
            buf.modified = true;
        }
        let (r, c) = self.rowcol_of(buf_id, start);
        self.set_cursor(r, c);
        for ch in text.chars() { self.insert_char_at_cursor(ch); }
        self.last_yank = Some((buf_id, start, text.chars().count(), new_ridx));
    }

    /// M-d / M-Backspace — kill from the cursor to a word boundary.
    fn kill_word(&mut self, forward: bool) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let from = self.buffers[&buf_id].char_at(row, col);
        if forward { self.move_word_forward(); } else { self.move_word_backward(); }
        let (row2, col2, _) = match self.editor_pos() { Some(x) => x, None => return };
        let to = self.buffers[&buf_id].char_at(row2, col2);
        let (s, e) = if from <= to { (from, to) } else { (to, from) };
        if s == e { return; }
        let killed = {
            let buf = self.buffers.get_mut(&buf_id).unwrap();
            buf.checkpoint();
            let k = buf.rope.slice(s..e).to_string();
            buf.rope.remove(s..e);
            buf.modified = true;
            k
        };
        let (r, c) = self.rowcol_of(buf_id, s);
        self.set_cursor(r, c);
        self.push_kill(killed);
    }

    /// C-l — center the viewport on the cursor line.
    fn recenter(&mut self) {
        let p = self.focused_pane_mut();
        let half = (p.view_h / 2).max(1);
        p.scroll_row = p.cursor_row.saturating_sub(half);
    }

    /// C-x h — select the whole buffer (anchor at start, cursor at end).
    fn select_all(&mut self) {
        if self.editor_pos().is_none() { return; }
        self.focused_pane_mut().selection_anchor = Some((0, 0));
        self.move_file_end();
    }

    // ── Buffers & windows ────────────────────────────────────────────────────

    fn kill_buffer(&mut self) {
        let buf_id = match self.editor_pos() { Some((_, _, id)) => id, None => return };
        if self.buffers.len() <= 1 {
            self.status_msg = Some("Only buffer".into());
            return;
        }
        let other = self.buffers.keys().copied().find(|&id| id != buf_id);
        self.buffers.remove(&buf_id);
        if let Some(o) = other {
            // Retarget EVERY pane showing the killed buffer, not just the
            // focused one — a stale BufferId would panic on next focus.
            for pane in self.panes.values_mut() {
                if matches!(pane.content, PaneContent::Editor(id) if id == buf_id) {
                    pane.content = PaneContent::Editor(o);
                    pane.buffer_id = o;
                    pane.cursor_row = 0; pane.cursor_col = 0; pane.scroll_row = 0;
                    pane.selection_anchor = None;
                }
            }
        }
    }

    fn delete_other_windows(&mut self) {
        let force = std::mem::take(&mut self.force_close_confirm);
        let focused = self.focused_pane_id();
        let victims: Vec<PaneId> =
            self.tab().layout.pane_ids().into_iter().filter(|id| *id != focused).collect();
        if self.confirm_close(
            self.live_terms_in(&victims),
            force,
            Action::DeleteOtherWindows,
            "the other panes",
        ) {
            return;
        }
        self.reap_panes(&victims);
        let tab = self.tab_mut();
        tab.layout = PaneLayout::Single(focused);
        tab.focused_pane = focused;
    }

    // ── Incremental search ───────────────────────────────────────────────────

    /// All char indices where `needle` occurs in the focused buffer.
    fn find_matches(&self, buf_id: BufferId, needle: &str) -> Vec<usize> {
        let text: Vec<char> = self.buffers[&buf_id].rope.chars().collect();
        let pat: Vec<char> = needle.chars().collect();
        if pat.is_empty() || pat.len() > text.len() {
            return Vec::new();
        }
        (0..=text.len() - pat.len())
            .filter(|&i| text[i..i + pat.len()] == pat[..])
            .collect()
    }

    /// Refresh match highlights for the live query and jump to the first match
    /// at or after the search origin (wrapping).
    fn update_isearch(&mut self, needle: &str) {
        let buf_id = match self.editor_pos() { Some((_, _, id)) => id, None => return };
        let matches = self.find_matches(buf_id, needle);
        self.search_hl = matches
            .iter()
            .map(|&i| {
                let (r, c) = self.rowcol_of(buf_id, i);
                (r, c, needle.chars().count())
            })
            .collect();
        if needle.is_empty() {
            if let Some((r, c)) = self.search_origin {
                self.set_cursor(r, c);
            }
            return;
        }
        let origin_idx = self
            .search_origin
            .map(|(r, c)| self.buffers[&buf_id].char_at(r, c))
            .unwrap_or(0);
        match matches.iter().find(|&&i| i >= origin_idx).or(matches.first()) {
            Some(&idx) => {
                let (r, c) = self.rowcol_of(buf_id, idx);
                self.set_cursor(r, c);
            }
            None => self.status_msg = Some(format!("Failing I-search: {}", needle)),
        }
    }

    /// C-s / C-r inside isearch — jump to the next/previous match from the cursor.
    fn isearch_step(&mut self, needle: &str, forward: bool) {
        let (row, col, buf_id) = match self.editor_pos() { Some(x) => x, None => return };
        let matches = self.find_matches(buf_id, needle);
        if matches.is_empty() {
            self.status_msg = Some(format!("Failing I-search: {}", needle));
            return;
        }
        let cur = self.buffers[&buf_id].char_at(row, col);
        let idx = if forward {
            *matches.iter().find(|&&i| i > cur).unwrap_or(&matches[0]) // wrap
        } else {
            *matches.iter().rev().find(|&&i| i < cur).unwrap_or(matches.last().unwrap())
        };
        let (r, c) = self.rowcol_of(buf_id, idx);
        self.set_cursor(r, c);
    }

    fn start_isearch(&mut self) {
        let (row, col, _) = match self.editor_pos() {
            Some(x) => x,
            None => {
                self.status_msg = Some("No editor pane here".into());
                return;
            }
        };
        self.search_origin = Some((row, col));
        self.search_hl.clear();
        self.start_prompt(PromptKind::Search, "I-search: ");
    }

    fn end_isearch(&mut self, restore_origin: bool) {
        if restore_origin {
            if let Some((r, c)) = self.search_origin {
                self.set_cursor(r, c);
            }
        }
        self.search_origin = None;
        self.search_hl.clear();
        self.search_labels.clear();
        self.search_pick = false;
    }

    // ── Undo / redo ──────────────────────────────────────────────────────────

    fn do_undo(&mut self) {
        let did = self.focused_buf_mut().undo();
        if did {
            self.status_msg = Some("Undo".into());
        } else {
            self.status_msg = Some("Nothing to undo".into());
        }
        self.clamp_cursor_after_edit();
    }

    fn do_redo(&mut self) {
        let did = self.focused_buf_mut().redo();
        if did {
            self.status_msg = Some("Redo".into());
        } else {
            self.status_msg = Some("Nothing to redo".into());
        }
        self.clamp_cursor_after_edit();
    }

    /// Enter the undo time-travel mode: ←/→ scrub backward/forward, Esc exits.
    /// Only meaningful in an editor pane.
    fn enter_undo_mode(&mut self) {
        if self.editor_pos().is_none() {
            self.status_msg = Some("Undo history works in an editor pane".into());
            return;
        }
        self.edit_run = EditRun::None;
        self.mode = Mode::Undo;
        self.undo_status();
    }

    /// Status line shown in undo mode: how far back / forward you can go.
    fn undo_status(&mut self) {
        let (back, fwd) = self
            .editor_pos()
            .and_then(|(_, _, id)| self.buffers.get(&id))
            .map(|b| b.undo_depth())
            .unwrap_or((0, 0));
        self.status_msg =
            Some(format!("TIME-TRAVEL ◂ {back} back · {fwd} forward ▸   ←/→ step · Home/End all · Esc done"));
    }

    fn handle_undo_mode(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Left | KeyCode::Up | KeyCode::Char('u') => { self.do_undo(); self.undo_status(); }
            KeyCode::Right | KeyCode::Down | KeyCode::Char('r') => { self.do_redo(); self.undo_status(); }
            KeyCode::Home => { while self.focused_buf_mut().undo() {} self.clamp_cursor_after_edit(); self.undo_status(); }
            KeyCode::End  => { while self.focused_buf_mut().redo() {} self.clamp_cursor_after_edit(); self.undo_status(); }
            _ => { self.mode = Mode::Edit; self.status_msg = Some("Undo history closed".into()); }
        }
    }

    fn clamp_cursor_after_edit(&mut self) {
        let pane = self.focused_pane();
        let buf_id = match pane.content { PaneContent::Editor(id) => id, _ => return };
        let line_count = self.buffers[&buf_id].line_count();
        let (row, col) = (pane.cursor_row, pane.cursor_col);
        let new_row = row.min(line_count.saturating_sub(1));
        let new_col = col.min(self.buffers[&buf_id].line_len(new_row));
        let p = self.focused_pane_mut();
        p.cursor_row = new_row;
        p.cursor_col = new_col;
        p.col_affinity = new_col;
    }

    // ── Save ─────────────────────────────────────────────────────────────────

    fn do_save(&mut self) {
        if self.focused_buf().path.is_none() {
            self.start_prompt(PromptKind::SaveAs, "Save as: ");
            return;
        }
        let name = self.focused_buf().name.clone();
        match self.focused_buf_mut().save() {
            Ok(_) => self.status_msg = Some(format!("Saved  {}", name)),
            Err(e) => self.status_msg = Some(format!("Save error: {}", e)),
        }
    }

    /// Quit, but never silently discard unsaved work.
    fn request_quit(&mut self) {
        let dirty = self.buffers.values().filter(|b| b.modified).count();
        if dirty == 0 {
            self.should_quit = true;
        } else {
            self.start_prompt(
                PromptKind::ConfirmQuit,
                &format!("{} modified buffer(s):  s save all & quit · q quit anyway · C-g cancel ", dirty),
            );
        }
    }

    /// Crash-safety: quietly save every modified buffer that has a real path.
    /// Scratch buffers are never touched. Called on a timer and on detach.
    pub fn autosave(&mut self) {
        let mut failed: Vec<String> = Vec::new();
        for buf in self.buffers.values_mut() {
            if buf.modified && buf.path.is_some() {
                if buf.save().is_err() {
                    failed.push(buf.name.clone());
                }
            }
        }
        // Autosave is silent when it works — but a failing write (disk full,
        // permission, path gone) must survive: the status line is cleared by the
        // next keypress, so a fast typist would never see it. Route it to the
        // notices queue, which persists until Esc-dismissed. De-dupe so repeated
        // autosave ticks don't stack the same warning.
        if !failed.is_empty() {
            let text = format!("⚠ autosave FAILED: {} — check disk/permissions", failed.join(", "));
            if !self.notices.iter().any(|n| n.text == text) {
                self.notices.push(Notice { text, kind: NoticeKind::Failure });
                self.notices.sort_by(|a, b| a.kind.cmp(&b.kind));
            }
        }
    }

    /// Save every modified buffer that has a path. Returns names left unsaved.
    fn save_all(&mut self) -> Vec<String> {
        let mut unsaved = Vec::new();
        for buf in self.buffers.values_mut() {
            if buf.modified {
                if buf.path.is_some() {
                    if buf.save().is_err() {
                        unsaved.push(buf.name.clone());
                    }
                } else {
                    unsaved.push(buf.name.clone());
                }
            }
        }
        unsaved
    }

    // ── Split panes ──────────────────────────────────────────────────────────

    pub fn split_horizontal(&mut self) {
        if self.tab().layout.count() >= self.tuning.max_panes {
            self.status_msg = Some(format!("Max {} panes", self.tuning.max_panes));
            return;
        }
        let focused = self.focused_pane_id();
        let buf_id = match self.focused_pane().content { PaneContent::Editor(id) => id, _ => self.new_scratch() };
        let new_id = self.alloc_pane(buf_id);
        let (r, c, s) = {
            let p = &self.panes[&focused];
            (p.cursor_row, p.cursor_col, p.scroll_row)
        };
        {
            let p = self.panes.get_mut(&new_id).unwrap();
            p.cursor_row = r;
            p.cursor_col = c;
            p.scroll_row = s;
        }
        let tab = self.tab_mut();
        tab.layout.hsplit(focused, new_id);
        tab.focused_pane = new_id;
        self.status_msg = Some("Split ─".into());
    }

    pub fn split_vertical(&mut self) {
        if self.tab().layout.count() >= self.tuning.max_panes {
            self.status_msg = Some(format!("Max {} panes", self.tuning.max_panes));
            return;
        }
        let focused = self.focused_pane_id();
        let buf_id = match self.focused_pane().content { PaneContent::Editor(id) => id, _ => self.new_scratch() };
        let new_id = self.alloc_pane(buf_id);
        let (r, c, s) = {
            let p = &self.panes[&focused];
            (p.cursor_row, p.cursor_col, p.scroll_row)
        };
        {
            let p = self.panes.get_mut(&new_id).unwrap();
            p.cursor_row = r;
            p.cursor_col = c;
            p.scroll_row = s;
        }
        let tab = self.tab_mut();
        tab.layout.vsplit(focused, new_id);
        tab.focused_pane = new_id;
        self.status_msg = Some("Split │".into());
    }

    /// How many still-running shells live inside these panes.
    fn live_terms_in(&self, pane_ids: &[PaneId]) -> usize {
        pane_ids
            .iter()
            .filter_map(|pid| self.panes.get(pid))
            .filter_map(|p| match p.content {
                PaneContent::Terminal(tid) => self.terms.get(&tid),
                _ => None,
            })
            .filter(|t| !t.exited)
            .count()
    }

    /// Remove panes AND everything they own: their terminals (killing the shell
    /// via Term::drop) and any watch state — never orphan a running PTY.
    fn reap_panes(&mut self, pane_ids: &[PaneId]) {
        for pid in pane_ids {
            if let Some(p) = self.panes.remove(pid) {
                if let PaneContent::Terminal(tid) = p.content {
                    self.terms.remove(&tid);
                    self.watches.remove(&tid);
                }
            }
        }
    }

    /// Gate a close behind one y/n prompt. Fires when it would kill `live`
    /// running shells (data-loss guard) OR when `force` is set (space-warp's
    /// motor-slip guard). Returns true when the caller should stop and wait.
    fn confirm_close(&mut self, live: usize, force: bool, action: Action, what: &str) -> bool {
        if std::mem::take(&mut self.close_confirmed) || (live == 0 && !force) {
            return false;
        }
        let msg = if live > 0 {
            let plural = if live == 1 { "" } else { "s" };
            format!("Close {what}{live} running terminal{plural} will be killed. y/n ")
        } else {
            format!("Close {what}? y/n ")
        };
        self.start_prompt(PromptKind::ConfirmAction(action), &msg);
        true
    }

    pub fn close_pane(&mut self) {
        let force = std::mem::take(&mut self.force_close_confirm);
        if self.tab().layout.count() <= 1 {
            return;
        }
        let focused = self.focused_pane_id();
        if self.confirm_close(self.live_terms_in(&[focused]), force, Action::ClosePane, "this pane") {
            return;
        }
        let next = self.tab().layout.next_pane(focused);
        let tab = self.tab_mut();
        tab.layout.remove(focused);
        tab.focused_pane = next;
        self.reap_panes(&[focused]);
    }

    pub fn focus_next_pane(&mut self) {
        let focused = self.focused_pane_id();
        let next = self.tab().layout.next_pane(focused);
        self.tab_mut().focused_pane = next;
    }

    /// M-arrows — focus the nearest pane in a screen direction, using the
    /// real geometry from the last render.
    fn focus_direction(&mut self, dx: i32, dy: i32) {
        let cur = self.focused_pane_id();
        let cur_rect = match self.pane_rects.iter().find(|(id, _)| *id == cur) {
            Some((_, r)) => *r,
            None => { self.focus_next_pane(); return; } // no geometry yet
        };
        let (cx, cy) = (
            cur_rect.x as i32 + cur_rect.width as i32 / 2,
            cur_rect.y as i32 + cur_rect.height as i32 / 2,
        );
        let mut best: Option<(i32, PaneId)> = None;
        for (id, r) in &self.pane_rects {
            if *id == cur { continue; }
            let px = r.x as i32 + r.width as i32 / 2;
            let py = r.y as i32 + r.height as i32 / 2;
            let (ddx, ddy) = (px - cx, py - cy);
            let aligned = if dx != 0 {
                ddx.signum() == dx && ddx.abs() >= ddy.abs()
            } else {
                ddy.signum() == dy && ddy.abs() >= ddx.abs()
            };
            if aligned {
                let dist = ddx.abs() + ddy.abs();
                if best.map(|(d, _)| dist < d).unwrap_or(true) {
                    best = Some((dist, *id));
                }
            }
        }
        if let Some((_, id)) = best {
            self.tab_mut().focused_pane = id;
        }
    }

    /// Grow/shrink the boundary nearest the focused pane (travel +/-).
    fn resize_pane(&mut self, delta: i16) {
        let focused = self.focused_pane_id();
        self.tab_mut().layout.resize(focused, delta);
    }

    /// Toggle zoom on the focused pane (travel z / tmux prefix-z).
    fn toggle_zoom(&mut self) {
        let focused = self.focused_pane_id();
        let tab = self.tab_mut();
        tab.zoomed = if tab.zoomed == Some(focused) { None } else { Some(focused) };
    }

    /// C-x x — move this pane's content into the next pane slot (swap).
    fn swap_pane(&mut self) {
        let a = self.focused_pane_id();
        let b = self.tab().layout.next_pane(a);
        if a == b { return; }
        let snap_a = self.panes.get(&a).unwrap().clone();
        let snap_b = self.panes.get(&b).unwrap().clone();
        for (dst, src) in [(a, &snap_b), (b, &snap_a)] {
            let p = self.panes.get_mut(&dst).unwrap();
            p.content = src.content.clone();
            p.buffer_id = src.buffer_id;
            p.cursor_row = src.cursor_row;
            p.cursor_col = src.cursor_col;
            p.col_affinity = src.col_affinity;
            p.scroll_row = src.scroll_row;
            p.selection_anchor = src.selection_anchor;
        }
        // Focus follows the moved content.
        self.tab_mut().focused_pane = b;
        self.status_msg = Some("Pane moved".into());
    }

    pub fn focus_prev_pane(&mut self) {
        let focused = self.focused_pane_id();
        let prev = self.tab().layout.prev_pane(focused);
        self.tab_mut().focused_pane = prev;
    }

    // ── Tab management ───────────────────────────────────────────────────────

    pub fn new_tab(&mut self) {
        let buf_id = self.new_scratch();
        let pane_id = self.alloc_pane(buf_id);
        let n = self.tabs.len() + 1;
        let id = self.alloc_tab_id();
        let tab = Tab::new(id, n.to_string(), pane_id);
        self.tabs.push(tab);
        self.active_tab = self.tabs.len() - 1;
    }

    /// Open a file in a NEW tab and switch to it — used when a nested `mars <file>`
    /// (run from a terminal pane inside this session) routes the open here instead
    /// of launching a second Mars.
    pub fn open_file_in_new_tab(&mut self, path: &str) {
        match self.open_file(path) {
            Ok(buf_id) => {
                let pane_id = self.alloc_pane(buf_id);
                let id = self.alloc_tab_id();
                let name = std::path::Path::new(path)
                    .file_name()
                    .and_then(|s| s.to_str())
                    .map(str::to_string)
                    .unwrap_or_else(|| (self.tabs.len() + 1).to_string());
                let tab = Tab::new(id, name.clone(), pane_id);
                self.tabs.push(tab);
                self.active_tab = self.tabs.len() - 1;
                self.mode = Mode::Edit;
                self.status_msg = Some(format!("Opened {name}"));
            }
            Err(e) => self.status_msg = Some(format!("Open failed: {e}")),
        }
    }

    pub fn close_tab(&mut self) {
        let force = std::mem::take(&mut self.force_close_confirm);
        if self.tabs.len() == 1 {
            self.request_quit(); // quit has its own dirty-buffer gate
            return;
        }
        let pane_ids = self.tab().layout.pane_ids();
        if self.confirm_close(self.live_terms_in(&pane_ids), force, Action::CloseTab, "this tab") {
            return;
        }
        self.reap_panes(&pane_ids);
        self.tabs.remove(self.active_tab);
        if self.active_tab >= self.tabs.len() {
            self.active_tab = self.tabs.len() - 1;
        }
    }

    pub fn next_tab(&mut self) {
        if !self.tabs.is_empty() {
            self.active_tab = (self.active_tab + 1) % self.tabs.len();
        }
    }

    pub fn prev_tab(&mut self) {
        if !self.tabs.is_empty() {
            self.active_tab = if self.active_tab == 0 {
                self.tabs.len() - 1
            } else {
                self.active_tab - 1
            };
        }
    }

    /// Reorder: move the active tab one slot left/right (no wrap).
    pub fn move_tab(&mut self, delta: i32) {
        let i = self.active_tab as i32;
        let j = i + delta;
        if j < 0 || j >= self.tabs.len() as i32 {
            return;
        }
        self.tabs.swap(i as usize, j as usize);
        self.active_tab = j as usize;
    }

    /// M-1..M-9 — jump straight to tab N.
    fn goto_tab(&mut self, n: usize) {
        if n >= 1 && n <= self.tabs.len() {
            self.active_tab = n - 1;
        }
    }


    // ── Key handlers ─────────────────────────────────────────────────────────

    pub fn handle_key(&mut self, key: KeyEvent) -> Result<()> {
        self.show_splash = false; // any keypress dismisses the banner
        // One gesture rules everything (doctrine §2): the bar opens from any
        // mode. Edit/Terminal/Bar handle bar-open themselves (prefix-aware /
        // submode-toggling), and a focused minibuffer keeps the keystroke — but
        // the transient nav modes (space warp, tree, time-travel) used to swallow
        // it. Handle those centrally so C-Space never intermittently dies.
        let chord = chord_of(&key);
        let bar_open = self.pending_prefix.is_empty()
            && (self.keys.bar_open.contains(&chord) || matches!(key.code, KeyCode::Null));
        if bar_open && matches!(self.mode, Mode::Tab | Mode::Tree | Mode::Undo) {
            self.open_bar(BarMode::Command);
            return Ok(());
        }
        match self.mode.clone() {
            Mode::Edit     => self.handle_edit(key),
            Mode::Bar      => self.handle_bar(key),
            Mode::Prompt   => self.handle_prompt(key),
            Mode::Tab      => self.handle_tab(key),
            Mode::Terminal => self.handle_terminal(key),
            Mode::Tree     => self.handle_tree(key),
            Mode::Undo     => self.handle_undo_mode(key),
        }
        Ok(())
    }

    // ── Non-modal editing (Emacs/Mac/Claude-Code feel) ───────────────────────

    fn handle_edit(&mut self, key: KeyEvent) {
        self.status_msg = None;
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let chord = chord_of(&key);

        // Ctrl+Space (or NUL, which many terminals send for it) / M-x → bar.
        if self.pending_prefix.is_empty()
            && (self.keys.bar_open.contains(&chord) || matches!(key.code, KeyCode::Null))
        {
            self.open_bar(BarMode::Command);
            return;
        }

        // Terminal pane: Enter (no prefix) re-attaches — or dismisses a dead shell.
        if self.pending_prefix.is_empty() {
            if let PaneContent::Terminal(tid) = self.focused_pane().content {
                if matches!(key.code, KeyCode::Enter) && key.modifiers == KeyModifiers::NONE {
                    if self.terms.get(&tid).map(|t| t.exited).unwrap_or(true) {
                        self.close_terminal_pane(tid);
                    } else {
                        self.mode = Mode::Terminal;
                    }
                    return;
                }
            }
        }

        // C-g / Esc cancel a pending prefix / selection (Emacs quit, modern cancel).
        if (ctrl && matches!(key.code, KeyCode::Char('g')))
            || (matches!(key.code, KeyCode::Esc) && key.modifiers == KeyModifiers::NONE)
        {
            // Esc dismisses a proactive notice first (nothing else pending).
            if self.pending_prefix.is_empty()
                && self.focused_pane().selection_anchor.is_none()
                && self.dismiss_notice()
            {
                return;
            }
            let had_state = !self.pending_prefix.is_empty()
                || self.focused_pane().selection_anchor.is_some();
            self.pending_prefix.clear();
            self.clear_selection();
            if had_state {
                self.status_msg = Some("Quit".into());
            }
            return;
        }

        // Prefix-key state machine (C-x …).
        let mut seq = self.pending_prefix.clone();
        seq.push(chord.clone());
        if let Some(action) = self.keys.lookup(&seq) {
            self.pending_prefix.clear();
            self.run_action(action);
            return;
        }
        let extends = self.keys.edit.keys().any(|k| k.len() > seq.len() && k.starts_with(&seq));
        if extends {
            self.pending_prefix = seq;
            self.prefix_tick = self.frame_tick;
            return;
        }
        if !self.pending_prefix.is_empty() {
            let shown = crate::config::render_chords(&seq);
            self.pending_prefix.clear();
            self.status_msg = Some(format!("{} is undefined", shown));
            return;
        }

        // No binding matched → editing primitives.
        self.handle_edit_primitive(key);
    }

    fn handle_edit_primitive(&mut self, key: KeyEvent) {
        let ctrl  = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt   = key.modifiers.contains(KeyModifiers::ALT);
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let cmd   = key.modifiers.contains(KeyModifiers::SUPER);

        self.last_yank = None; // any primitive key breaks a C-y / M-y chain
        // Undo coalescing: remember the run in progress, then default to breaking
        // it — only the insert/backspace arms below renew it.
        let prev_run = self.edit_run;
        self.edit_run = EditRun::None;

        match key.code {
            // Emacs cursor chords
            KeyCode::Char('f') if ctrl => self.move_right_sel(false),
            KeyCode::Char('b') if ctrl => self.move_left_sel(false),
            KeyCode::Char('n') if ctrl => self.move_down_sel(false),
            KeyCode::Char('p') if ctrl => self.move_up_sel(false),
            KeyCode::Char('a') if ctrl => self.move_line_start_sel(false),
            KeyCode::Char('e') if ctrl => self.move_line_end_sel(false),
            KeyCode::Char('d') if ctrl => self.delete_char_forward(),
            KeyCode::Char('f') if alt  => self.move_word_forward(),
            KeyCode::Char('b') if alt  => self.move_word_backward(),
            KeyCode::Char('v') if alt  => self.page_up(),

            // M-1..M-9 — jump to tab N (browser standard).
            KeyCode::Char(c) if alt && c.is_ascii_digit() => {
                self.goto_tab((c as u8 - b'0') as usize);
            }

            // Fast motion — ⌘ (kitty terminals) OR Option/Alt (the universal
            // fallback where the OS eats ⌘): ⌥←/→ = code-token, ⌥↑/↓ = page;
            // Shift extends the selection.
            KeyCode::Left  if cmd || alt => self.move_token_sel(false, shift),
            KeyCode::Right if cmd || alt => self.move_token_sel(true, shift),
            KeyCode::Up    if cmd || alt => self.page_up(),
            KeyCode::Down  if cmd || alt => self.page_down(),

            // Ctrl+arrows — directional pane focus (C-o and C-t travel also work).
            KeyCode::Left  if ctrl => self.focus_direction(-1, 0),
            KeyCode::Right if ctrl => self.focus_direction(1, 0),
            KeyCode::Up    if ctrl => self.focus_direction(0, -1),
            KeyCode::Down  if ctrl => self.focus_direction(0, 1),

            // Arrows / nav (Shift extends the selection, Mac-style)
            KeyCode::Left  => self.move_left_sel(shift),
            KeyCode::Right => self.move_right_sel(shift),
            KeyCode::Up    => self.move_up_sel(shift),
            KeyCode::Down  => self.move_down_sel(shift),
            KeyCode::Home  => self.move_line_start_sel(shift),
            KeyCode::End   => self.move_line_end_sel(shift),
            KeyCode::PageUp   => self.page_up(),
            KeyCode::PageDown => self.page_down(),

            // Editing — an active selection is replaced/deleted (Mac contract).
            // Consecutive backspaces / typed chars coalesce into ONE undo step.
            KeyCode::Backspace => {
                if !self.delete_selection() {
                    if prev_run != EditRun::Delete { self.focused_buf_mut().checkpoint(); }
                    self.delete_before_cursor();
                    self.edit_run = EditRun::Delete;
                }
            }
            KeyCode::Delete => {
                if !self.delete_selection() { self.delete_char_forward(); }
            }
            KeyCode::Enter => {
                self.focused_buf_mut().checkpoint();
                self.delete_selection();
                self.insert_char_at_cursor('\n');
                self.auto_indent(); // carry the previous line's leading whitespace
            }
            KeyCode::Tab   => {
                if self.focused_pane().selection_anchor.is_some() {
                    self.indent_region(false); // Tab indents the selected lines
                } else {
                    if prev_run != EditRun::Insert { self.focused_buf_mut().checkpoint(); }
                    for _ in 0..4 { self.insert_char_at_cursor(' '); }
                    self.edit_run = EditRun::Insert;
                }
            }
            KeyCode::BackTab => self.indent_region(true), // Shift-Tab dedents
            KeyCode::Char(c) if !ctrl && !alt => {
                if self.delete_selection() {
                    // replace: the delete checkpointed; typing joins that step
                } else if prev_run != EditRun::Insert {
                    self.focused_buf_mut().checkpoint();
                }
                self.insert_char_at_cursor(c);
                self.edit_run = EditRun::Insert;
            }
            _ => {}
        }
    }

    /// Indent (+4 spaces) or dedent (≤4 leading spaces / one tab) every line the
    /// selection touches, or the current line if there's no selection. One undo
    /// step; the selection is preserved so Tab/Shift-Tab can repeat.
    fn indent_region(&mut self, dedent: bool) {
        let sel = self.selection_range();
        let (buf_id, start_row, end_row) = match sel {
            Some((id, s, e)) => {
                let (sr, _) = self.rowcol_of(id, s);
                let (er, ec) = self.rowcol_of(id, e);
                // A selection ending at column 0 doesn't include that trailing line.
                let er = if ec == 0 && er > sr { er - 1 } else { er };
                (id, sr, er)
            }
            None => match self.editor_pos() {
                Some((row, _, id)) => (id, row, row),
                None => return,
            },
        };
        self.focused_buf_mut().checkpoint();
        self.edit_run = EditRun::None;
        for row in start_row..=end_row {
            let line_start = self.buffers[&buf_id].char_at(row, 0);
            if dedent {
                let head: String = self.buffers[&buf_id].rope.line(row).chars().take(4).collect();
                let n = if head.starts_with('\t') { 1 } else { head.chars().take_while(|c| *c == ' ').count() };
                if n > 0 {
                    self.buffers.get_mut(&buf_id).unwrap().rope.remove(line_start..line_start + n);
                }
            } else {
                self.buffers.get_mut(&buf_id).unwrap().rope.insert(line_start, "    ");
            }
        }
        self.buffers.get_mut(&buf_id).unwrap().modified = true;
        if sel.is_some() {
            // Re-select the affected lines so the block stays highlighted for repeats.
            let end_len = self.buffers[&buf_id].line_len(end_row);
            self.focused_pane_mut().selection_anchor = Some((start_row, 0));
            let p = self.focused_pane_mut();
            p.cursor_row = end_row;
            p.cursor_col = end_len;
            p.col_affinity = end_len;
        } else {
            self.clamp_cursor_after_edit();
        }
    }

    // ── Query-replace (M-%) ──────────────────────────────────────────────────

    fn begin_query_replace(&mut self) {
        self.replace_checkpointed = false;
        self.replace_idx = None;
        // Scan the whole buffer from the top (the "search & replace" expectation).
        if self.qr_show_next(0) {
            let label = format!("Replace '{}' → '{}'?  y / n / ! (all) / q ", self.replace_from, self.replace_to);
            self.start_prompt(PromptKind::QueryReplace, &label);
        } else {
            self.status_msg = Some(format!("No matches for '{}'", self.replace_from));
        }
    }

    /// Find the next match at/after `from_idx`; move the cursor there + highlight.
    fn qr_show_next(&mut self, from_idx: usize) -> bool {
        let from = self.replace_from.clone();
        let buf_id = match self.editor_pos() { Some((_, _, id)) => id, None => return false };
        match self.find_matches(buf_id, &from).into_iter().find(|&m| m >= from_idx) {
            Some(idx) => {
                self.replace_idx = Some(idx);
                let (r, c) = self.rowcol_of(buf_id, idx);
                self.set_cursor(r, c);
                self.search_hl = vec![(r, c, from.chars().count())];
                true
            }
            None => false,
        }
    }

    fn qr_replace_at(&mut self, idx: usize, flen: usize, to: &str) {
        let buf_id = match self.editor_pos() { Some((_, _, id)) => id, None => return };
        if !self.replace_checkpointed {
            self.focused_buf_mut().checkpoint(); // one undo step for the whole replace
            self.replace_checkpointed = true;
        }
        let buf = self.buffers.get_mut(&buf_id).unwrap();
        buf.rope.remove(idx..idx + flen);
        buf.rope.insert(idx, to);
        buf.modified = true;
    }

    fn qr_finish(&mut self) {
        self.replace_idx = None;
        self.search_hl.clear();
        self.close_prompt();
    }

    fn handle_query_replace_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let to = self.replace_to.clone();
        let flen = self.replace_from.chars().count();
        let tlen = to.chars().count();
        let Some(idx) = self.replace_idx else { self.qr_finish(); return };
        match key.code {
            KeyCode::Char('y') | KeyCode::Char(' ') => {
                self.qr_replace_at(idx, flen, &to);
                if !self.qr_show_next(idx + tlen) {
                    self.qr_finish();
                    self.status_msg = Some("Replaced".into());
                }
            }
            KeyCode::Char('n') => {
                if !self.qr_show_next(idx + flen) { self.qr_finish(); }
            }
            KeyCode::Char('!') => {
                let mut count = 0;
                loop {
                    let m = self.replace_idx.unwrap();
                    self.qr_replace_at(m, flen, &to);
                    count += 1;
                    if !self.qr_show_next(m + tlen) { break; }
                }
                self.qr_finish();
                self.status_msg = Some(format!("Replaced {count}"));
            }
            KeyCode::Char('q') | KeyCode::Esc => self.qr_finish(),
            KeyCode::Char('g') if ctrl => self.qr_finish(),
            _ => {}
        }
    }

    /// Delete the active selection (no kill-ring). Returns true if one existed.
    fn delete_selection(&mut self) -> bool {
        if let Some((buf_id, s, e)) = self.selection_range() {
            {
                let buf = self.buffers.get_mut(&buf_id).unwrap();
                buf.checkpoint();
                buf.rope.remove(s..e);
                buf.modified = true;
            }
            let (r, c) = self.rowcol_of(buf_id, s);
            self.set_cursor(r, c);
            self.clear_selection();
            true
        } else {
            self.clear_selection();
            false
        }
    }

    // ── Minibuffer prompt (find-file, switch-buffer, search) ──────────────────

    fn open_bar(&mut self, bar_mode: BarMode) {
        // Remember where to return: a terminal keeps its focus (seamless switch).
        self.bar_return = if self.mode == Mode::Terminal { Mode::Terminal } else { Mode::Edit };
        let mut p = Palette::root();
        p.bar_mode = bar_mode;
        // Editor bars are menu-first (a row is always selected); the terminal
        // composer opens unengaged — typing or arrowing selects the top match
        // (registry-first Enter), and an unengaged Enter is a no-op.
        p.navigated = self.bar_return != Mode::Terminal;
        self.palette = Some(p);
        self.mode = Mode::Bar;
        self.shell_ready = false;
    }

    fn start_prompt(&mut self, kind: PromptKind, label: &str) {
        self.start_prompt_with(kind, label, "");
    }

    /// Prompt pre-filled with the current value (rename flows).
    fn start_prompt_with(&mut self, kind: PromptKind, label: &str, initial: &str) {
        self.prompt = Some(Prompt {
            label: label.to_string(),
            input: initial.to_string(),
            kind,
        });
        self.mode = Mode::Prompt;
    }

    fn handle_prompt(&mut self, key: KeyEvent) {
        let kind = match self.prompt.as_ref() {
            Some(p) => p.kind.clone(),
            None => { self.mode = Mode::Edit; return; }
        };
        match kind {
            PromptKind::Search => self.handle_isearch_key(key),
            PromptKind::ConfirmQuit => self.handle_confirm_quit_key(key),
            PromptKind::ConfirmAction(action) => self.handle_confirm_action_key(key, action),
            PromptKind::QueryReplace => self.handle_query_replace_key(key),
            _ => self.handle_line_prompt_key(key),
        }
    }

    fn close_prompt(&mut self) {
        self.prompt = None;
        self.mode = Mode::Edit;
    }

    fn handle_line_prompt_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        if ctrl && matches!(key.code, KeyCode::Char('g')) {
            self.close_prompt();
            return;
        }
        match key.code {
            KeyCode::Esc => self.close_prompt(),
            KeyCode::Enter => {
                if let Some(p) = self.prompt.take() {
                    self.mode = Mode::Edit;
                    self.finish_prompt(p);
                }
            }
            KeyCode::Backspace => { if let Some(p) = self.prompt.as_mut() { p.input.pop(); } }
            KeyCode::Char(c) if !ctrl => { if let Some(p) = self.prompt.as_mut() { p.input.push(c); } }
            _ => {}
        }
    }

    /// Live isearch: typing filters immediately; C-s/C-r step; Enter accepts;
    /// C-g/Esc restores the origin.
    fn handle_isearch_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let query = self.prompt.as_ref().map(|p| p.input.clone()).unwrap_or_default();

        // Label-pick mode (after Tab): the next key jumps to a labeled match.
        if self.search_pick {
            self.search_pick = false;
            if let KeyCode::Char(c) = key.code {
                if let Some(&(r, col, _)) = self.search_labels.iter().find(|(_, _, l)| *l == c) {
                    self.set_cursor(r, col);
                    self.end_isearch(false);
                    self.close_prompt();
                    return;
                }
            }
            self.search_labels.clear(); // not a label → drop labels, handle normally
        }

        if ctrl && matches!(key.code, KeyCode::Char('g')) {
            self.end_isearch(true);
            self.close_prompt();
            return;
        }
        match key.code {
            KeyCode::Esc => { self.end_isearch(true); self.close_prompt(); }
            KeyCode::Enter => { self.end_isearch(false); self.close_prompt(); }
            KeyCode::Char('s') if ctrl => self.isearch_step(&query, true),
            KeyCode::Char('r') if ctrl => self.isearch_step(&query, false),
            // Tab → teleport: label the matches; the next key jumps to one.
            KeyCode::Tab => {
                if self.search_hl.len() >= 2 {
                    self.build_search_labels();
                    self.search_pick = true;
                }
            }
            KeyCode::Backspace => {
                if let Some(p) = self.prompt.as_mut() { p.input.pop(); }
                let q = self.prompt.as_ref().map(|p| p.input.clone()).unwrap_or_default();
                self.update_isearch(&q);
            }
            KeyCode::Char(c) if !ctrl => {
                if let Some(p) = self.prompt.as_mut() { p.input.push(c); }
                let q = self.prompt.as_ref().map(|p| p.input.clone()).unwrap_or_default();
                self.update_isearch(&q);
            }
            // Land-on-any-key: any other key accepts at the current match, then is
            // applied in edit mode — so search flows straight into editing.
            _ => {
                self.end_isearch(false);
                self.close_prompt();
                let _ = self.handle_key(key);
            }
        }
    }

    /// Assign home-row labels to the first matches (document order) for Tab-pick.
    fn build_search_labels(&mut self) {
        const ALPHA: &[u8] = b"asdfghjklqwertyuiopvbnm";
        self.search_labels = self
            .search_hl
            .iter()
            .take(ALPHA.len())
            .enumerate()
            .map(|(i, &(r, c, _))| (r, c, ALPHA[i] as char))
            .collect();
    }

    /// (1-based current, total) match index at the cursor, for the `n/m` counter.
    pub fn isearch_status(&self) -> Option<(usize, usize)> {
        let total = self.search_hl.len();
        if total == 0 {
            return None;
        }
        let pane = self.focused_pane();
        let (cr, cc) = (pane.cursor_row, pane.cursor_col);
        let cur = self
            .search_hl
            .iter()
            .position(|&(r, c, _)| r == cr && c == cc)
            .map(|i| i + 1)
            .unwrap_or(0);
        Some((cur, total))
    }

    fn handle_confirm_quit_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        if ctrl && matches!(key.code, KeyCode::Char('g')) {
            self.close_prompt();
            return;
        }
        match key.code {
            KeyCode::Char('s') => {
                let unsaved = self.save_all();
                self.close_prompt();
                if unsaved.is_empty() {
                    self.should_quit = true;
                } else {
                    self.status_msg = Some(format!(
                        "No file for: {} — save it first (C-x C-s)",
                        unsaved.join(", ")
                    ));
                }
            }
            KeyCode::Char('q') | KeyCode::Char('!') => {
                self.close_prompt();
                self.should_quit = true;
            }
            KeyCode::Esc | KeyCode::Char('n') => self.close_prompt(),
            _ => {}
        }
    }

    fn handle_confirm_action_key(&mut self, key: KeyEvent, action: Action) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Char('y') | KeyCode::Enter => {
                self.close_prompt();
                self.close_confirmed = true; // the gated close_* runs once, un-re-prompted
                self.run_action(action);
                self.close_confirmed = false;
            }
            _ if ctrl || matches!(key.code, KeyCode::Esc | KeyCode::Char('n')) => {
                self.close_prompt();
                self.status_msg = Some("Cancelled".into());
            }
            _ => {}
        }
    }

    fn finish_prompt(&mut self, p: Prompt) {
        match p.kind {
            PromptKind::ReplaceFrom => {
                self.replace_from = p.input;
                if self.replace_from.is_empty() {
                    return;
                }
                self.start_prompt(PromptKind::ReplaceTo, "Replace with: ");
            }
            PromptKind::ReplaceTo => {
                self.replace_to = p.input;
                self.begin_query_replace();
            }
            PromptKind::GotoLine => {
                match p.input.trim().parse::<usize>() {
                    Ok(n) if n >= 1 => {
                        if let Some((_, _, buf_id)) = self.editor_pos() {
                            let last = self.buffers[&buf_id].line_count().saturating_sub(1);
                            let row = (n - 1).min(last);
                            self.set_cursor(row, 0);
                            self.recenter();
                        }
                    }
                    _ => self.status_msg = Some("Not a line number".into()),
                }
            }
            PromptKind::SaveAs => {
                let path = p.input.trim().to_string();
                if path.is_empty() { return; }
                let result = self
                    .focused_buf_mut()
                    .save_as(std::path::PathBuf::from(&path));
                self.status_msg = Some(match result {
                    Ok(_) => format!("Saved  {}", path),
                    Err(e) => format!("Save error: {}", e),
                });
            }
            PromptKind::RenameTab => {
                let name = p.input.trim().to_string();
                if !name.is_empty() {
                    let id = self.tab().id;
                    self.auto_name_attempted.insert(id); // manual name opts out
                    self.tab_mut().name = name;
                }
            }
            PromptKind::RenamePane => {
                let title = p.input.trim().to_string();
                let pid = self.focused_pane_id();
                if let Some(pane) = self.panes.get_mut(&pid) {
                    pane.title = if title.is_empty() { None } else { Some(title) };
                }
            }
            PromptKind::RenameSession => {
                let name = p.input.trim().to_string();
                if !name.is_empty() && !name.contains('/') {
                    self.rename_session_to = Some(name);
                } else if !name.is_empty() {
                    self.status_msg = Some("Session names cannot contain '/'".into());
                }
            }
            // Search / confirms / query-replace are handled key-by-key, never via finish.
            PromptKind::Search | PromptKind::ConfirmQuit
            | PromptKind::ConfirmAction(_) | PromptKind::QueryReplace => {}
        }
    }

    /// C-t travel mode — one-char verbs for tabs and panes, with an on-screen
    /// cheat panel. Rule: creation exits the mode, navigation stays.
    fn handle_tab(&mut self, key: KeyEvent) {
        let ctrl  = key.modifiers.contains(KeyModifiers::CONTROL);
        let shift = key.modifiers == KeyModifiers::SHIFT;

        // Leave: Esc / Enter / C-g / C-t (back to whatever the pane hosts).
        if matches!(key.code, KeyCode::Esc | KeyCode::Enter)
            || (ctrl && matches!(key.code, KeyCode::Char('g') | KeyCode::Char('t')))
        {
            self.mode = self.mode_for_focused_pane();
            return;
        }

        match key.code {
            // ── Tabs ──
            KeyCode::Char('t') | KeyCode::Char('n') => {
                self.new_tab();
                self.mode = Mode::Edit; // creation exits — you'll want to type
            }
            // Destructive warp verbs sit beside navigation keys (d~h/l, 0~1-9) —
            // a motor slip must cost a prompt, not a tab. force_close_confirm
            // makes the close gate always fire here (even with no live terminal).
            KeyCode::Char('d') => {
                self.force_close_confirm = true;
                self.close_tab();
            }
            KeyCode::Char('T') => {
                // Open a terminal in a NEW tab (non-destructive; creation exits).
                self.new_tab();
                self.open_terminal(); // converts the new tab's pane; sets Mode::Terminal
            }
            KeyCode::Char('r') => self.run_action(Action::RenameTab), // → prompt, exits mode
            KeyCode::Char('?') => self.run_action(Action::ExplainFailure), // triage → Ask
            KeyCode::Char('w') => self.toggle_watch_pane(), // W6: watch this pane
            KeyCode::Char('h') | KeyCode::Left if !shift => self.prev_tab(),
            KeyCode::Char('l') | KeyCode::Right if !shift => self.next_tab(),
            KeyCode::Char('H') => self.move_tab(-1),
            KeyCode::Char('L') => self.move_tab(1),
            KeyCode::Left  if shift => self.move_tab(-1),
            KeyCode::Right if shift => self.move_tab(1),
            KeyCode::Char(c) if c.is_ascii_digit() && c != '0' => {
                self.goto_tab((c as u8 - b'0') as usize);
                self.mode = self.mode_for_focused_pane(); // land ready to use
            }
            // ── Panes ──
            KeyCode::Char('o') | KeyCode::Tab => self.focus_next_pane(),
            KeyCode::Char('x') => self.swap_pane(),
            KeyCode::Char('z') => self.toggle_zoom(),
            KeyCode::Char('>') | KeyCode::Char('+') | KeyCode::Char('=') => self.resize_pane(6),
            KeyCode::Char('<') => self.resize_pane(-6),
            KeyCode::Char('|') | KeyCode::Char('\\') | KeyCode::Char('v') => {
                self.split_vertical();
                self.mode = Mode::Edit;
            }
            KeyCode::Char('-') | KeyCode::Char('s') => {
                self.split_horizontal();
                self.mode = Mode::Edit;
            }
            KeyCode::Char('q') | KeyCode::Char('0') => {
                self.force_close_confirm = true; // motor-slip guard (0 ~ digit row)
                self.close_pane();
            }
            // ── Session ──
            KeyCode::Char('D') => {
                self.run_action(Action::Detach);
                if !self.detach_requested {
                    self.mode = self.mode_for_focused_pane(); // standalone: just exit mode
                }
            }
            _ => {}
        }
    }

    // ── Command bar (was handle_palette) ─────────────────────────────────────

    fn handle_bar(&mut self, key: KeyEvent) {
        let ctrl  = key.modifiers.contains(KeyModifiers::CONTROL);
        let none  = key.modifiers == KeyModifiers::NONE;
        let shift = key.modifiers == KeyModifiers::SHIFT;

        // C-g cancels the bar from every submode — the one overlearned recovery
        // chord (doctrine §3.4) must be reliable here, the most-used surface.
        if ctrl && matches!(key.code, KeyCode::Char('g')) {
            self.close_bar();
            return;
        }

        // Ctrl+Space inside a sub-mode (shell / file) → the full command bar.
        let chord = chord_of(&key);
        if self.keys.bar_open.contains(&chord) || matches!(key.code, KeyCode::Null) {
            if let Some(p) = self.palette.as_mut() {
                if p.bar_mode == BarMode::Shell {
                    p.bar_mode = BarMode::Command;
                    p.query.clear();
                    p.selected = 0;
                    self.shell_ready = false;
                }
            }
            return;
        }

        // Tab: in shell mode it TRANSLATES the English query into a command;
        // elsewhere it toggles CMD ↔ ASK.
        if let KeyCode::Tab = key.code {
            let mode = self.palette.as_ref().map(|p| p.bar_mode.clone());
            match mode {
                Some(BarMode::Shell) => { self.translate_shell_query(); return; }
                _ => {
                    if let Some(p) = self.palette.as_mut() {
                        p.bar_mode = match p.bar_mode {
                            BarMode::Command => BarMode::Ask,
                            _ => BarMode::Command,
                        };
                    }
                    return;
                }
            }
        }

        // Leading '!' / '?' / '@' on an empty query switches mode instead of typing:
        // `!` shell, `?` ask, `@` file picker (VS Code Ctrl+P style).
        let empty_query = self.palette.as_ref().map(|p| p.query.is_empty()).unwrap_or(false);
        if (none || shift) && empty_query {
            match key.code {
                KeyCode::Char('!') => {
                    if let Some(p) = self.palette.as_mut() { p.bar_mode = BarMode::Shell; }
                    return;
                }
                KeyCode::Char('?') => {
                    if let Some(p) = self.palette.as_mut() { p.bar_mode = BarMode::Ask; }
                    return;
                }
                KeyCode::Char('@') => {
                    self.close_bar();
                    self.toggle_file_tree(); // `@` opens the left file tree
                    return;
                }
                _ => {}
            }
        }

        let bar_mode = self
            .palette
            .as_ref()
            .map(|p| p.bar_mode.clone())
            .unwrap_or(BarMode::Command);
        match bar_mode {
            BarMode::Command => self.handle_bar_command(key, ctrl, none, shift),
            BarMode::Ask     => self.handle_bar_ask(key, none, shift),
            BarMode::Shell   => self.handle_bar_shell(key, none, shift),
        }
    }

    /// Clear the bar and any pending agent state, returning to the mode the
    /// bar was opened from (Edit, or Terminal for seamless switching).
    /// The unified terminal composer's shell fallback: the query didn't match a
    /// command, so translate it (LLM) into a shell command for confirmation —
    /// or, with no agent key, run it directly.
    fn submit_terminal_shell(&mut self) {
        let cmd = self.palette.as_ref().map(|p| p.query.clone()).unwrap_or_default();
        if cmd.trim().is_empty() {
            return;
        }
        if self.shell_ready || !agent::AgentConfig::from_env().is_configured() {
            self.close_bar();
            self.run_shell_command(&cmd);
        } else {
            // Flip to the inline shell composer so the translated command shows,
            // anchored at the cursor, for a confirming second Enter.
            if let Some(p) = self.palette.as_mut() { p.bar_mode = BarMode::Shell; }
            self.translate_shell_query();
        }
    }

    fn close_bar(&mut self) {
        // A pending, un-accepted translation dismissed here = a reject signal.
        // (Accept clears translate_call_id first, so this only fires on cancel.)
        if let Some(id) = self.translate_call_id.take() {
            crate::llm_log::record_outcome(id, None, false, true);
        }
        self.translate_request = None;
        self.palette = None;
        self.mode = self.bar_return.clone();
        self.agent_answer = None;
        self.agent_partial = None;
        self.agent_directive = None;
        self.refactor_target = None;
        self.refactor_replacement = None;
        self.ask_scroll = 0;
        // agent_pending/agent_history survive — an in-flight answer lands in
        // the transcript and is there when the bar reopens.
    }

    fn handle_bar_command(&mut self, key: KeyEvent, ctrl: bool, none: bool, shift: bool) {
        let items_len = {
            let frec = &self.frecency;
            self.palette.as_ref().map(|p| p.visible_items(frec).len()).unwrap_or(0)
        };

        match key.code {
            KeyCode::Esc => {
                let close = if let Some(p) = self.palette.as_mut() { !p.pop() } else { true };
                if close { self.close_bar(); }
            }
            KeyCode::Up | KeyCode::BackTab => {
                if let Some(p) = self.palette.as_mut() { p.select_up(items_len); }
            }
            KeyCode::Down => {
                if let Some(p) = self.palette.as_mut() { p.select_down(items_len); }
            }
            KeyCode::Char('p') if ctrl => {
                if let Some(p) = self.palette.as_mut() { p.select_up(items_len); }
            }
            KeyCode::Char('n') if ctrl => {
                if let Some(p) = self.palette.as_mut() { p.select_down(items_len); }
            }
            KeyCode::Enter => {
                let frec = &self.frecency;
                let (kind, navigated) = self
                    .palette
                    .as_ref()
                    .map(|p| {
                        (p.visible_items(frec).into_iter().nth(p.selected).map(|r| r.kind), p.navigated)
                    })
                    .unwrap_or((None, false));
                // REGISTRY-FIRST (2026-07 ruling, reversing the earlier
                // shell-first one): typing pre-selects the top match and Enter
                // fires it — commands stay one keystroke away. Only when
                // nothing in the registry matches does the query fall through
                // to natural language: shell-translate in a terminal, an
                // editor-grounded ask elsewhere. `!` still forces pure shell.
                let has_query = self.palette.as_ref().map(|p| !p.query.trim().is_empty()).unwrap_or(false);
                if kind.is_some() && (navigated || has_query) {
                    self.activate_kind(kind);
                } else if has_query {
                    if self.bar_return == Mode::Terminal {
                        self.submit_terminal_shell();
                    } else {
                        if let Some(p) = self.palette.as_mut() { p.bar_mode = BarMode::Ask; }
                        self.submit_agent_query();
                    }
                }
                // Empty query, nothing highlighted → Enter is a no-op: it must
                // never fire a row the user can't see is selected.
            }
            KeyCode::Backspace => {
                let close = if let Some(p) = self.palette.as_mut() {
                    if p.query.is_empty() {
                        !p.pop()
                    } else {
                        p.query.pop();
                        p.selected = 0;
                        p.navigated = !p.query.is_empty();
                        false
                    }
                } else { false };
                if close { self.close_bar(); }
            }
            // Search-first (Claude-Code feel): typing always filters, and the
            // top match is selected so Enter fires it with no arrowing.
            KeyCode::Char(c) if none || shift => {
                if let Some(p) = self.palette.as_mut() {
                    p.query.push(c);
                    p.selected = 0;
                    p.navigated = true;
                }
            }
            _ => {}
        }
    }

    /// Ask-the-AI submode: text is a natural-language question; Enter sends it,
    /// and a second Enter fires any directive (RUN/TYPE) the model proposed.
    fn handle_bar_ask(&mut self, key: KeyEvent, none: bool, shift: bool) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // C-l starts a fresh conversation.
        if ctrl && matches!(key.code, KeyCode::Char('l')) {
            self.agent_history.clear();
            self.agent_answer = None;
            self.agent_partial = None;
            self.agent_directive = None;
            self.refactor_target = None;
            self.refactor_replacement = None;
            self.ask_scroll = 0;
            return;
        }

        match key.code {
            KeyCode::Esc => self.close_bar(),
            // Scroll the transcript.
            KeyCode::Up => self.ask_scroll = self.ask_scroll.saturating_add(1),
            KeyCode::Down => self.ask_scroll = self.ask_scroll.saturating_sub(1),
            KeyCode::Enter => {
                // A pending refactor is confirmed with Enter (unless you're typing
                // a follow-up question), applied as one reversible edit.
                let has_query = self.palette.as_ref().map(|p| !p.query.trim().is_empty()).unwrap_or(false);
                if self.refactor_replacement.is_some() && !has_query {
                    self.apply_refactor();
                    return;
                }
                match self.agent_directive.clone() {
                    Some(agent::AgentDirective::Run(name)) => {
                        self.agent_directive = None;
                        let Some(action) = Action::from_name(&name) else {
                            self.agent_answer = Some(format!("⚠ unknown action: {name}"));
                            return;
                        };
                        self.close_bar();
                        if action.is_destructive() {
                            // Never let the model fire a destructive action unconfirmed.
                            self.start_prompt(
                                PromptKind::ConfirmAction(action.clone()),
                                &format!("Agent wants to run “{}” — y run · n cancel ", action.label()),
                            );
                        } else {
                            self.run_action(action);
                        }
                    }
                    Some(agent::AgentDirective::Type(cmd)) => {
                        self.agent_directive = None;
                        self.close_bar();
                        self.run_shell_command(&cmd);
                    }
                    Some(agent::AgentDirective::Open(loc)) => {
                        self.agent_directive = None;
                        self.close_bar();
                        self.open_at(&loc);
                    }
                    // NEED is auto-satisfied in tick and never surfaced here.
                    Some(agent::AgentDirective::Need(_)) => { self.agent_directive = None; }
                    None => self.submit_agent_query(),
                }
            }
            KeyCode::Backspace => {
                let close = if let Some(p) = self.palette.as_mut() {
                    if p.query.is_empty() {
                        true
                    } else {
                        p.query.pop();
                        false
                    }
                } else { false };
                if close {
                    self.close_bar();
                } else {
                    self.agent_directive = None; // a new edit invalidates the suggestion
                }
            }
            KeyCode::Char(c) if none || shift => {
                if let Some(p) = self.palette.as_mut() { p.query.push(c); }
                self.agent_directive = None;
            }
            _ => {}
        }
    }

    /// Inline natural-language shell composer. Enter translates the English
    /// request into a shell command via the agent (shown for confirmation),
    /// then a second Enter runs it. With no API key it runs the text literally.
    fn handle_bar_shell(&mut self, key: KeyEvent, none: bool, shift: bool) {
        match key.code {
            KeyCode::Esc => self.close_bar(),
            KeyCode::Enter => {
                let cmd = self.palette.as_ref().map(|p| p.query.clone()).unwrap_or_default();
                if cmd.trim().is_empty() {
                    return;
                }
                if self.shell_ready || !agent::AgentConfig::from_env().is_configured() {
                    // Command is ready (translated), or there's no key to
                    // translate with → run what's shown. Record accept BEFORE
                    // close_bar clears the correlation state, and remember the
                    // (request → accepted command) pair for corrective memory.
                    if let Some(id) = self.translate_call_id.take() {
                        if let Some(req) = self.translate_request.take() {
                            crate::retrieval::remember_command(&req, &cmd);
                        }
                        crate::llm_log::record_outcome(id, Some(&cmd), false, false);
                    }
                    self.close_bar();
                    self.run_shell_command(&cmd);
                } else {
                    // Translate the English request; the command lands in the
                    // pill (shell_ready) and the next Enter runs it.
                    self.translate_shell_query();
                }
            }
            KeyCode::Backspace => {
                self.on_translation_edited();
                self.shell_ready = false; // an edit invalidates the translation
                self.agent_answer = None; // and clears any stale error
                if let Some(p) = self.palette.as_mut() {
                    if p.query.is_empty() {
                        p.bar_mode = BarMode::Command;
                    } else {
                        p.query.pop();
                    }
                }
            }
            KeyCode::Char(c) if none || shift => {
                self.on_translation_edited();
                self.shell_ready = false;
                self.agent_answer = None;
                if let Some(p) = self.palette.as_mut() { p.query.push(c); }
            }
            _ => {}
        }
    }

    /// `OPEN: path:line` — open a file at a line (from a cited stack trace).
    /// If the focused pane is a terminal, split first so it stays visible.
    fn open_at(&mut self, loc: &str) {
        // Parse "path:line" — line optional, trailing ":col" tolerated.
        let (path, line) = match loc.rsplit_once(':') {
            Some((p, n)) if n.chars().all(|c| c.is_ascii_digit()) && !n.is_empty() => {
                (p.to_string(), n.parse::<usize>().unwrap_or(1))
            }
            _ => (loc.to_string(), 1),
        };
        let path = path.trim();
        if path.is_empty() {
            return;
        }
        // Keep a visible terminal by opening the file beside it.
        if matches!(self.focused_pane().content, PaneContent::Terminal(_))
            && self.tab().layout.count() < self.tuning.max_panes
        {
            self.split_vertical();
        }
        match self.open_file(path) {
            Ok(buf_id) => {
                let pid = self.focused_pane_id();
                if let Some(pane) = self.panes.get_mut(&pid) {
                    pane.content = PaneContent::Editor(buf_id);
                }
                let last = self.buffers[&buf_id].line_count().saturating_sub(1);
                let row = line.saturating_sub(1).min(last);
                self.set_cursor(row, 0);
                self.recenter();
                self.mode = Mode::Edit;
                self.status_msg = Some(format!("Opened {}:{}", path, line));
            }
            Err(e) => self.status_msg = Some(format!("Can't open {}: {}", path, e)),
        }
    }

    // ── Left file-tree sidebar (@ / C-x d) ───────────────────────────────────

    /// Open/focus/hide the tree (tri-state): closed → open+focus; open+focused →
    /// hide; open+unfocused → focus. Keeps the sidebar persistent across opens.
    pub fn toggle_file_tree(&mut self) {
        if !self.tree_open {
            self.ensure_project_index();
            if self.file_tree.is_none() {
                let root = self
                    .project_index
                    .as_ref()
                    .map(|i| i.root.clone())
                    .unwrap_or_else(|| std::path::PathBuf::from("."));
                // Absolute path so `../` (parent) navigation works — a relative
                // "." has an empty parent and would blank the tree.
                let root = std::fs::canonicalize(&root).unwrap_or(root);
                self.file_tree = Some(FileTree {
                    root,
                    expanded: std::collections::HashSet::new(),
                    selected: 0,
                    filter: String::new(),
                });
            }
            self.tree_open = true;
            self.mode = Mode::Tree;
            self.refresh_tree_rows();
        } else if self.mode == Mode::Tree {
            self.close_tree();
        } else {
            self.mode = Mode::Tree;
            self.refresh_tree_rows();
        }
    }

    /// Hide the sidebar and forget its navigation state, so the next open starts
    /// fresh at the project root (not wherever `../` last wandered to).
    fn close_tree(&mut self) {
        self.tree_open = false;
        self.mode = Mode::Edit;
        self.file_tree = None;
        self.tree_rows.clear();
    }

    /// Recompute the flattened visible rows after any tree mutation.
    fn refresh_tree_rows(&mut self) {
        let rows = self.compute_tree_rows();
        let n = rows.len();
        self.tree_rows = rows;
        if let Some(t) = self.file_tree.as_mut() {
            if t.selected >= n {
                t.selected = n.saturating_sub(1);
            }
        }
    }

    /// The rows shown in the sidebar. Empty filter → the browse tree (folders
    /// expand in place); a filter → a flat fuzzy shortlist over the index.
    fn compute_tree_rows(&self) -> Vec<TreeRow> {
        let Some(tree) = self.file_tree.as_ref() else { return Vec::new() };
        if !tree.filter.is_empty() {
            // Shortlist: fuzzy over the project index (relative paths).
            let mut scored: Vec<(i64, u32, String)> = self
                .project_index
                .as_ref()
                .map(|i| {
                    i.files
                        .iter()
                        .filter_map(|f| {
                            palette::fuzzy_score(&tree.filter, f)
                                .map(|s| (s, *self.file_frecency.get(f).unwrap_or(&0), f.clone()))
                        })
                        .collect()
                })
                .unwrap_or_default();
            scored.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
            return scored
                .into_iter()
                .take(300)
                .map(|(_, _, rel)| TreeRow {
                    path: tree.root.join(&rel),
                    label: rel,
                    depth: 0,
                    is_dir: false,
                    expanded: false,
                    updir: false,
                })
                .collect();
        }
        // Browse: `../` (if the root has a parent), then the expanded tree.
        let mut rows = Vec::new();
        if tree.root.parent().is_some() {
            rows.push(TreeRow {
                path: tree.root.clone(),
                label: "../".into(),
                depth: 0,
                is_dir: true,
                expanded: false,
                updir: true,
            });
        }
        self.push_dir_rows(&tree.root, 0, &tree.expanded, &mut rows);
        rows
    }

    /// Append a directory's entries (dirs first, alpha), recursing into expanded
    /// folders — the expand-in-place tree.
    fn push_dir_rows(
        &self,
        dir: &std::path::Path,
        depth: usize,
        expanded: &std::collections::HashSet<std::path::PathBuf>,
        rows: &mut Vec<TreeRow>,
    ) {
        for (name, is_dir) in self.read_dir_entries(dir) {
            let path = dir.join(&name);
            let is_expanded = is_dir && expanded.contains(&path);
            rows.push(TreeRow {
                path: path.clone(),
                label: name,
                depth,
                is_dir,
                expanded: is_expanded,
                updir: false,
            });
            if is_expanded {
                self.push_dir_rows(&path, depth + 1, expanded, rows);
            }
        }
    }

    /// One directory's entries (dotdirs + the ignore-list skipped), dirs first.
    fn read_dir_entries(&self, dir: &std::path::Path) -> Vec<(String, bool)> {
        let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
        let mut entries: Vec<(String, bool)> = rd
            .flatten()
            .filter_map(|e| {
                let name = e.file_name().to_string_lossy().to_string();
                if name.starts_with('.') || self.tuning.project_ignore.iter().any(|i| i == &name) {
                    return None;
                }
                let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
                Some((name, is_dir))
            })
            .collect();
        entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.to_lowercase().cmp(&b.0.to_lowercase())));
        entries
    }

    fn handle_tree(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let none = key.modifiers.is_empty();
        let shift = key.modifiers == KeyModifiers::SHIFT;
        let len = self.tree_rows.len();
        match key.code {
            KeyCode::Esc | KeyCode::Char('g') if key.code == KeyCode::Esc || ctrl => {
                // Esc / C-g: clear an active filter, else close the sidebar.
                let cleared = self.file_tree.as_mut().map(|t| {
                    if t.filter.is_empty() { false } else { t.filter.clear(); t.selected = 0; true }
                }).unwrap_or(false);
                if cleared { self.refresh_tree_rows(); }
                else { self.close_tree(); }
            }
            KeyCode::Up | KeyCode::BackTab => {
                if let Some(t) = self.file_tree.as_mut() { t.selected = t.selected.saturating_sub(1); }
            }
            KeyCode::Down => {
                if let Some(t) = self.file_tree.as_mut() {
                    if t.selected + 1 < len { t.selected += 1; }
                }
            }
            KeyCode::Char('p') if ctrl => {
                if let Some(t) = self.file_tree.as_mut() { t.selected = t.selected.saturating_sub(1); }
            }
            KeyCode::Char('n') if ctrl => {
                if let Some(t) = self.file_tree.as_mut() {
                    if t.selected + 1 < len { t.selected += 1; }
                }
            }
            KeyCode::Enter => self.tree_activate(true),  // open + focus editor
            KeyCode::Right => self.tree_activate(false), // expand / preview (stay in tree)
            KeyCode::Left => self.tree_collapse(),
            KeyCode::Backspace => {
                let changed = self.file_tree.as_mut().map(|t| {
                    if t.filter.is_empty() { false } else { t.filter.pop(); t.selected = 0; true }
                }).unwrap_or(false);
                if changed { self.refresh_tree_rows(); }
            }
            KeyCode::Char(c) if none || shift => {
                if let Some(t) = self.file_tree.as_mut() { t.filter.push(c); t.selected = 0; }
                self.refresh_tree_rows();
            }
            _ => {}
        }
    }

    /// Enter/→ on a row. Folders expand and `../` re-roots for both. For a file,
    /// `commit` (Enter) opens it and focuses the editor; a preview (→) shows it
    /// but keeps you in the tree, reversibly — arrow to another file to re-preview.
    fn tree_activate(&mut self, commit: bool) {
        let Some(row) = self.tree_rows.get(self.file_tree.as_ref().map(|t| t.selected).unwrap_or(0)) else { return };
        let (path, is_dir, updir) = (row.path.clone(), row.is_dir, row.updir);
        if updir {
            if let Some(parent) = path.parent().map(|p| p.to_path_buf()) {
                if let Some(t) = self.file_tree.as_mut() { t.root = parent; t.selected = 0; }
            }
            self.refresh_tree_rows();
        } else if is_dir {
            if let Some(t) = self.file_tree.as_mut() {
                if !t.expanded.remove(&path) { t.expanded.insert(path); }
            }
            self.refresh_tree_rows();
        } else {
            self.show_file_in_pane(&path, commit);
        }
    }

    /// ←: collapse an expanded folder, else jump selection to the parent row.
    fn tree_collapse(&mut self) {
        let sel = self.file_tree.as_ref().map(|t| t.selected).unwrap_or(0);
        let Some(row) = self.tree_rows.get(sel) else { return };
        if row.is_dir && row.expanded {
            let path = row.path.clone();
            if let Some(t) = self.file_tree.as_mut() { t.expanded.remove(&path); }
            self.refresh_tree_rows();
        } else if row.depth > 0 {
            let target_depth = row.depth - 1;
            let parent = self.tree_rows[..sel].iter().rposition(|r| r.depth == target_depth);
            if let (Some(idx), Some(t)) = (parent, self.file_tree.as_mut()) { t.selected = idx; }
        }
    }

    /// Show a tree file in the focused pane. `commit` (Enter) focuses the editor;
    /// otherwise (→) it's a preview and focus stays in the tree. Reuses an already
    /// open buffer so repeated previews don't pile up duplicates.
    fn show_file_in_pane(&mut self, path: &std::path::Path, commit: bool) {
        let existing = self
            .buffers
            .values()
            .find(|b| b.path.as_deref() == Some(path))
            .map(|b| b.id);
        // Keep a visible terminal by opening the file beside it.
        if matches!(self.focused_pane().content, PaneContent::Terminal(_))
            && self.tab().layout.count() < self.tuning.max_panes
        {
            self.split_vertical();
        }
        let buf = match existing {
            Some(id) => Ok(id),
            None => self.open_file(&path.to_string_lossy()),
        };
        match buf {
            Ok(buf_id) => {
                let pid = self.focused_pane_id();
                if let Some(pane) = self.panes.get_mut(&pid) {
                    pane.content = PaneContent::Editor(buf_id);
                    pane.cursor_row = 0; pane.cursor_col = 0; pane.scroll_row = 0;
                    pane.selection_anchor = None;
                }
                if commit {
                    self.mode = Mode::Edit; // focus the editor; sidebar stays open
                    let name = path.file_name().map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| path.to_string_lossy().to_string());
                    self.status_msg = Some(format!("Opened {name}"));
                }
            }
            Err(e) => self.status_msg = Some(format!("Can't open {}: {e}", path.display())),
        }
    }

    /// W3: send the shell-bar's English text to be turned into one command,
    /// which replaces the query when it returns (`ShellTranslation` event).
    fn translate_shell_query(&mut self) {
        let text = self.palette.as_ref().map(|p| p.query.clone()).unwrap_or_default();
        if text.trim().is_empty() {
            return;
        }
        let cfg = agent::AgentConfig::from_env();
        if !cfg.is_configured() {
            self.status_msg = Some("No API key — set GEMINI_API_KEY to translate".into());
            return;
        }
        self.agent_pending = true;
        self.translate_request = Some(text.clone()); // for the corrective-memory pair
        agent::translate_shell(cfg, text, self.screen_context(), self.agent_tx.clone());
    }

    /// Editing a ready translation invalidates it — log it as an "edited" outcome
    /// (once) so the accept/edit/reject split is measurable.
    fn on_translation_edited(&mut self) {
        if self.shell_ready {
            if let Some(id) = self.translate_call_id.take() {
                crate::llm_log::record_outcome(id, None, true, false);
            }
        }
    }

    /// Run `cmd` in a terminal pane: reuse one in this tab, else open one here.
    fn run_shell_command(&mut self, cmd: &str) {
        // Prefer an existing terminal pane in the current tab.
        let term_pane = self
            .tab()
            .layout
            .pane_ids()
            .into_iter()
            .find(|id| matches!(self.panes.get(id).map(|p| &p.content), Some(PaneContent::Terminal(_))));
        if let Some(pid) = term_pane {
            self.tab_mut().focused_pane = pid;
            self.mode = Mode::Terminal;
        } else {
            self.open_terminal();
        }
        if let PaneContent::Terminal(tid) = self.focused_pane().content {
            if let Some(t) = self.terms.get_mut(&tid) {
                t.send_bytes(cmd.as_bytes());
                t.send_bytes(b"\n");
            }
        }
    }

    /// W1/W2: open the Ask bar with a canned question and submit it at once —
    /// a zero-typing "explain / triage" gesture grounded in the live screen.
    fn ask_prefilled(&mut self, question: &str) {
        self.open_bar(BarMode::Ask);
        if let Some(p) = self.palette.as_mut() {
            p.query = question.to_string();
        }
        self.submit_agent_query();
    }

    /// Fire off the current Ask query to the LLM on a background thread —
    /// grounded in the live screen, with the conversation history attached.
    fn submit_agent_query(&mut self) {
        let question = self.palette.as_ref().map(|p| p.query.clone()).unwrap_or_default();
        if question.trim().is_empty() {
            return;
        }
        let mut cfg = agent::AgentConfig::from_env();
        cfg.max_tokens = self.tuning.agent_max_tokens;
        cfg.temperature = self.tuning.agent_temperature;
        if !cfg.is_configured() {
            self.agent_answer = Some(
                "⚠ No API key. Export GROQ_API_KEY, GEMINI_API_KEY, or MARS_LLM_KEY and retry."
                    .into(),
            );
            self.agent_directive = None;
            return;
        }
        self.agent_pending = true;
        self.agent_answer = None;
        self.agent_directive = None;
        self.refactor_replacement = None;
        self.last_question = question.clone();
        self.need_depth = 0;
        self.ask_scroll = 0; // snap to the newest turn
        let history = self.agent_history.clone();
        self.agent_history.push(("user".into(), question.clone()));
        if let Some(p) = self.palette.as_mut() {
            p.query.clear();
        }
        // Selection-aware: a live selection becomes precise context, and marks the
        // range a proposed refactor would replace ("translate this to French").
        // With no selection but the cursor in an editor, the target is an empty
        // range at point, so a reply's code block INSERTS there ("write a
        // limerick about potatoes").
        let mut context = self.screen_context();
        self.refactor_target = self.selection_range();
        if let Some(sel) = self.selected_text() {
            context.push_str(&sel);
        } else if let PaneContent::Editor(buf_id) = self.focused_pane().content {
            let (row, col) = {
                let p = self.focused_pane();
                (p.cursor_row, p.cursor_col)
            };
            let at = self.buffers[&buf_id].char_at(row, col);
            self.refactor_target = Some((buf_id, at, at));
            context.push_str(
                &crate::prompts::CURSOR_INSERT
                    .replace("{line}", &(row + 1).to_string())
                    .replace("{file}", &self.buffers[&buf_id].name),
            );
        }
        agent::ask(
            cfg,
            question,
            palette::registry_context(),
            context,
            history,
            self.agent_tx.clone(),
        );
    }

    /// Apply a confirm-gated refactor: replace the captured selection with the
    /// agent's code block, as ONE undo step (C-/ reverts the whole AI edit).
    pub fn apply_refactor(&mut self) {
        let (Some((buf_id, s, e)), Some(code)) =
            (self.refactor_target, self.refactor_replacement.take())
        else {
            return;
        };
        self.refactor_target = None;
        // Clamp both endpoints to the current buffer length — the range was
        // captured at query time and the buffer may have changed since.
        let len = self.buffers.get(&buf_id).map(|b| b.rope.len_chars()).unwrap_or(0);
        let (s, e) = (s.min(len), e.min(len));
        if let Some(buf) = self.buffers.get_mut(&buf_id) {
            buf.checkpoint(); // one reversible chunk
            buf.rope.remove(s..e);
            buf.rope.insert(s, &code);
            buf.modified = true;
        }
        let (r, c) = self.rowcol_of(buf_id, s + code.chars().count());
        self.close_bar();
        self.clear_selection();
        self.set_cursor(r, c);
        self.mode = Mode::Edit;
        self.status_msg = Some("Refactor applied — C-/ to undo".into());
    }

    /// W4/W5: replay the last question with an extra context source the model asked
    /// for via `NEED:`. One expansion per ask (capped in `tick`), never surfaced.
    fn reask_with_need(&mut self, kind: agent::NeedKind) {
        let mut cfg = agent::AgentConfig::from_env();
        cfg.max_tokens = self.tuning.agent_max_tokens;
        cfg.temperature = self.tuning.agent_temperature;
        if !cfg.is_configured() {
            self.agent_pending = false;
            return;
        }
        let extra = self.expand_context(&kind);
        let context = format!("{}\n\n### expanded ###\n{}", self.screen_context(), extra);
        let history = self.agent_history.clone();
        let q = self.last_question.clone();
        self.agent_pending = true; // keep the spinner; the re-ask is the same turn
        agent::ask(cfg, q, palette::registry_context(), context, history, self.agent_tx.clone());
    }

    /// Render the extra source a `NEED:` asked for (full scrollback, or another tab).
    fn expand_context(&self, kind: &agent::NeedKind) -> String {
        match kind {
            agent::NeedKind::Scrollback => {
                if let PaneContent::Terminal(id) = self.focused_pane().content {
                    if let Some(t) = self.terms.get(&id) {
                        let cap = self.tuning.terminal_scrollback_lines.min(2000);
                        return format!("FULL TERMINAL SCROLLBACK:\n{}", t.history_tail(cap));
                    }
                }
                String::new()
            }
            agent::NeedKind::Tab(name) => {
                let low = name.to_lowercase();
                let Some(tab) = self.tabs.iter().find(|t| t.name.to_lowercase().contains(&low)) else {
                    return format!("(no tab matching '{name}')");
                };
                let mut out = format!("TAB {}:\n", tab.name);
                for pid in tab.layout.pane_ids() {
                    let Some(p) = self.panes.get(&pid) else { continue };
                    match p.content {
                        PaneContent::Terminal(tid) => {
                            if let Some(t) = self.terms.get(&tid) {
                                out.push_str(t.screen().contents().trim_end());
                                out.push('\n');
                            }
                        }
                        PaneContent::Editor(bid) => {
                            if let Some(b) = self.buffers.get(&bid) {
                                out.push_str(&format!("[{}]\n", b.name));
                                for line in b.rope.to_string().lines().take(120) {
                                    out.push_str(line);
                                    out.push('\n');
                                }
                            }
                        }
                    }
                }
                out
            }
        }
    }

    /// The highlighted code as a labeled context block, telling the model that a
    /// refactor request should reply with ONLY the replacement in a ``` block.
    fn selected_text(&self) -> Option<String> {
        let (buf_id, s, e) = self.selection_range()?;
        let buf = self.buffers.get(&buf_id)?;
        let text = buf.rope.slice(s..e).to_string();
        let (sr, _) = self.rowcol_of(buf_id, s);
        let (er, _) = self.rowcol_of(buf_id, e);
        Some(format!(
            "\n\nSELECTED CODE — {} lines {}-{} (the user has this highlighted). If they ask \
             to refactor/rewrite/fix/simplify it, reply with ONLY the replacement inside one \
             ``` code block and no prose:\n```\n{}\n```\n",
            buf.name,
            sr + 1,
            er + 1,
            text
        ))
    }

    /// The context-bus slice: what the user is looking at, as text the model
    /// can ground its answers in. Capped so huge buffers can't blow the prompt.
    fn screen_context(&self) -> String {
        const CAP: usize = 6 * 1024;
        let mut out = String::new();
        if let Some(s) = &self.session_name {
            out.push_str(&format!("session: {s}\n"));
        }
        let tab_names: Vec<String> = self
            .tabs
            .iter()
            .enumerate()
            .map(|(i, t)| {
                if i == self.active_tab { format!("[{}]", t.name) } else { t.name.clone() }
            })
            .collect();
        out.push_str(&format!("tabs: {}\n", tab_names.join(" ")));

        let focused = self.focused_pane_id();
        for pid in self.tab().layout.pane_ids() {
            let Some(pane) = self.panes.get(&pid) else { continue };
            let marker = if pid == focused { " (focused)" } else { "" };
            match pane.content {
                PaneContent::Editor(buf_id) => {
                    if let Some(buf) = self.buffers.get(&buf_id) {
                        out.push_str(&format!(
                            "\n--- editor pane: {}{marker}, cursor at line {} ---\n",
                            buf.name,
                            pane.cursor_row + 1
                        ));
                        // The visible window plus a little margin.
                        let from = pane.scroll_row;
                        let to = (from + pane.view_h.max(20) + 10).min(buf.line_count());
                        for row in from..to {
                            out.push_str(&buf.line_str(row));
                            out.push('\n');
                        }
                    }
                }
                PaneContent::Terminal(tid) => {
                    if let Some(t) = self.terms.get(&tid) {
                        out.push_str(&format!("\n--- terminal pane{marker} ---\n"));
                        out.push_str(t.screen().contents().trim_end());
                        out.push('\n');
                    }
                }
            }
            if out.len() > CAP {
                break;
            }
        }
        if out.len() > CAP {
            // Keep the head (layout) and the tail (most recent output).
            let head: String = out.chars().take(CAP / 3).collect();
            let tail: String = out
                .chars()
                .rev()
                .take(2 * CAP / 3)
                .collect::<String>()
                .chars()
                .rev()
                .collect();
            out = format!("{head}\n…(truncated)…\n{tail}");
        }
        out
    }

    /// Dispatch a palette ItemKind.
    fn activate_kind(&mut self, kind: Option<ItemKind>) {
        match kind {
            Some(ItemKind::Submenu(name)) => {
                if let Some(p) = self.palette.as_mut() {
                    p.push(name);
                }
            }
            Some(ItemKind::Run(action)) => {
                self.palette = None;
                self.mode = self.bar_return.clone();
                self.run_action_from_bar(action);
            }
            None => {}
        }
    }

    /// Run an action chosen in the bar, and — once it's clearly a habit —
    /// nudge toward its direct keybinding (subtle, one status line, never blocks).
    fn run_action_from_bar(&mut self, action: Action) {
        let key = format!("{:?}", action);
        let uses = self.bar_uses.entry(key).or_insert(0);
        *uses += 1;
        let nudge = if *uses >= self.tuning.nudge_threshold {
            self.keys
                .binding_for(&action)
                .map(|b| format!("💡 next time: {}  ({})", b, action.label()))
        } else {
            None
        };
        self.run_action(action);
        if let Some(n) = nudge {
            self.status_msg = Some(n);
        }
    }

    /// Execute a palette action.
    pub fn run_action(&mut self, action: Action) {
        self.edit_run = EditRun::None; // a command breaks the typing/backspace undo run
        // Track frecency
        let key = format!("{:?}", action);
        *self.frecency.entry(key).or_insert(0) += 1;

        // Any action other than yank/yank-pop breaks the M-y chain.
        if !matches!(action, Action::Yank | Action::YankPop) {
            self.last_yank = None;
        }

        match action {
            Action::SplitHorizontal    => self.split_horizontal(),
            Action::SplitVertical      => self.split_vertical(),
            Action::ClosePane          => self.close_pane(),
            Action::DeleteOtherWindows => self.delete_other_windows(),
            Action::NextPane           => self.focus_next_pane(),
            Action::PrevPane           => self.focus_prev_pane(),
            Action::SwapPane           => self.swap_pane(),
            Action::ZoomPane           => self.toggle_zoom(),
            Action::NewTab             => self.new_tab(),
            Action::CloseTab           => self.close_tab(),
            Action::NextTab            => self.next_tab(),
            Action::PrevTab            => self.prev_tab(),
            Action::MoveTabLeft        => self.move_tab(-1),
            Action::MoveTabRight       => self.move_tab(1),
            Action::RenameTab          => {
                let current = self.tab().name.clone();
                self.start_prompt_with(PromptKind::RenameTab, "Rename tab: ", &current);
            }
            Action::RenamePane         => {
                let current = self.focused_pane().title.clone().unwrap_or_default();
                self.start_prompt_with(PromptKind::RenamePane, "Rename pane: ", &current);
            }
            Action::RenameSession      => {
                if self.session_name.is_some() {
                    let current = self.session_name.clone().unwrap_or_default();
                    self.start_prompt_with(PromptKind::RenameSession, "Rename session: ", &current);
                } else {
                    self.status_msg =
                        Some("Not in a session — start one with: mars new <name>".into());
                }
            }
            Action::TabMode            => self.mode = Mode::Tab,
            Action::Save               => self.do_save(),
            Action::ToggleFileTree     => self.toggle_file_tree(),
            Action::RefreshIndex       => {
                self.project_index = None;
                self.ensure_project_index();
                if self.tree_open { self.refresh_tree_rows(); }
                self.status_msg = Some("File index refreshed".into());
            }
            Action::RestoreKeybindings => {
                match config::reset_keys() {
                    Ok(_) => {
                        self.keys = config::load(); // apply immediately, no restart
                        self.status_msg = Some("Default keybindings restored (old file → keys.json.bak)".into());
                    }
                    Err(e) => self.status_msg = Some(format!("Reset failed: {e}")),
                }
            }
            Action::KillBuffer         => self.kill_buffer(),
            Action::Undo               => self.do_undo(),
            Action::Redo               => self.do_redo(),
            Action::UndoMode           => self.enter_undo_mode(),
            Action::KillLine           => self.kill_line(),
            Action::KillRegion         => self.kill_region(),
            Action::CopyRegion         => self.copy_region(),
            Action::Yank               => self.yank(),
            Action::YankPop            => self.yank_pop(),
            Action::Paste              => self.paste_clipboard(),
            Action::KillWordForward    => self.kill_word(true),
            Action::KillWordBackward   => self.kill_word(false),
            Action::SelectAll          => self.select_all(),
            Action::GoTop              => self.move_file_start(),
            Action::GoBottom           => self.move_file_end(),
            Action::GotoLine           => self.start_prompt(PromptKind::GotoLine, "Go to line: "),
            Action::JumpBlockPrev      => self.jump_block(false),
            Action::JumpBlockNext      => self.jump_block(true),
            Action::JumpSymbolPrev     => self.jump_symbol(false),
            Action::JumpSymbolNext     => self.jump_symbol(true),
            Action::MatchBracket       => self.match_bracket(),
            Action::Recenter           => self.recenter(),
            Action::Search             => self.start_isearch(),
            Action::QueryReplace       => self.start_prompt(PromptKind::ReplaceFrom, "Query replace: "),
            Action::OpenTerminal       => self.open_terminal(),
            Action::AskAgent           => self.open_bar(BarMode::Ask),
            Action::ExplainThis        => self.ask_prefilled(crate::prompts::EXPLAIN_THIS.trim_end()),
            Action::ExplainFailure     => self.ask_prefilled(crate::prompts::EXPLAIN_FAILURE.trim_end()),
            Action::WatchPane          => self.toggle_watch_pane(),
            Action::ExpandNotices      => self.expand_notices(),
            Action::AwayDigest         => self.show_away_digest(),
            Action::Detach             => {
                if self.session_name.is_some() {
                    self.detach_requested = true;
                } else {
                    self.status_msg =
                        Some("Not in a session — start one with: mars --session <name>".into());
                }
            }
            Action::OpenCommandMemory  => self.open_command_memory(),
            Action::ClearCommandMemory => self.clear_command_memory(),
            Action::OpenDenylist       => self.open_denylist(),
            // Quit = detach (2026-07 ruling): leaving mars never ends a
            // session — kill is the deleting verb (KillSession here, `mars
            // kill`/`mars killall` outside). Standalone has nothing to keep
            // running, so Quit still exits there (dirty-guarded).
            Action::Quit               => {
                if self.session_name.is_some() {
                    self.detach_requested = true;
                } else {
                    self.request_quit();
                }
            }
            Action::KillSession        => self.request_quit(),
        }
    }

    // ── Memory management ────────────────────────────────────────────────────
    // The stores are plain local files, so "manage memory" is "edit a buffer":
    // ownership means the user can read, edit, and delete what the agent knows.

    fn open_command_memory(&mut self) {
        match crate::retrieval::command_memory_path() {
            Some(p) if p.exists() => {
                let path = p.to_string_lossy().into_owned();
                if let Err(e) = self.open_file(&path) {
                    self.status_msg = Some(format!("couldn't open {path}: {e}"));
                }
            }
            _ => {
                self.status_msg =
                    Some("no command memory yet — accept a translated command first".into());
            }
        }
    }

    fn clear_command_memory(&mut self) {
        let n = crate::retrieval::load_command_records().len();
        if n == 0 {
            self.status_msg = Some("command memory is already empty".into());
            return;
        }
        if !self.close_confirmed {
            self.start_prompt(
                PromptKind::ConfirmAction(Action::ClearCommandMemory),
                &format!("Forget all {n} remembered command(s)?  y forget · n cancel "),
            );
            return;
        }
        if let Some(p) = crate::retrieval::command_memory_path() {
            let _ = std::fs::write(&p, "");
        }
        self.status_msg = Some(format!("forgot {n} remembered command(s)"));
    }

    fn open_denylist(&mut self) {
        let Some(p) = crate::retrieval::denylist_path() else {
            self.status_msg = Some("no HOME — can't locate ~/.mars/denylist".into());
            return;
        };
        if !p.exists() {
            if let Some(dir) = p.parent() {
                let _ = std::fs::create_dir_all(dir);
            }
            let _ = std::fs::write(
                &p,
                "# One entry per line. Any line's text appearing in command memory or\n\
                 # shell history is replaced with [REDACTED] before entering an LLM prompt.\n",
            );
        }
        let path = p.to_string_lossy().into_owned();
        if let Err(e) = self.open_file(&path) {
            self.status_msg = Some(format!("couldn't open {path}: {e}"));
        }
    }

    // ── Terminal pane ────────────────────────────────────────────────────────

    pub fn open_terminal(&mut self) {
        // If this pane is already a terminal, just re-attach.
        if let PaneContent::Terminal(_) = self.focused_pane().content {
            self.mode = Mode::Terminal;
            return;
        }
        let id = self.next_term_id;
        self.next_term_id += 1;
        let (rows, cols) = (self.tuning.terminal_default_rows, self.tuning.terminal_default_cols);
        let scrollback = self.tuning.terminal_scrollback_lines;
        // The first opened file's dir if any, else where `mars` was launched —
        // never portable-pty's default (which lands the shell at /).
        let cwd = self.startup_cwd.clone().or_else(|| self.run_cwd.clone());
        match terminal::spawn(id, rows, cols, scrollback, cwd, self.session_name.as_deref(), self.term_tx.clone()) {
            Ok(term) => {
                self.terms.insert(id, term);
                let pid = self.focused_pane_id();
                if let Some(p) = self.panes.get_mut(&pid) {
                    p.content = PaneContent::Terminal(id);
                }
                self.mode = Mode::Terminal;
                self.status_msg = Some("Terminal — Ctrl+g back to editor".into());
            }
            Err(e) => {
                self.status_msg = Some(format!("Terminal failed: {}", e));
            }
        }
    }

    /// The mode a pane's content wants when it has focus.
    fn mode_for_focused_pane(&self) -> Mode {
        match self.focused_pane().content {
            PaneContent::Terminal(_) => Mode::Terminal,
            PaneContent::Editor(_) => Mode::Edit,
        }
    }

    /// Chrome layer: navigation chords are global — they mean the same thing
    /// inside a terminal pane as in the editor. Editing chords (C-k, C-c,
    /// C-x…) are NOT intercepted; they keep their shell meanings.
    fn is_chrome_action(a: &Action) -> bool {
        matches!(
            a,
            Action::NextPane | Action::PrevPane | Action::SwapPane
                | Action::NextTab | Action::PrevTab | Action::MoveTabLeft
                | Action::MoveTabRight | Action::NewTab | Action::TabMode
                | Action::SplitHorizontal | Action::SplitVertical
        )
    }

    fn handle_terminal(&mut self, key: KeyEvent) {
        // Ctrl+Space from a terminal opens the unified composer, one keystroke: a
        // red inline overlay anchored at the cursor (type in place, the terminal
        // stays visible) AND a ↑/↓ menu of matching Mars commands above the bar.
        // Enter runs a picked command; with no match it's a shell command
        // (LLM-translated + confirmed). `!` forces pure-shell; `?` asks the agent.
        let chord = chord_of(&key);
        if self.keys.bar_open.contains(&chord) || matches!(key.code, KeyCode::Null) {
            self.open_bar(BarMode::Command);
            return;
        }
        // Ctrl+g detaches back to the editor.
        if key.modifiers.contains(KeyModifiers::CONTROL) {
            if let KeyCode::Char('g') = key.code {
                self.mode = Mode::Edit;
                return;
            }
        }
        // A proactive notice is up: Esc dismisses it here (one keypress budget)
        // rather than leaking 0x1b to the shell — so the notice's "Esc dismiss"
        // hint is honest even when it renders over a focused terminal pane.
        if matches!(key.code, KeyCode::Esc) && !self.notices.is_empty() {
            self.dismiss_notice();
            return;
        }
        // Global chrome chords (single-chord only — prefixes belong to the shell).
        if let Some(action) = self.keys.lookup(std::slice::from_ref(&chord)) {
            if Self::is_chrome_action(&action) {
                self.run_action(action);
                // Follow the (possibly new) focused pane — unless the action
                // opened a transient mode of its own (travel mode).
                if !matches!(self.mode, Mode::Tab | Mode::Bar) {
                    self.mode = self.mode_for_focused_pane();
                }
                return;
            }
        }
        // Chrome primitives: M-1..9 tab jump, M-/Ctrl+arrows pane focus.
        let alt  = key.modifiers.contains(KeyModifiers::ALT);
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Char(c) if alt && c.is_ascii_digit() => {
                self.goto_tab((c as u8 - b'0') as usize);
                self.mode = self.mode_for_focused_pane();
                return;
            }
            KeyCode::Left if alt || ctrl => {
                self.focus_direction(-1, 0);
                self.mode = self.mode_for_focused_pane();
                return;
            }
            KeyCode::Right if alt || ctrl => {
                self.focus_direction(1, 0);
                self.mode = self.mode_for_focused_pane();
                return;
            }
            KeyCode::Up if alt || ctrl => {
                self.focus_direction(0, -1);
                self.mode = self.mode_for_focused_pane();
                return;
            }
            KeyCode::Down if alt || ctrl => {
                self.focus_direction(0, 1);
                self.mode = self.mode_for_focused_pane();
                return;
            }
            _ => {}
        }
        let term_id = match self.focused_pane().content {
            PaneContent::Terminal(id) => id,
            _ => {
                self.mode = Mode::Edit;
                return;
            }
        };

        // Dead shell: the pane only waits to be dismissed.
        if self.terms.get(&term_id).map(|t| t.exited).unwrap_or(false) {
            if matches!(key.code, KeyCode::Enter | KeyCode::Char('q')) {
                self.close_terminal_pane(term_id);
            }
            return;
        }

        // Scrollback view: Shift+PageUp/PageDown page through history.
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        if shift && matches!(key.code, KeyCode::PageUp | KeyCode::PageDown) {
            let page = self.focused_pane().view_h.max(2) as i64 - 1;
            let delta = if key.code == KeyCode::PageUp { page } else { -page };
            if let Some(t) = self.terms.get_mut(&term_id) {
                t.scroll_view(delta);
            }
            return;
        }

        let bytes = key_to_bytes(&key);
        if !bytes.is_empty() {
            if let Some(t) = self.terms.get_mut(&term_id) {
                t.scroll_to_live(); // typing snaps out of scrollback
                t.send_bytes(&bytes);
            }
        }
    }

    /// Dismiss an exited terminal: close the pane, or recycle the last pane
    /// back into an editor showing a scratch/existing buffer.
    fn close_terminal_pane(&mut self, term_id: TermId) {
        self.terms.remove(&term_id);
        if self.tab().layout.count() > 1 {
            self.close_pane();
        } else {
            let buf = match self.buffers.keys().next().copied() {
                Some(b) => b,
                None => self.new_scratch(),
            };
            let pid = self.focused_pane_id();
            if let Some(p) = self.panes.get_mut(&pid) {
                p.content = PaneContent::Editor(buf);
                p.cursor_row = 0;
                p.cursor_col = 0;
                p.scroll_row = 0;
            }
        }
        self.mode = self.mode_for_focused_pane();
    }

    // ── Main loop ────────────────────────────────────────────────────────────

    /// One housekeeping tick: animation counter + PTY/agent event drains.
    /// Called every loop iteration whether or not a client is attached.
    pub fn tick(&mut self) {
        self.frame_tick = self.frame_tick.wrapping_add(1);

        // Drain terminal signals (repaint next frame); mark dead shells and feed
        // the watch clock (W6: output resets quiet, exit queues a verdict).
        let now = self.frame_tick;
        while let Ok(ev) = self.term_rx.try_recv() {
            self.needs_redraw = true; // terminal content moved → repaint
            match ev {
                TermEvent::Output(id) => {
                    if let Some(w) = self.watches.get_mut(&id) {
                        // A fresh run begins when output resumes after a quiet/fired
                        // gap (or on the very first output) — stamp its start.
                        if w.triggered || w.run_started_tick == 0 {
                            w.run_started_tick = now;
                        }
                        w.last_output_tick = now;
                        w.triggered = false;
                    }
                }
                TermEvent::Exited(id) => {
                    if let Some(t) = self.terms.get_mut(&id) {
                        t.exited = true;
                    }
                    let watched = self.watches.get(&id).map(|w| w.watched && !w.triggered).unwrap_or(false);
                    if watched {
                        self.pending_watch = Some((id, WatchReason::Exit)); // gets an LLM verdict
                    } else {
                        // An unwatched shell ending is a deterministic away-event.
                        self.push_away(AwayKind::Done, "shell exited".into(), None);
                    }
                }
            }
        }

        // Silent autosave of modified, path-backed buffers.
        let secs = self.tuning.autosave_secs;
        if secs > 0 {
            let ticks_per_save = (secs * 1000 / self.tuning.poll_interval_ms.max(1)).max(1);
            if self.frame_tick % ticks_per_save == 0 {
                self.autosave();
            }
        }

        // Drain background LLM-agent events.
        let mut events = Vec::new();
        while let Ok(ev) = self.agent_rx.try_recv() {
            events.push(ev);
        }
        if !events.is_empty() {
            self.needs_redraw = true; // an answer / verdict / rename landed
        }
        for ev in events {
            match ev {
                AgentEvent::Answer { text, directive } => {
                    // W4/W5: a NEED: request re-asks once with the extra source and
                    // is never surfaced (no history push, spinner keeps spinning).
                    if let Some(agent::AgentDirective::Need(kind)) = &directive {
                        if self.need_depth < 1 {
                            self.need_depth += 1;
                            self.reask_with_need(kind.clone());
                            continue;
                        }
                    }
                    self.agent_pending = false;
                    self.agent_partial = None;
                    // If the query targeted a selection and the reply carries a code
                    // block, offer it as a confirm-gated replacement (a refactor).
                    if self.refactor_target.is_some() {
                        self.refactor_replacement = extract_code_block(&text);
                    }
                    self.agent_history.push(("assistant".into(), text));
                    self.agent_directive = directive;
                    self.ask_scroll = 0; // show the new turn
                }
                AgentEvent::AnswerStart => {
                    self.agent_partial = Some(String::new());
                }
                AgentEvent::AnswerDelta { text } => {
                    self.agent_partial.get_or_insert_with(String::new).push_str(&text);
                }
                AgentEvent::AutoName { tab_id, name } => {
                    self.bg_busy = false;
                    // Apply only if the tab still wears its default numeric
                    // name — a user rename always wins the race.
                    if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == tab_id) {
                        if tab.name.chars().all(|c| c.is_ascii_digit()) {
                            tab.name = name;
                        }
                    }
                }
                AgentEvent::SessionName { name } => {
                    self.bg_busy = false;
                    // Rename only if still numeric (user/explicit names win).
                    let numeric = self
                        .session_name
                        .as_ref()
                        .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
                        .unwrap_or(false);
                    if numeric {
                        self.rename_session_to = Some(name);
                    }
                }
                AgentEvent::ShellTranslation { command, call_id } => {
                    self.agent_pending = false;
                    // Only meaningful if still composing a shell command.
                    let is_shell = self
                        .palette
                        .as_ref()
                        .map(|p| p.bar_mode == BarMode::Shell)
                        .unwrap_or(false);
                    if is_shell {
                        if let Some(p) = self.palette.as_mut() {
                            p.query = command;
                        }
                        self.shell_ready = true; // Enter now runs the translated command
                        self.translate_call_id = Some(call_id); // correlate the outcome
                        self.agent_answer = None; // clear any prior error
                    }
                }
                AgentEvent::Error(e) => {
                    self.agent_pending = false;
                    self.agent_partial = None;
                    self.bg_busy = false;
                    self.agent_answer = Some(format!("{}", e));
                    self.agent_directive = None;
                }
                AgentEvent::BgDone => {
                    self.bg_busy = false;
                }
                AgentEvent::WatchSummary { term_id, verdict } => {
                    self.bg_busy = false;
                    let failed = verdict.to_lowercase().contains("fail")
                        || verdict.to_lowercase().contains("error");
                    let tab = self.tab_label_of_term(term_id);
                    let dur = self.watches.get(&term_id).and_then(|w| {
                        (w.run_started_tick > 0).then(|| now.saturating_sub(w.run_started_tick))
                    });
                    if let Some(w) = self.watches.get_mut(&term_id) {
                        w.verdict = Some(verdict.clone());
                    }
                    self.notices.push(Notice {
                        text: format!("{verdict}{tab}"),
                        kind: if failed { NoticeKind::Failure } else { NoticeKind::Info },
                    });
                    // Failures surface first.
                    self.notices.sort_by(|a, b| a.kind.cmp(&b.kind));
                    // Also record it for the Away Digest (with the run's duration).
                    self.push_away(
                        if failed { AwayKind::NeedsYou } else { AwayKind::Done },
                        format!("{verdict}{tab}"),
                        dur,
                    );
                    // And into the work journal — the persistent stream of
                    // what-was-happening snapshots (mission inference, mars ls).
                    let ts = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs())
                        .unwrap_or(0);
                    crate::worklog::record(&crate::worklog::WorkEntry {
                        ts,
                        session: self.session_label(),
                        tab: tab.trim_start_matches(" · ").trim().to_string(),
                        verdict: verdict.clone(),
                        failed,
                        dur_secs: dur.map(|t| t * self.tuning.poll_interval_ms / 1000),
                    });
                    self.maybe_infer_mission(ts);
                }
                AgentEvent::Mission { text } => {
                    self.bg_busy = false;
                    let ts = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs())
                        .unwrap_or(0);
                    crate::worklog::save_mission(&self.session_label(), &text, ts);
                }
            }
        }

        self.maybe_auto_name();
        self.maybe_auto_name_session();
        self.maybe_fire_watches();

        // Timer-driven surfaces that animate without input: the agent spinner
        // (every frame while thinking) and the which-key panel (appears a few
        // ticks after a prefix is held). Redraw while either is live; otherwise
        // an idle screen stays quiet — no draw, no flush, silent link.
        if self.agent_pending || !self.pending_prefix.is_empty() {
            self.needs_redraw = true;
        }
    }

    /// Append an event to the bounded away-log ring (the Away Digest source).
    fn push_away(&mut self, kind: AwayKind, text: String, dur_ticks: Option<u64>) {
        self.away_log.push(AwayEvent {
            tick: self.frame_tick,
            kind,
            text,
            dur_ticks,
        });
        const CAP: usize = 200;
        if self.away_log.len() > CAP {
            let drop = self.away_log.len() - CAP;
            self.away_log.drain(0..drop);
        }
    }

    /// Human duration from a tick span ("45s" / "4m12s" / "3h02m").
    fn fmt_dur(&self, ticks: u64) -> String {
        let secs = ticks * self.tuning.poll_interval_ms.max(1) / 1000;
        if secs < 60 {
            format!("{secs}s")
        } else if secs < 3600 {
            format!("{}m{:02}s", secs / 60, secs % 60)
        } else {
            format!("{}h{:02}m", secs / 3600, (secs % 3600) / 60)
        }
    }

    /// Toggle watching the focused terminal pane (W6).
    fn toggle_watch_pane(&mut self) {
        let PaneContent::Terminal(id) = self.focused_pane().content else {
            self.status_msg = Some("Watch works on a terminal pane".into());
            return;
        };
        let now = self.frame_tick;
        let w = self.watches.entry(id).or_default();
        w.watched = !w.watched;
        w.last_output_tick = now;
        w.triggered = false;
        let watching = w.watched;
        self.status_msg = Some(if watching {
            if agent::AgentConfig::from_env().is_configured() {
                "Watching this pane — I'll summarize it when it quiets (~20s) or exits".into()
            } else {
                "Watching — but set GROQ_API_KEY/GEMINI_API_KEY for the AI summary".into()
            }
        } else {
            "Stopped watching this pane".into()
        });
    }

    /// Capture a cheap snapshot when the last client detaches; the away_log carries
    /// events, the snapshot only what isn't event-shaped (which buffers were dirty).
    pub fn on_detach(&mut self) {
        self.detach_tick = Some(self.frame_tick);
        self.detach_snapshot = Some(Snapshot {
            dirty: self.buffers.values().filter(|b| b.modified).map(|b| b.name.clone()).collect(),
        });
    }

    /// W7 → Away Digest: on reattach, summarize everything logged since detach as
    /// one duration-anchored headline (failures first); `↵` opens the full digest.
    /// Deterministic — verdict text is the only LLM-derived part, and it was
    /// produced earlier through the normal `watch_summary` seam (broker-proxied in
    /// the future); a keyless box still gets the full digest. Quiet when idle.
    pub fn on_attach(&mut self) {
        let Some(snap) = self.detach_snapshot.take() else { return };
        let from = self.detach_tick.take().unwrap_or(0);
        // Fold file changes since detach into the log as Context events, so the
        // digest owns the whole story (names, not just a count).
        let dirty: Vec<String> = self
            .buffers
            .values()
            .filter(|b| b.modified && !snap.dirty.contains(&b.name))
            .map(|b| b.name.clone())
            .collect();
        if !dirty.is_empty() {
            let text = format!(
                "{} file{} modified ({})",
                dirty.len(),
                if dirty.len() == 1 { "" } else { "s" },
                dirty.join(", ")
            );
            self.push_away(AwayKind::Context, text, None);
        }
        // Reattach briefing: mission + the last few work-journal snapshots as
        // an assistant turn — "where was I?" is answerable the moment the ask
        // panel opens, and the context rides along with follow-up questions
        // (build_messages sends the recent turns). Deterministic; no LLM call.
        let session = self.session_label();
        let mission = crate::worklog::load_mission(&session);
        let recent = crate::worklog::recent(&session, 5);
        if mission.is_some() || !recent.is_empty() {
            let mut brief = String::from("Where you left off\n");
            if let Some((m, _)) = &mission {
                brief.push_str(&format!("  mission: {m}\n"));
            }
            for e in &recent {
                let mark = if e.failed { "" } else { "" };
                brief.push_str(&format!(
                    "  {mark} {} [{}] {}\n",
                    crate::broker::ago(e.ts),
                    e.tab,
                    e.verdict
                ));
            }
            self.agent_history.push(("assistant".into(), brief));
        }
        // Headline items from the away window: failures lead, then the rest.
        let events: Vec<&AwayEvent> = self.away_log.iter().filter(|e| e.tick >= from).collect();
        let mut items: Vec<String> = Vec::new();
        let mut failed = false;
        for e in events.iter().filter(|e| e.kind == AwayKind::NeedsYou) {
            items.push(format!("{}", e.text));
            failed = true;
        }
        let done = events.iter().filter(|e| e.kind == AwayKind::Done).count();
        for e in events.iter().filter(|e| e.kind == AwayKind::Done).take(2) {
            items.push(format!("{}", e.text));
        }
        if done > 2 {
            items.push(format!("+{} more done", done - 2));
        }
        for e in events.iter().filter(|e| e.kind == AwayKind::Context) {
            items.push(e.text.clone());
        }
        if items.is_empty() {
            return; // nothing happened — no briefing
        }
        // The headline subsumes watch notices queued while detached — drop the
        // duplicates so reattach greets with ONE line, not a stack.
        self.notices.retain(|n| !events.iter().any(|e| n.text == e.text));
        self.digest_from_tick = Some(from); // the "away digest" action re-summons details
        let away = self.fmt_dur(self.frame_tick.saturating_sub(from));
        // Honesty invariant, situated: the digest hint shows the live binding —
        // but reattach usually lands in a terminal pane, where a prefix chord
        // like C-x g goes to the shell, not Mars. So prefix it with the
        // leave-terminal step (C-g) whenever the focus is a terminal.
        let in_term = matches!(self.focused_pane().content, PaneContent::Terminal(_));
        let hint = match self.keys.binding_for(&Action::AwayDigest) {
            Some(b) if in_term => format!(" · C-g then {b} · digest"),
            Some(b) => format!(" · {b} digest"),
            None => String::new(),
        };
        self.notices.push(Notice {
            text: format!("while away {away}{}{hint}", items.join(" · ")),
            kind: if failed { NoticeKind::Failure } else { NoticeKind::Info },
        });
        self.notices.sort_by(|a, b| a.kind.cmp(&b.kind));
    }

    /// Render the Away Digest (events since the last detach window — or the whole
    /// log if never detached) into the ask transcript: sectioned, timestamped
    /// relative ("12m ago"), scrollable, re-summonable. Fully deterministic.
    fn show_away_digest(&mut self) {
        let from = self.digest_from_tick.unwrap_or(0);
        let events: Vec<AwayEvent> =
            self.away_log.iter().filter(|e| e.tick >= from).cloned().collect();
        if events.is_empty() {
            self.status_msg = Some("Away digest: nothing notable recorded".into());
            return;
        }
        let now = self.frame_tick;
        let mut out = String::from("While you were away\n");
        for (kind, title) in [
            (AwayKind::NeedsYou, "✗ needs you"),
            (AwayKind::Done, "✓ done"),
            (AwayKind::Context, "· context"),
        ] {
            let section: Vec<&AwayEvent> = events.iter().filter(|e| e.kind == kind).collect();
            if section.is_empty() {
                continue;
            }
            out.push_str(&format!("\n{title}\n"));
            for e in section {
                let ago = self.fmt_dur(now.saturating_sub(e.tick));
                let dur = e
                    .dur_ticks
                    .map(|d| format!(", ran {}", self.fmt_dur(d)))
                    .unwrap_or_default();
                out.push_str(&format!("  {ago} ago — {}{dur}\n", e.text));
            }
        }
        self.agent_history.push(("assistant".into(), out));
        self.ask_scroll = 0;
        self.open_bar(BarMode::Ask);
    }

    fn session_label(&self) -> String {
        self.session_name.clone().unwrap_or_else(|| "standalone".to_string())
    }

    /// Debounced background mission inference: at most one per
    /// `mission_refresh_secs`, only with enough journal signal, never while
    /// another background task holds the gate.
    fn maybe_infer_mission(&mut self, now: u64) {
        let refresh = self.tuning.mission_refresh_secs;
        if refresh == 0 || self.bg_busy {
            return;
        }
        let session = self.session_label();
        if let Some((_, as_of)) = crate::worklog::load_mission(&session) {
            if now.saturating_sub(as_of) < refresh {
                return;
            }
        }
        let entries = crate::worklog::recent(&session, 15);
        if entries.len() < 2 {
            return;
        }
        let cfg = agent::AgentConfig::from_env();
        if !cfg.is_configured() {
            return;
        }
        let lines: Vec<String> = entries
            .iter()
            .map(|e| {
                let mark = if e.failed { "" } else { "" };
                format!("{} {} [{}] {}", mark, crate::broker::ago(e.ts), e.tab, e.verdict)
            })
            .collect();
        self.bg_busy = true;
        agent::infer_mission(cfg, lines, self.agent_tx.clone());
    }

    /// Expand every pending notice into one digest turn in the ask panel and
    /// clear the queue — the "read them all at once" alternative to Esc-ing
    /// through notices one by one.
    fn expand_notices(&mut self) {
        if self.notices.is_empty() {
            self.status_msg = Some("no pending notices".into());
            return;
        }
        let mut out = String::from("Pending notices\n");
        for n in &self.notices {
            let mark = if n.kind == NoticeKind::Failure { "" } else { "·" };
            out.push_str(&format!("  {mark} {}\n", n.text));
        }
        self.notices.clear();
        self.agent_history.push(("assistant".into(), out));
        self.ask_scroll = 0;
        self.open_bar(BarMode::Ask);
    }

    /// Dismiss the front (highest-priority) notice, if any. Returns true if one popped.
    pub fn dismiss_notice(&mut self) -> bool {
        if self.notices.is_empty() {
            false
        } else {
            self.notices.remove(0);
            true
        }
    }

    /// W6: summarize a watched terminal that just went quiet or exited. One global
    /// in-flight gate (`bg_busy`); a foreground ask always preempts. Runs inside the
    /// daemon's `tick`, so it fires even while detached.
    fn maybe_fire_watches(&mut self) {
        if self.bg_busy || self.agent_pending {
            return;
        }
        let quiet_ticks =
            self.tuning.watch_quiet_secs * 1000 / self.tuning.poll_interval_ms.max(1);
        let now = self.frame_tick;
        // Peek: is anything ready to fire? (don't consume the trigger yet.)
        let candidate = self.pending_watch.is_some()
            || self.watches.values().any(|w| {
                w.watched && !w.triggered && now.saturating_sub(w.last_output_tick) > quiet_ticks
            });
        if !candidate {
            return;
        }
        // Remote box, tunnel down (you're detached): HOLD every trigger — don't
        // consume it — so the verdict fires on reattach instead of being lost.
        let cfg = agent::AgentConfig::from_env();
        if cfg.provider == "broker" && !cfg.is_configured() {
            return;
        }
        // An exit trigger queued from term_rx wins; else the first quiet watched pane.
        let fire = self.pending_watch.take().or_else(|| {
            self.watches
                .iter()
                .find(|(_, w)| {
                    w.watched && !w.triggered && now.saturating_sub(w.last_output_tick) > quiet_ticks
                })
                .map(|(id, _)| (*id, WatchReason::Quiet))
        });
        let Some((id, reason)) = fire else { return };
        if let Some(w) = self.watches.get_mut(&id) {
            w.triggered = true;
        }
        if !cfg.is_configured() {
            return; // no key at all (not broker) — consumed, so we don't spin
        }
        let tail = self.terminal_tail(id, self.tuning.agent_scrollback_context);
        self.bg_busy = true;
        agent::watch_summary(cfg, id, reason, tail, self.agent_tx.clone());
    }

    /// The last `lines` of a terminal pane's visible screen, for a watch summary.
    fn terminal_tail(&self, id: TermId, lines: usize) -> String {
        let Some(t) = self.terms.get(&id) else { return String::new() };
        let contents = t.screen().contents();
        let rows: Vec<&str> = contents.lines().collect();
        let start = rows.len().saturating_sub(lines);
        rows[start..].join("\n")
    }

    /// A " · <tab>/<n panes>" locator suffix for a watched terminal's notice.
    fn tab_label_of_term(&self, id: TermId) -> String {
        for tab in &self.tabs {
            for pid in tab.layout.pane_ids() {
                if let Some(p) = self.panes.get(&pid) {
                    if matches!(p.content, PaneContent::Terminal(tid) if tid == id) {
                        return format!("  · {}", tab.name);
                    }
                }
            }
        }
        String::new()
    }

    /// One-shot AI naming of a still-numeric session (numbered → AI → explicit).
    fn maybe_auto_name_session(&mut self) {
        if self.session_name_attempted || self.tuning.auto_name_secs == 0 {
            return;
        }
        let numeric = self
            .session_name
            .as_ref()
            .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
            .unwrap_or(false);
        if !numeric {
            self.session_name_attempted = true; // explicitly named already
            return;
        }
        // Give it a little longer than tab-naming so there's real activity.
        let ticks = (self.tuning.auto_name_secs * 2 * 1000 / self.tuning.poll_interval_ms.max(1)).max(1);
        if self.frame_tick % ticks != 0 || self.bg_busy {
            return;
        }
        let cfg = agent::AgentConfig::from_env();
        if !cfg.is_configured() {
            return;
        }
        self.session_name_attempted = true;
        self.bg_busy = true;
        agent::name_session(cfg, self.screen_context(), self.agent_tx.clone());
    }

    /// With an agent configured, quietly name the active tab once it has
    /// content and is still called "1"/"2"/…. Manual renames opt a tab out.
    fn maybe_auto_name(&mut self) {
        let secs = self.tuning.auto_name_secs;
        if secs == 0 || self.bg_busy {
            return;
        }
        let ticks = (secs * 1000 / self.tuning.poll_interval_ms.max(1)).max(1);
        if self.frame_tick % ticks != 0 {
            return;
        }
        let tab = self.tab();
        let (tab_id, default_named) =
            (tab.id, tab.name.chars().all(|c| c.is_ascii_digit()));
        if !default_named || self.auto_name_attempted.contains(&tab_id) {
            return;
        }
        // Only bother once there's something to name.
        let has_content = self.tab().layout.pane_ids().iter().any(|pid| {
            match self.panes.get(pid).map(|p| &p.content) {
                Some(PaneContent::Editor(b)) => {
                    self.buffers.get(b).map(|b| b.rope.len_chars() > 40).unwrap_or(false)
                }
                Some(PaneContent::Terminal(_)) => true,
                None => false,
            }
        });
        if !has_content {
            return;
        }
        let cfg = agent::AgentConfig::from_env();
        if !cfg.is_configured() {
            return;
        }
        self.auto_name_attempted.insert(tab_id);
        self.bg_busy = true;
        agent::auto_name(cfg, tab_id, self.screen_context(), self.agent_tx.clone());
    }

    /// Apply one source-agnostic input event.
    pub fn apply_input(&mut self, ev: InputEvent) -> Result<()> {
        match ev {
            InputEvent::Key(key) => self.handle_key(key)?,
            InputEvent::Mouse(m) => self.handle_mouse(m),
            InputEvent::Paste(s) => self.paste_text(&s),
            InputEvent::Resize(_, _) => {} // session server rebuilds its viewport
        }
        Ok(())
    }

    /// Standalone main loop: draw, tick, and consume events from `events`
    /// (fed by a TTY-reader thread) until quit.
    pub fn run<W: io::Write>(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<W>>,
        events: &mpsc::Receiver<InputEvent>,
    ) -> Result<()> {
        loop {
            self.tick();
            // Only redraw (and flush) when something visible changed — an idle
            // screen must not stream no-op frames, especially over SSH.
            if self.needs_redraw {
                terminal.draw(|f| ui::render(f, self))?;
                self.needs_redraw = false;
            }

            match events.recv_timeout(Duration::from_millis(self.tuning.poll_interval_ms)) {
                Ok(first) => {
                    // Apply the first event, then drain whatever else queued.
                    self.apply_input(first)?;
                    while let Ok(ev) = events.try_recv() {
                        self.apply_input(ev)?;
                    }
                    self.needs_redraw = true; // input → repaint
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(mpsc::RecvTimeoutError::Disconnected) => break, // input source gone
            }

            if self.detach_requested {
                // Standalone has nothing to detach from; session servers use
                // their own loop and consume this flag before we get here.
                self.detach_requested = false;
                self.status_msg =
                    Some("Not in a session — start one with: mars --session <name>".into());
            }
            if self.should_quit {
                break;
            }
        }
        self.save_state();
        Ok(())
    }

    pub fn save_state_now(&self) {
        self.save_state();
    }

    // ── Mouse ────────────────────────────────────────────────────────────────

    /// Click focuses a pane (and positions the cursor); wheel scrolls.
    /// Only active in Edit/Terminal — the bar and prompts own the keyboard.
    pub fn handle_mouse(&mut self, m: MouseEvent) {
        // The ask transcript scrolls under the wheel too (same as the Up/Down
        // keys), so reviewing past turns doesn't require leaving the mouse.
        if matches!(self.mode, Mode::Bar)
            && matches!(self.palette.as_ref().map(|p| &p.bar_mode), Some(BarMode::Ask))
        {
            match m.kind {
                MouseEventKind::ScrollUp => {
                    self.ask_scroll = self.ask_scroll.saturating_add(self.tuning.wheel_scroll_lines);
                }
                MouseEventKind::ScrollDown => {
                    self.ask_scroll = self.ask_scroll.saturating_sub(self.tuning.wheel_scroll_lines);
                }
                _ => {}
            }
            return;
        }
        if !matches!(self.mode, Mode::Edit | Mode::Terminal) {
            return;
        }
        match m.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                let hit = self
                    .pane_rects
                    .iter()
                    .find(|(_, r)| {
                        m.column >= r.x && m.column < r.x + r.width
                            && m.row >= r.y && m.row < r.y + r.height
                    })
                    .map(|(id, r)| (*id, *r));
                let (pane_id, rect) = match hit { Some(h) => h, None => return };
                self.tab_mut().focused_pane = pane_id;
                match self.panes.get(&pane_id).map(|p| p.content.clone()) {
                    Some(PaneContent::Terminal(tid)) => {
                        self.mode = Mode::Terminal;
                        // Begin a drag-selection at the clicked cell (screen coords).
                        let (rows, cols) = self
                            .terms
                            .get(&tid)
                            .map(|t| t.screen().size())
                            .unwrap_or((0, 0));
                        let vh = rows.min(rect.height.saturating_sub(2));
                        let vw = cols.min(rect.width.saturating_sub(2));
                        let (ox, oy) = (rect.x + 1, rect.y + 1);
                        let cell = (
                            m.row.saturating_sub(oy).min(vh.saturating_sub(1)),
                            m.column.saturating_sub(ox).min(vw.saturating_sub(1)),
                        );
                        self.term_sel = Some(TermSel { tid, ox, oy, vw, vh, anchor: cell, end: cell });
                    }
                    Some(PaneContent::Editor(buf_id)) => {
                        self.mode = Mode::Edit;
                        // Inner area = rect minus 1-cell border; text starts
                        // after the line-number gutter.
                        let inner_x = rect.x + 1 + crate::ui::gutter_width(&self.tuning);
                        let inner_y = rect.y + 1;
                        if m.row >= inner_y && m.column >= rect.x + 1 {
                            let scroll = self.panes[&pane_id].scroll_row;
                            let row = scroll + (m.row - inner_y) as usize;
                            let row = row.min(self.buffers[&buf_id].line_count().saturating_sub(1));
                            let col = (m.column.saturating_sub(inner_x)) as usize;
                            let col = col.min(self.buffers[&buf_id].line_len(row));
                            self.clear_selection();
                            let p = self.panes.get_mut(&pane_id).unwrap();
                            p.cursor_row = row;
                            p.cursor_col = col;
                            p.col_affinity = col;
                        }
                    }
                    None => {}
                }
            }
            // Terminal wheel = tmux's three-way dispatch. Mars's own scrollback
            // is only ONE of the destinations: a full-screen app (alternate
            // screen — Claude Code, less, vim) has no scrollback at all, so the
            // wheel must become input to the app, not a silent no-op.
            MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
                let up = matches!(m.kind, MouseEventKind::ScrollUp);
                let n = self.tuning.wheel_scroll_lines;
                let fid = self.focused_pane_id();
                let rect = self.pane_rects.iter().find(|(id, _)| *id == fid).map(|(_, r)| *r);
                match self.focused_pane().content {
                    PaneContent::Terminal(tid) => {
                        let Some(t) = self.terms.get_mut(&tid) else { return };
                        let screen = t.screen();
                        let delta = if up { n as i64 } else { -(n as i64) };
                        if t.view_offset() > 0 {
                            // Already browsing mars scrollback: the wheel keeps
                            // operating on the view until it returns to live,
                            // so scrollback is always escapable.
                            t.scroll_view(delta);
                        } else if screen.mouse_protocol_mode() != vt100::MouseProtocolMode::None {
                            // The inner app owns the mouse — forward the wheel
                            // press in the app's own encoding, pane-relative,
                            // 1-based (inner area starts past the border cell).
                            let (mut x, mut y) = (1u16, 1u16);
                            if let Some(r) = rect {
                                if m.column > r.x && m.row > r.y {
                                    x = (m.column - r.x).min(r.width.saturating_sub(2).max(1));
                                    y = (m.row - r.y).min(r.height.saturating_sub(2).max(1));
                                }
                            }
                            let bytes = encode_wheel(&screen, up, x, y);
                            t.send_bytes(&bytes);
                        } else if screen.alternate_screen() {
                            // Full-screen app without mouse reporting: translate
                            // each notch into arrow keys, honoring DECCKM.
                            let seq: &[u8] = match (up, screen.application_cursor()) {
                                (true, false) => b"\x1b[A",
                                (true, true) => b"\x1bOA",
                                (false, false) => b"\x1b[B",
                                (false, true) => b"\x1bOB",
                            };
                            for _ in 0..n {
                                t.send_bytes(seq);
                            }
                        } else {
                            t.scroll_view(delta);
                        }
                    }
                    PaneContent::Editor(_) if self.mode == Mode::Edit => {
                        for _ in 0..n {
                            if up { self.move_up() } else { self.move_down() }
                        }
                    }
                    _ => {}
                }
            }
            // Extend an in-progress terminal selection.
            MouseEventKind::Drag(MouseButton::Left) => {
                if let Some(sel) = self.term_sel.as_mut() {
                    sel.end = (
                        m.row.saturating_sub(sel.oy).min(sel.vh.saturating_sub(1)),
                        m.column.saturating_sub(sel.ox).min(sel.vw.saturating_sub(1)),
                    );
                }
            }
            // Release: copy the selected terminal text to the clipboard — but
            // only for a real drag. A plain click (anchor == end) is focus, not
            // a selection; copying a 1-char "selection" would silently clobber
            // the clipboard on every click.
            MouseEventKind::Up(MouseButton::Left) => {
                if let Some(sel) = self.term_sel.take() {
                    let text = if sel.anchor == sel.end {
                        String::new()
                    } else {
                        self.term_selection_text(&sel)
                    };
                    if !text.is_empty() {
                        if let Some(cb) = self.clipboard.as_mut() {
                            let _ = cb.set_text(text.clone());
                        }
                        self.kill_ring.push(text.clone());
                        self.status_msg = Some(format!("Copied {} chars", text.chars().count()));
                    }
                }
            }
            _ => {}
        }
    }

    /// Extract the text under a terminal drag-selection.
    fn term_selection_text(&self, sel: &TermSel) -> String {
        let Some(t) = self.terms.get(&sel.tid) else { return String::new() };
        let (mut a, mut b) = (sel.anchor, sel.end);
        if b < a {
            std::mem::swap(&mut a, &mut b);
        }
        selection_text_from_screen(&t.screen(), a, b, sel.vw.saturating_sub(1))
    }

    // ── Persisted state (frecency + nudge counters) ──────────────────────────

    fn save_state(&self) {
        let state = PersistedState {
            frecency: self.frecency.clone(),
            bar_uses: self.bar_uses.clone(),
            file_frecency: self.file_frecency.clone(),
        };
        if let Some(path) = config::state_path() {
            if let Some(parent) = path.parent() {
                let _ = std::fs::create_dir_all(parent);
            }
            if let Ok(json) = serde_json::to_string_pretty(&state) {
                let _ = std::fs::write(path, json);
            }
        }
    }
}

#[derive(Default, serde::Serialize, serde::Deserialize)]
struct PersistedState {
    #[serde(default)]
    frecency: HashMap<String, u32>,
    #[serde(default)]
    bar_uses: HashMap<String, u32>,
    #[serde(default)]
    file_frecency: HashMap<String, u32>,
}

impl PersistedState {
    fn load() -> Self {
        config::state_path()
            .and_then(|p| std::fs::read_to_string(p).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default()
    }
}

/// Extract the first fenced ``` code block's body (drops an optional language
/// tag on the opening fence). None if there's no complete block.
pub fn extract_code_block(text: &str) -> Option<String> {
    let start = text.find("```")?;
    let after = &text[start + 3..];
    // Skip the rest of the opening-fence line (e.g. ```rust).
    let body_start = after.find('\n').map(|i| i + 1).unwrap_or(after.len());
    let body = &after[body_start..];
    let end = body.find("```")?;
    Some(body[..end].trim_end_matches('\n').to_string())
}

/// Encode a wheel press for an inner app that enabled mouse reporting, in the
/// app's own negotiated encoding. Coordinates are 1-based, pane-relative.
fn encode_wheel(screen: &vt100::Screen, up: bool, x: u16, y: u16) -> Vec<u8> {
    let button: u32 = if up { 64 } else { 65 };
    match screen.mouse_protocol_encoding() {
        vt100::MouseProtocolEncoding::Sgr => format!("\x1b[<{button};{x};{y}M").into_bytes(),
        vt100::MouseProtocolEncoding::Utf8 => {
            let mut out = vec![0x1b, b'[', b'M'];
            for v in [32 + button, 32 + x as u32, 32 + y as u32] {
                let mut buf = [0u8; 4];
                out.extend_from_slice(
                    char::from_u32(v).unwrap_or(' ').encode_utf8(&mut buf).as_bytes(),
                );
            }
            out
        }
        // X10 bytes overflow past coordinate 223 (32 + 223 = 255); clamp.
        vt100::MouseProtocolEncoding::Default => {
            let b = |v: u32| (32 + v.min(223)) as u8;
            vec![0x1b, b'[', b'M', b(button), b(x as u32), b(y as u32)]
        }
    }
}

/// Translate a key event into the byte sequence a PTY expects.
fn key_to_bytes(key: &KeyEvent) -> Vec<u8> {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    match key.code {
        KeyCode::Char(c) => {
            if ctrl && c.is_ascii_alphabetic() {
                // Ctrl-A..Ctrl-Z → 0x01..0x1a
                vec![(c.to_ascii_lowercase() as u8 - b'a') + 1]
            } else {
                let mut b = [0u8; 4];
                c.encode_utf8(&mut b).as_bytes().to_vec()
            }
        }
        KeyCode::Enter     => vec![b'\r'],
        KeyCode::Backspace => vec![0x7f],
        KeyCode::Tab       => vec![b'\t'],
        KeyCode::BackTab   => vec![0x1b, b'[', b'Z'],
        KeyCode::Esc       => vec![0x1b],
        KeyCode::Left      => vec![0x1b, b'[', b'D'],
        KeyCode::Right     => vec![0x1b, b'[', b'C'],
        KeyCode::Up        => vec![0x1b, b'[', b'A'],
        KeyCode::Down      => vec![0x1b, b'[', b'B'],
        KeyCode::Home      => vec![0x1b, b'[', b'H'],
        KeyCode::End       => vec![0x1b, b'[', b'F'],
        KeyCode::PageUp    => vec![0x1b, b'[', b'5', b'~'],
        KeyCode::PageDown  => vec![0x1b, b'[', b'6', b'~'],
        KeyCode::Delete    => vec![0x1b, b'[', b'3', b'~'],
        _ => vec![],
    }
}