croft-software 0.1.942

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
use anyhow::{Context, Result};
use crossterm::{
    event::{
        self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
        Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags,
        MouseButton, MouseEvent, MouseEventKind, PopKeyboardEnhancementFlags,
        PushKeyboardEnhancementFlags,
    },
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
    Terminal,
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::Paragraph,
};
use std::collections::BTreeSet;
use std::io::{Stdout, stdout};
use std::path::{Path, PathBuf};
use std::time::Duration;

mod click;
mod cursor_blink;
mod editor_layout;
mod fs_watch;
mod git_worker;
mod hover;
mod nav;
mod overlay;
mod perf_hud;
pub(crate) mod sidebar_dwell;
mod welcome;
use click::{ClickTracker, ModifiedClickTracker};
use cursor_blink::CursorBlink;
use fs_watch::FsWatch;
use git_worker::GitWorker;
use hover::{HOVER_DELAY, HoverDwell};
use nav::{NavHistory, NavLoc};
use overlay::OverlayManager;
use perf_hud::PerfHud;
use sidebar_dwell::{AUTO_HIDE_DWELL, SidebarDwell};
use welcome::WelcomeState;

use crate::widgets::terminal::cwd_of_pid;

use crate::widgets::{
    dependencies::{DependenciesPanel, Dependency, Ecosystem},
    editor::{Editor, EditorTabs},
    file_tree::FileTree,
    open_editors::{OpenEditorItem, OpenEditorsPanel},
    outline::OutlinePanel,
    remote::RemotePanel,
    run_debug::RunDebugPanel,
    search::{SearchPanel, SearchRequest},
    source_control::SourceControlPanel,
    terminal::{MouseAction, MouseButtonKind, MouseMods, PtyTerminal},
    timeline::TimelinePanel,
};

/// Which sidebar view is active in the left side panel.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SidebarView {
    Explorer,
    Search,
    SourceControl,
    Remote,
    RunDebug,
    Extensions,
    Testing,
}

/// The toggleable sub-views stacked inside the Explorer side panel, mirroring
/// VS Code's "Views and More Actions" (⋯) menu on the EXPLORER header. Ordered
/// top-to-bottom exactly as they stack in the panel.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ExplorerView {
    OpenEditors,
    Folders,
    Outline,
    Timeline,
    Dependencies,
}

impl ExplorerView {
    /// Every view, in stacking order — the order the ⋯ menu lists them.
    pub const ALL: [ExplorerView; 5] = [
        ExplorerView::OpenEditors,
        ExplorerView::Folders,
        ExplorerView::Outline,
        ExplorerView::Timeline,
        ExplorerView::Dependencies,
    ];

    /// Menu / section-header label, matching VS Code's wording. Dependencies is
    /// a static fallback only — its real label is language-aware and computed
    /// from the detected ecosystems (see [`crate::widgets::dependencies`]).
    pub fn label(self) -> &'static str {
        match self {
            ExplorerView::OpenEditors => "Open Editors",
            ExplorerView::Folders => "Folders",
            ExplorerView::Outline => "Outline",
            ExplorerView::Timeline => "Timeline",
            ExplorerView::Dependencies => "Dependencies",
        }
    }
}

/// Which Explorer sub-views are shown, toggled from the ⋯ menu. Wraps the
/// persisted [`crate::prefs::ExplorerViewsPrefs`] so the app can query/flip a
/// view by its [`ExplorerView`] without touching the serde struct's fields
/// directly.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct ExplorerViewVisibility {
    flags: crate::prefs::ExplorerViewsPrefs,
}

impl ExplorerViewVisibility {
    fn from_prefs(flags: crate::prefs::ExplorerViewsPrefs) -> Self {
        Self { flags }
    }

    fn as_prefs(self) -> crate::prefs::ExplorerViewsPrefs {
        self.flags
    }

    pub fn is_visible(&self, view: ExplorerView) -> bool {
        match view {
            ExplorerView::OpenEditors => self.flags.open_editors,
            ExplorerView::Folders => self.flags.folders,
            ExplorerView::Outline => self.flags.outline,
            ExplorerView::Timeline => self.flags.timeline,
            ExplorerView::Dependencies => self.flags.dependencies,
        }
    }

    /// Flip one view's visibility, returning the new state.
    pub fn toggle(&mut self, view: ExplorerView) -> bool {
        let slot = match view {
            ExplorerView::OpenEditors => &mut self.flags.open_editors,
            ExplorerView::Folders => &mut self.flags.folders,
            ExplorerView::Outline => &mut self.flags.outline,
            ExplorerView::Timeline => &mut self.flags.timeline,
            ExplorerView::Dependencies => &mut self.flags.dependencies,
        };
        *slot = !*slot;
        *slot
    }
}

/// The clickable icons on the activity bar, used to track which one the
/// pointer is hovering. Mirrors `SidebarView` plus the bottom-anchored
/// settings gear, which is not a sidebar view but is still a hoverable
/// button.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ActivityIcon {
    Explorer,
    Search,
    SourceControl,
    Remote,
    RunDebug,
    Extensions,
    Testing,
    Settings,
}

/// How many commits the history scrubber loads up front (#371).
///
/// A ceiling rather than the whole history: the issue's own criterion is
/// that scrubbing 200 commits stays interactive, and a repo with 50,000 of
/// them should not pay for all of them to answer a question about the last
/// few hundred. Lazy loading around the cursor is the follow-up; this bounds
/// the first version so it cannot be slow on a large repo.
const SCRUB_COMMIT_LIMIT: usize = 500;

/// How long one host gets in a fleet run (#363).
///
/// A ceiling on the CONNECT and a wall-clock bound on the whole thing: the
/// issue's criterion is that a host which times out shows red without
/// delaying the others, and only the second bound delivers that for a host
/// that connects and then hangs.
const FLEET_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

const ACTIVITY_BAR_WIDTH: u16 = 4;

const ACTIVITY_ICON_HEIGHT: u16 = 2;
const ACTIVITY_ICON_GAP: u16 = 0;
const FALLBACK_CELL_PIXEL: (u32, u32) = (10, 20);

/// Fixed width of the secondary side bar (hosts the active file's Outline),
/// on the edge opposite the primary side bar. VS Code's auxiliary bar.
const SECONDARY_SIDEBAR_WIDTH: u16 = 30;

/// Cell box for each Customize Layout toolbar icon: 2 cells wide × 1 tall —
/// exactly HALF an activity-bar icon's `ACTIVITY_BAR_WIDTH`×`ACTIVITY_ICON_HEIGHT`
/// (4×2) box, so the toolbar reads as a smaller chrome control than the far-left
/// Explorer / Search icons, as intended. With the usual ~1:2 cell aspect this is
/// a crisp ~square ≈20×20px image. Baked OPAQUE on the editor background so it
/// paints in FRONT of the tab-strip / welcome top line (the line sits behind
/// it), and stays within the single top row (no overlap with editor content).
const LAYOUT_ICON_CELLS_W: u16 = 2;
const LAYOUT_ICON_CELLS_H: u16 = 1;

/// Which edge the primary side bar (and the activity bar that flanks it) dock
/// to. VS Code's "Primary Side Bar Position". Persisted via `crate::prefs`.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum SideBarPosition {
    #[default]
    Left,
    Right,
}

/// Horizontal span of the bottom panel (the terminal stack). Mirrors VS
/// Code's "Panel Alignment": `Center` (default) spans the editor column;
/// `Left`/`Right` hug that half of the editor column; `Justify` stretches the
/// panel across the full content width, under the side bar. Persisted.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum PanelAlignment {
    Left,
    #[default]
    Center,
    Right,
    Justify,
}

/// Where the quick input (command palette / Go to File) anchors vertically.
/// VS Code's "Quick Input Position". Persisted.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum QuickInputPosition {
    #[default]
    Top,
    Center,
}

/// One in-flight `textDocument/selectionRange` request (#254): the
/// Expand Selection gesture waiting on its chains. `positions` snapshots
/// the exact cursors the request was fired for, so a reply (or a reuse
/// attempt) after ANY caret movement is recognised as stale even though
/// `edit_seq` did not move.
struct PendingSelectionRanges {
    id: u64,
    path: PathBuf,
    seq: u64,
    presses: usize,
    positions: Vec<(u32, u32)>,
}

/// Pre-Zen visibility snapshot, restored verbatim when Zen Mode is toggled
/// off so the workspace returns to exactly the chrome it had before.
#[derive(Clone, Copy, Debug)]
struct PreZenLayout {
    activity_bar: bool,
    status_bar: bool,
    side_bar: bool,
    secondary_side_bar: bool,
    panel: bool,
}

/// Hit-test rects for the three layout-control icons (Toggle Primary Side
/// Bar, Toggle Panel, Customize Layout) rendered at the top-right of the
/// editor tab strip and the welcome screen — croft's analog of VS Code's
/// title-bar layout controls.
#[derive(Clone, Copy, Default)]
struct LayoutIconAreas {
    toggle_side_bar: Rect,
    toggle_panel: Rect,
    customize: Rect,
}

/// Result of [`compute_chrome_layout`]: the rectangles for each workspace
/// region within the horizontal `main` band. Hidden regions are `None` and
/// consume no width.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
struct ChromeLayout {
    activity: Option<Rect>,
    primary_side: Option<Rect>,
    secondary_side: Option<Rect>,
    /// The editor + terminal column (always present).
    right: Rect,
    /// Column of the seam between the editor and the primary side bar, where a
    /// resize drag starts. `None` when the primary side bar is hidden.
    sidebar_splitter_x: Option<u16>,
}

/// Pure horizontal layout of the workspace chrome within `main`. Column order
/// follows the primary side bar's position (the activity bar always flanks the
/// primary side bar on its outer edge, like VS Code):
///   `Left`:  `[activity][primary][right......][secondary]`
///   `Right`: `[secondary][right......][primary][activity]`
/// The `right` column is guaranteed at least `RIGHT_PANE_MIN` cells; the
/// primary side bar is shrunk to make room when the frame is narrow.
fn compute_chrome_layout(
    main: Rect,
    activity_visible: bool,
    primary_visible: bool,
    secondary_visible: bool,
    side_bar_position: SideBarPosition,
    sidebar_w: u16,
    secondary_w: u16,
) -> ChromeLayout {
    let activity_w = if activity_visible {
        ACTIVITY_BAR_WIDTH
    } else {
        0
    };
    let secondary_w = if secondary_visible { secondary_w } else { 0 };
    // Reserve activity + secondary first, then fit the primary side bar in
    // what's left while keeping RIGHT_PANE_MIN for the editor column.
    let reserved = activity_w.saturating_add(secondary_w);
    let after_reserved = main.width.saturating_sub(reserved);
    let max_primary = after_reserved.saturating_sub(RIGHT_PANE_MIN);
    let primary_w = if primary_visible {
        sidebar_w.min(max_primary)
    } else {
        0
    };
    let right_w = after_reserved.saturating_sub(primary_w);

    let row = |x: u16, w: u16| Rect {
        x,
        y: main.y,
        width: w,
        height: main.height,
    };
    let mut x = main.x;
    let (activity, primary_side, right, secondary_side, splitter);
    match side_bar_position {
        SideBarPosition::Left => {
            activity = (activity_w > 0).then(|| row(x, activity_w));
            x += activity_w;
            primary_side = (primary_w > 0).then(|| row(x, primary_w));
            x += primary_w;
            let right_rect = row(x, right_w);
            // Seam = editor's left edge.
            splitter = (primary_w > 0).then_some(right_rect.x);
            right = right_rect;
            x += right_w;
            secondary_side = (secondary_w > 0).then(|| row(x, secondary_w));
        }
        SideBarPosition::Right => {
            secondary_side = (secondary_w > 0).then(|| row(x, secondary_w));
            x += secondary_w;
            let right_rect = row(x, right_w);
            right = right_rect;
            x += right_w;
            // Seam = sidebar's left edge (= editor's right edge).
            splitter = (primary_w > 0).then_some(x);
            primary_side = (primary_w > 0).then(|| row(x, primary_w));
            x += primary_w;
            activity = (activity_w > 0).then(|| row(x, activity_w));
        }
    }
    ChromeLayout {
        activity,
        primary_side,
        secondary_side,
        right,
        sidebar_splitter_x: splitter,
    }
}

/// Pure horizontal placement of the bottom panel within its `band`. `Center`
/// and `Justify` fill the band; `Left`/`Right` hug that half (clamped to a
/// usable minimum). The leftover strip is painted with the editor background
/// by the caller so it never ghosts.
fn panel_band_rect(band: Rect, alignment: PanelAlignment) -> Rect {
    match alignment {
        PanelAlignment::Center | PanelAlignment::Justify => band,
        PanelAlignment::Left => Rect {
            width: (band.width / 2).max(RIGHT_PANE_MIN).min(band.width),
            ..band
        },
        PanelAlignment::Right => {
            let w = (band.width / 2).max(RIGHT_PANE_MIN).min(band.width);
            Rect {
                x: band.x + band.width - w,
                width: w,
                ..band
            }
        }
    }
}

/// Centered popup geometry for frames of any size. Min bounds cap at the
/// frame because Ord::clamp panics on min > max, and a frame with no
/// cells on an axis gets no popup at all.
fn fallback_popup_rect(full: Rect, max_w_cap: u16) -> Rect {
    if full.width == 0 || full.height == 0 {
        return Rect {
            width: 0,
            height: 0,
            ..full
        };
    }
    let max_w = max_w_cap.min(full.width);
    let max_h = full.height;
    let width = (full.width.saturating_mul(7) / 10).clamp(40.min(max_w), max_w);
    let height = (full.height.saturating_mul(6) / 10).clamp(10.min(max_h), max_h);
    Rect {
        x: full.x + (full.width.saturating_sub(width)) / 2,
        y: full.y + (full.height.saturating_sub(height)) / 4,
        width,
        height,
    }
}

fn activity_icon_glyph_x(bar: Rect) -> u16 {
    bar.x + bar.width / 2
}

/// Rank an executable basename as an lldb-dap candidate, or `None` if it is not
/// one. LLVM ships the adapter under several names: the bare `lldb-dap`, the
/// versioned `lldb-dap-18` that Debian/Ubuntu install (often with no
/// unversioned symlink), and the legacy `lldb-vscode[-NN]` name from older
/// releases. Higher rank wins: an unversioned binary (tracks the system
/// default) beats any versioned one, a newer LLVM release beats an older one,
/// and at equal version the modern `lldb-dap` name beats legacy `lldb-vscode`.
fn lldb_dap_rank(name: &str) -> Option<i64> {
    if name == "lldb-dap" {
        return Some(i64::MAX);
    }
    if name == "lldb-vscode" {
        return Some(i64::MAX - 1);
    }
    // `family` breaks ties at equal version: lldb-dap (1) over lldb-vscode (0).
    let (version, family) = name
        .strip_prefix("lldb-dap-")
        .map(|v| (v, 1))
        .or_else(|| name.strip_prefix("lldb-vscode-").map(|v| (v, 0)))?;
    let version: i64 = version.parse().ok()?;
    Some(version * 2 + family)
}

/// Resolve the `lldb-dap` adapter binary: the Xcode Command Line Tools copy
/// first (always present on a dev Mac), then the best-ranked match found by
/// scanning `PATH` for `lldb-dap`/`lldb-dap-NN`/`lldb-vscode[-NN]`. `None` if
/// none is installed.
fn lldb_dap_path() -> Option<String> {
    let xcode = "/Library/Developer/CommandLineTools/usr/bin/lldb-dap";
    if std::path::Path::new(xcode).is_file() {
        return Some(xcode.to_string());
    }
    let path_var = std::env::var_os("PATH")?;
    let mut best: Option<(i64, String)> = None;
    for dir in std::env::split_paths(&path_var) {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
                continue;
            };
            let Some(rank) = lldb_dap_rank(&name) else {
                continue;
            };
            let full = entry.path();
            if is_executable_file(&full) && best.as_ref().is_none_or(|(r, _)| rank > *r) {
                best = Some((rank, full.to_string_lossy().into_owned()));
            }
        }
    }
    best.map(|(_, p)| p)
}

/// The error shown when no lldb-dap adapter is installed, with a host-correct
/// install hint: Xcode Command Line Tools on macOS, the LLVM package elsewhere.
fn lldb_dap_missing_message() -> String {
    let hint = if cfg!(target_os = "macos") {
        "install Xcode Command Line Tools"
    } else {
        "install LLVM, e.g. apt install lldb"
    };
    format!("lldb-dap not found ({hint})")
}

/// The interpreter that runs a Python project's own code: its `.venv` python
/// (where the project's deps, pytest included, are importable) or the system
/// python3. The debug venv's python is only the debugpy ADAPTER host — the
/// debuggee must be this one, or a pytest module launch can't import pytest.
fn project_python(root: &Path) -> PathBuf {
    let venv = root.join(".venv").join("bin").join("python");
    if venv.is_file() {
        return venv;
    }
    if let Some(path_var) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&path_var) {
            let candidate = dir.join("python3");
            if candidate.is_file() {
                return candidate;
            }
        }
    }
    PathBuf::from("python3")
}

/// Whether `path` is a regular file with the executable bit set — i.e. a
/// compiled binary or script croft can run directly (`./file`) and debug via
/// lldb-dap without a build step. The honest signal for "directly executable",
/// since such files usually have no extension.
fn is_executable_file(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path)
        .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}

/// Append variable rows to the debug tree, recursing into any expanded
/// (`variablesReference` in `expanded`) container whose children are loaded.
/// Pulled out as a free function so it can borrow the session immutably while
/// the caller mutates the row vector.
fn push_variable_rows(
    rows: &mut Vec<crate::widgets::run_debug::DebugRow>,
    session: &crate::dap::session::DapSession,
    expanded: &std::collections::HashSet<i64>,
    vars: &[crate::dap::session::Variable],
    indent: u8,
) {
    use crate::widgets::run_debug::{DebugRow, DebugRowKind};
    for v in vars {
        let expandable = v.variables_ref > 0;
        let is_open = expandable && expanded.contains(&v.variables_ref);
        rows.push(DebugRow {
            indent,
            kind: DebugRowKind::Variable {
                reference: v.variables_ref,
                expandable,
                expanded: is_open,
                name: v.name.clone(),
                value: v.value.clone(),
                type_name: v.type_name.clone(),
            },
        });
        if is_open && let Some(children) = session.variables.get(&v.variables_ref) {
            push_variable_rows(rows, session, expanded, children, indent.saturating_add(1));
        }
    }
}

fn activity_explorer_y(bar: Rect) -> u16 {
    bar.y + 1
}

fn activity_search_y(bar: Rect) -> u16 {
    activity_explorer_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}

fn activity_source_control_y(bar: Rect) -> u16 {
    activity_search_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}

fn activity_run_debug_y(bar: Rect) -> u16 {
    activity_source_control_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}

fn activity_remote_y(bar: Rect) -> u16 {
    activity_run_debug_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}

fn activity_extensions_y(bar: Rect) -> u16 {
    activity_remote_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}

fn activity_testing_y(bar: Rect) -> u16 {
    activity_extensions_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}

fn activity_explorer_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_explorer_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

fn activity_search_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_search_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

fn activity_source_control_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_source_control_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

fn activity_remote_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_remote_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

fn activity_run_debug_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_run_debug_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

fn activity_extensions_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_extensions_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

fn activity_testing_block(bar: Rect) -> Rect {
    Rect {
        x: bar.x,
        y: activity_testing_y(bar),
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

/// The settings gear, anchored to the BOTTOM of the activity bar (VS Code's
/// "Manage" gear), asymmetric to the view icons stacked from the top. Returns
/// an empty rect when the bar is too short to fit the gear below the last view
/// icon, so the caller skips rendering and hit-testing it rather than letting
/// it collide with Run-and-Debug on a tiny terminal.
///
/// Reserves a 1-cell bottom inset (`ACTIVITY_ICON_HEIGHT + 1`) so the gap below
/// the gear matches the 1-cell top inset the view icons get from
/// `activity_explorer_y`'s `bar.y + 1`. Without it the gear hugged the row
/// directly above the status bar, reading as lopsidedly low.
const ACTIVITY_BOTTOM_INSET: u16 = 1;

fn activity_settings_block(bar: Rect) -> Rect {
    let y = bar
        .y
        .saturating_add(bar.height)
        .saturating_sub(ACTIVITY_ICON_HEIGHT + ACTIVITY_BOTTOM_INSET);
    let last_view_bottom = activity_testing_y(bar) + ACTIVITY_ICON_HEIGHT;
    if y < last_view_bottom {
        return Rect::default();
    }
    Rect {
        x: bar.x,
        y,
        width: bar.width,
        height: ACTIVITY_ICON_HEIGHT,
    }
}

#[derive(Default, Clone, Copy)]
struct SidebarAreas {
    /// Block occupied by the Explorer activity-bar icon, in absolute coords.
    /// Multi-row when image rendering is active; the hit-test still uses the
    /// whole block.
    explorer_icon: Rect,
    /// Block occupied by the Search activity-bar icon, in absolute coords.
    search_icon: Rect,
    /// Block occupied by the Source Control activity-bar icon, in absolute coords.
    source_control_icon: Rect,
    /// Block occupied by the Remote Explorer activity-bar icon, in absolute coords.
    remote_icon: Rect,
    /// Block occupied by the Run and Debug activity-bar icon, in absolute coords.
    run_debug_icon: Rect,
    /// Block occupied by the Extensions activity-bar icon, in absolute coords.
    extensions_icon: Rect,
    /// Block occupied by the Testing (beaker) activity-bar icon, in absolute coords.
    testing_icon: Rect,
    /// Block occupied by the settings gear, bottom-anchored on the activity
    /// bar (VS Code's "Manage" button). Asymmetric to the view icons up top;
    /// clicking it opens the settings menu (Color Theme picker).
    settings_icon: Rect,
}

/// Pre-encoded iTerm2 OSC-1337 inline-image escape sequences for each icon
/// state. Encoded once in `App::init_graphics` (no PNG re-encoding per
/// frame) and rewritten under the activity-bar block after every ratatui
/// frame draw, since ratatui's bg-clear overdraws the image.
pub struct ActivityBarImages {
    explorer_active: String,
    explorer_inactive: String,
    explorer_hovered: String,
    search_active: String,
    search_inactive: String,
    search_hovered: String,
    source_control_active: String,
    source_control_inactive: String,
    source_control_hovered: String,
    remote_active: String,
    remote_inactive: String,
    remote_hovered: String,
    run_debug_active: String,
    run_debug_inactive: String,
    run_debug_hovered: String,
    extensions_active: String,
    extensions_inactive: String,
    extensions_hovered: String,
    testing_active: String,
    testing_inactive: String,
    testing_hovered: String,
    /// The settings gear. `active` is shown while its menu is open so the
    /// button reads as pressed, mirroring the view icons' selected state;
    /// `hovered` brightens it while the pointer rests on it.
    settings_active: String,
    settings_inactive: String,
    settings_hovered: String,
    /// Customize Layout toolbar icons (top-right of the editor / welcome),
    /// baked OPAQUE at the 4×2-cell toolbar box so they paint in front of the
    /// container's top line. The side-bar / panel icons carry an on/off pair
    /// (filled vs. hollow) matching their visibility; every icon also has a
    /// brighter `_hover` variant emitted while the pointer rests on it, exactly
    /// like the activity-bar icons.
    layout_sidebar_on: String,
    layout_sidebar_on_hover: String,
    layout_sidebar_off: String,
    layout_sidebar_off_hover: String,
    layout_panel_on: String,
    layout_panel_on_hover: String,
    layout_panel_off: String,
    layout_panel_off_hover: String,
    layout_customize: String,
    layout_customize_hover: String,
}

/// Single source of truth for the application's user-facing name.
pub const APP_NAME: &str = "croft";

/// Agnoster-style status colours: clean working tree is green, any dirtiness
/// (modified, staged, or untracked) flips the pill to yellow/orange.
const GIT_CLEAN_COLOR: Color = Color::Rgb(0xa3, 0xbe, 0x8c);
const GIT_DIRTY_COLOR: Color = Color::Rgb(0xeb, 0xcb, 0x8b);

/// Build the status-bar spans for the git pill: branch glyph, branch name,
/// optional ahead/behind counts.  Colour alone carries clean/dirty state, in
/// the spirit of the Agnoster zsh theme.  Returns an empty vec outside a git
/// repo so the bar shows nothing.
fn git_status_spans<'a>(status: &'a crate::git::GitStatus) -> Vec<Span<'a>> {
    if !status.in_repo {
        return Vec::new();
    }
    let pill_color = if status.dirty {
        GIT_DIRTY_COLOR
    } else {
        GIT_CLEAN_COLOR
    };
    let mut spans: Vec<Span> = Vec::with_capacity(6);
    spans.push(Span::raw("  "));
    // Codicon `cod-source-control` (U+EA68): the Y-fork that matches the
    // activity-bar Source Control icon, so the status-bar branch indicator
    // and the SCM panel share the same visual mark.
    spans.push(Span::styled("\u{ea68} ", Style::default().fg(pill_color)));
    let label: &str = match (&status.branch, &status.detached_hash) {
        (Some(b), _) => b.as_str(),
        (None, Some(h)) => h.as_str(),
        (None, None) => "(no head)",
    };
    spans.push(Span::styled(
        label,
        Style::default().fg(pill_color).add_modifier(Modifier::BOLD),
    ));
    if status.ahead > 0 {
        spans.push(Span::styled(
            format!(" \u{2191}{}", status.ahead),
            Style::default().fg(GIT_CLEAN_COLOR),
        ));
    }
    if status.behind > 0 {
        spans.push(Span::styled(
            format!(" \u{2193}{}", status.behind),
            Style::default().fg(GIT_DIRTY_COLOR),
        ));
    }
    spans
}

/// Logo orange (#e97c41), sampled from `assets/logo.png`: the colour of the
/// `<>` angle brackets in the "cr<>ft" wordmark. Also the Extensions panel's
/// trash button — the warm complement to the teal brand gradient.
pub(crate) const BRAND_ORANGE: Color = Color::Rgb(0xe9, 0x7c, 0x41);

/// Spans for the "cr<>ft" wordmark at the left of the status bar, styled to
/// mirror the app logo: white letters with the `<>` (the stylised "o") in the
/// brand orange, sitting on the bar's own background rather than a pill.
fn brand_spans(theme: crate::theme::Theme) -> Vec<Span<'static>> {
    let letter = Style::default()
        .fg(theme.ui(Color::White))
        .add_modifier(Modifier::BOLD);
    vec![
        Span::styled(" cr", letter),
        Span::styled(
            "<>",
            Style::default()
                .fg(BRAND_ORANGE)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("ft ", letter),
    ]
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Pane {
    Tree,
    Editor,
    Terminal,
}

/// Which tab the bottom panel group shows. The panel is the "terminal group"
/// VS Code-style: a tab strip over a shared region. `Terminal` shows the live
/// shell(s); `Problems` shows aggregated workspace diagnostics; `Output` is the
/// read-only per-channel log viewer.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum BottomPanelTab {
    Terminal,
    Problems,
    Output,
    Ports,
    Captures,
}

/// A transient, click-only notification that a browsable port just appeared in
/// the terminal. It never captures keystrokes — the terminal owns those — so
/// the user clicks an action or lets it auto-dismiss. The forward actions only
/// apply on a remote session (a local port is already reachable).
struct PortToast {
    port: u16,
    process: Option<String>,
    origin_remote: bool,
    shown_at: std::time::Instant,
    /// Action button hit rects, recomputed each render.
    buttons: Vec<(Rect, PortToastAction)>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PortToastAction {
    ForwardAndOpen,
    ForwardOnly,
    Open,
    Dismiss,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum CreateKind {
    File,
    Folder,
}

/// Why the single-host lock was last refused, for announcing each reason
/// once (see `App::pair_lock_denied`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PairLockDenial {
    Busy,
    Io,
}

/// The bottom-left "a newer croft is available" popup (#333). Click-only
/// like the port toast: it never takes a keystroke from the editor or a
/// terminal. `ready` flips it from Update/Later to Relaunch once the staged
/// build has landed.
struct UpdateToast {
    version: String,
    ready: bool,
    /// Action button hit rects, recomputed each render.
    buttons: Vec<(Rect, UpdateToastAction)>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum UpdateToastAction {
    /// Stage the new version in the background; nothing on PATH changes.
    Update,
    /// Dismiss, and never offer this version again.
    Later,
    /// Swap the staged binary in and re-exec - the only path that updates.
    Relaunch,
}

/// Which producer an [`crate::update_watch::UpdateEvent`] came from: the
/// remote install watcher, the drift rebuild, or the staged release build
/// (#333). They share one event type and one status-bar state machine.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum UpdateSource {
    Watch,
    SelfInstall,
    Staged,
}

/// A fenced block about to run (#353), parked behind the confirm popup.
#[derive(Clone, Debug)]
struct PendingRunBlock {
    pane_name: String,
    cwd: PathBuf,
    command: String,
    /// The block as written, shown whole in the popup (the fence was
    /// refused if it carried control characters, so it renders as typed).
    code: String,
    /// Turns the popup red: the block looks destructive or said `{confirm}`.
    destructive: bool,
    /// The document this block came from, for `{persist}`'s write-back.
    doc: Option<PathBuf>,
    /// The fence opener's SOURCE line, which keys the captured output.
    block_line: usize,
    /// `{persist}`: write the capture back into the document.
    persist: bool,
    /// `{timeout=N}`: stop CAPTURING after N seconds. Never stops the
    /// process; the block keeps running in its pane.
    capture_timeout: Option<std::time::Duration>,
}

/// A block whose output croft is waiting for (#354).
///
/// Armed when the block is typed into its pane and settled by
/// [`App::settle_block_captures`] when the shell reports the command
/// finished.
///
/// IDENTITY, NOT POSITION (#440, landed as #441). `after` is the id of the
/// last command the pane had already finished when the block was typed, so
/// this block's command is the first decoration whose id is greater. Ids
/// are monotonic and the collector never renumbers them, so an evicted
/// command reads as GONE rather than as its neighbour - which is what makes
/// the `{persist}` write safe rather than merely guarded.
///
/// The previous shape indexed the decoration list, which is a sliding
/// window: an eviction shifted every index down and index `seen` came to
/// name a stranger. That was narrowed with a high-water sample and could
/// not be closed by one, because any length-derived signal samples a value
/// that can move twice between observations. An id cannot move at all.
struct PendingCapture {
    pane_name: String,
    doc: Option<PathBuf>,
    block_line: usize,
    /// Ids at or below this belong to commands that finished BEFORE the
    /// block was typed.
    ///
    /// `None` is a sentinel, not a special case: ids start at 1, so `None`
    /// and `Some(0)` select identically and a fresh pane needs no separate
    /// handling.
    ///
    /// THE RESIDUAL IS IN THE SELECTION, NOT HERE. Settling takes the
    /// EARLIEST qualifying id, which is this block's command only if
    /// nothing else finished in the gap between arming and the keystrokes
    /// reaching the shell. A command completing in that gap is taken
    /// instead, on a pane with a full history exactly as on a fresh one -
    /// `after` does not enter into it. The window is much smaller than the
    /// eviction one it replaced, since a foreign command must now COMPLETE
    /// in the gap rather than merely exist, and the outcome self-corrects
    /// on the next run. Closing it properly means arming after the
    /// keystrokes are known to have landed, which is a different change.
    after: Option<u64>,
    started: std::time::Instant,
    timeout: Option<std::time::Duration>,
    persist: bool,
}

/// Canonicalise `path` even when it no longer exists.
///
/// `std::fs::canonicalize` stats the final component, so it fails on a path
/// that has been deleted — and a deletion event carries exactly such a path.
/// Resolving the deepest ancestor that still exists and re-attaching the tail
/// gives the same answer for a live path and a usable one for a dead path,
/// which is what lets a removal clear the row it created (#345).
///
/// `None` when nothing on the way to the filesystem root resolves, and also
/// for a path with no file name to strip — a bare root, or one ending in
/// `..` — which cannot be climbed any further.
fn canonicalize_existing_ancestor(path: &Path) -> Option<PathBuf> {
    let mut tail: Vec<std::ffi::OsString> = Vec::new();
    let mut probe = path.to_path_buf();
    loop {
        if let Ok(canon) = std::fs::canonicalize(&probe) {
            let mut out = canon;
            for part in tail.iter().rev() {
                out.push(part);
            }
            return Some(out);
        }
        // `file_name` is None for a root or `..`; either way there is
        // nothing further to climb.
        tail.push(probe.file_name()?.to_os_string());
        probe = probe.parent()?.to_path_buf();
    }
}

/// State of a background self-update observed by a remote-launched croft.
/// `Idle` is the steady state; `InProgress` paints an "Updating" hint in
/// the status bar; `Ready` arms the re-exec into the freshly-shipped binary.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum UpdateStatus {
    Idle,
    InProgress,
    Ready,
}

/// What to do with one on-type formatting reply (#254). `NotOurs` leaves the
/// armed request alone — a superseded reply must not disarm the newer one
/// still in flight — while `Stale` and `Apply` both consume it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum OnTypeReply {
    NotOurs,
    Stale,
    Apply,
}

/// Rotating-arc frames for the in-progress update glyph. Cycled to read as a
/// spinning circular arrow, the universal "working" indicator.
const UPDATE_SPINNER_FRAMES: [&str; 6] = [
    "\u{25DC}", "\u{25E0}", "\u{25DD}", "\u{25DE}", "\u{25E1}", "\u{25DF}",
];
/// Milliseconds each spinner frame is held; ~10 frames/second reads as smooth
/// motion while keeping the status-bar-only redraws light over SSH.
const UPDATE_SPINNER_FRAME_MS: u128 = 100;

/// Grace before the post-teardown js-debug orphan sweep runs, letting a
/// just-killed server's detached watchdog reparent to init so the sweep can
/// recognise it as an orphan. See [`crate::dap::reaper`].
const REAPER_TEARDOWN_GRACE_MS: u64 = 250;

/// Pick the spinner frame for a given elapsed time. Pure so the wrap-around
/// is unit-testable without a clock.
fn update_spinner_frame(elapsed_ms: u128) -> &'static str {
    let n = UPDATE_SPINNER_FRAMES.len() as u128;
    UPDATE_SPINNER_FRAMES[((elapsed_ms / UPDATE_SPINNER_FRAME_MS) % n) as usize]
}

#[derive(Clone, PartialEq, Eq, Debug)]
enum MenuAction {
    Create(CreateKind),
    /// Move every path in `paths` to the OS trash (recoverable). One entry
    /// for a single right-click, more when a multi-selection is active.
    Delete {
        paths: Vec<PathBuf>,
    },
    /// Open the rename prompt pre-filled with the entry's current name.
    Rename(PathBuf),
    /// Cut the listed paths to the explorer clipboard for later Paste.
    Cut(Vec<PathBuf>),
    /// Copy the listed paths to the explorer clipboard for later Paste.
    Copy(Vec<PathBuf>),
    /// Paste the explorer clipboard's payload into `target_dir`.
    Paste(PathBuf),
    /// Stash this path as the "compare anchor" so the next file the user
    /// right-clicks can be diffed against it.
    SelectForCompare(PathBuf),
    /// Open a side-by-side diff between the previously-selected anchor and
    /// the file the user just right-clicked.
    CompareWithSelected {
        anchor: PathBuf,
        other: PathBuf,
    },
    /// Re-root the workspace at the right-clicked folder. Folder-only -
    /// files can't be roots. Used to dive into a nested git repo without
    /// relaunching croft.
    MakeRoot(PathBuf),
    /// Add another folder to the workspace (multi-root, #147): opens the
    /// fuzzy directory picker in add-folder mode.
    AddWorkspaceFolder,
    /// Drop a SECONDARY workspace root from the folder set (#147).
    RemoveWorkspaceFolder(PathBuf),
    /// Copy the absolute path of the right-clicked editor tab to the system
    /// clipboard (VS Code's "Copy Path"). Available wherever the tab is backed
    /// by a real on-disk path, local or remote.
    CopyTabPath(PathBuf),
    /// Copy the right-clicked editor tab's path relative to the workspace root
    /// (VS Code's "Copy Relative Path"). Falls back to the absolute path when
    /// the file lives outside the workspace root. Local or remote.
    CopyTabRelativePath(PathBuf),
    /// Reveal the right-clicked editor tab's file in the Explorer tree:
    /// expand its parent folders, select its row, and focus the Explorer.
    /// Mirrors VS Code's "Reveal in Explorer View". Works local and remote.
    RevealInExplorer(PathBuf),
    /// Reveal the path in macOS Finder via `open -R`. Local-macOS only:
    /// on a remote SSH session croft runs on the headless host where no
    /// Finder exists, so the menu omits this entry entirely rather than
    /// offering a no-op.
    RevealInFinder(PathBuf),
    /// Open the file in an extension-contributed viewer (#465): the viewer's
    /// id and the file.
    OpenInViewer(String, PathBuf),
    /// Close the editor tab at `idx`. Mirrors clicking the tab's `×`
    /// glyph; surfaces in the tab-strip right-click menu so the four
    /// close actions (Close / Others / Right / All) live in one place.
    CloseTab(usize),
    /// Close every editor tab whose index ≠ `keep_idx`.
    CloseOtherTabs(usize),
    /// Close every editor tab whose index > `from_idx`.
    CloseTabsToRight(usize),
    /// Close every editor tab and reset the pane to a blank state.
    CloseAllTabs,
    /// Close every saved (non-dirty) editor tab, keeping any with unsaved
    /// changes. Mirrors VS Code's "Close Saved".
    CloseSavedTabs,
    /// Promote the preview tab at `idx` to a permanent tab so a later
    /// single-click open won't replace it (VS Code's "Keep Open"). Only
    /// surfaced for a tab that is currently the replaceable preview slot.
    KeepTabOpen(usize),
    /// Toggle the pinned state of the tab at `idx` (VS Code's "Pin" / "Unpin").
    /// Pinned tabs stay leftmost and survive Close Others / Close to the Right.
    ToggleTabPin(usize),
    /// Split the editor side by side, the new (focused) duplicate to the RIGHT
    /// (VS Code "Split Right"). The default split.
    SplitEditor,
    /// Split side by side, the new focused duplicate to the LEFT ("Split Left").
    SplitEditorLeft,
    /// Split stacked, the new focused duplicate ABOVE ("Split Up").
    SplitEditorUp,
    /// Split stacked, the new focused duplicate BELOW ("Split Down").
    SplitEditorDown,
    /// Move the active editor into the group above ("Move Above").
    MoveEditorUp,
    /// Move the active editor into the group below ("Move Below").
    MoveEditorDown,
    /// Move the active editor into the group to the left ("Move Left").
    MoveEditorLeft,
    /// Move the active editor into the group to the right ("Move Right").
    MoveEditorRight,
    /// Open a second view of the active file beside it ("Split in Group").
    SplitInGroup,
    /// Move keyboard focus to the left editor group (while split).
    FocusGroupLeft,
    /// Move keyboard focus to the right editor group (while split).
    FocusGroupRight,
    /// VS Code "Move into New Window": detach the tab at `idx` into a
    /// full-screen, chrome-free editor window (Esc returns it). The tab leaves
    /// its group, which collapses if it was the group's last tab.
    MoveIntoNewWindow(usize),
    /// VS Code "Copy into New Window" (⌘K O): open a duplicate view of the tab
    /// at `idx` in a full-screen editor window, leaving the original in place.
    CopyIntoNewWindow(usize),
    /// Editor body: LSP "Rename Symbol" of the identifier at buffer `(row,
    /// col)`. Captured at right-click so the later dispatch targets the same
    /// symbol the user clicked.
    RenameSymbolAt {
        row: usize,
        col: usize,
    },
    /// Editor body: "Change All Occurrences" of the word at buffer `(row,
    /// col)` (multi-cursor select within the current file).
    ChangeAllOccurrencesAt {
        row: usize,
        col: usize,
    },
    /// Editor body: LSP "Go to Definition" of the identifier at buffer
    /// `(row, col)`.
    GoToDefinitionAt {
        row: usize,
        col: usize,
    },
    /// Editor body: LSP "Go to Declaration" of the identifier at buffer
    /// `(row, col)`. Distinct from definition for languages that separate the
    /// two (C/C++ header prototype vs `.c` body, TypeScript `.d.ts` vs source).
    GoToDeclarationAt {
        row: usize,
        col: usize,
    },
    /// Editor body: LSP "Go to Type Definition" of the identifier at buffer
    /// `(row, col)`. Jumps to where the *type* of the expression under the
    /// cursor is defined (e.g. the `User` struct for `let u = get_user()`),
    /// as opposed to where the symbol itself is defined.
    GoToTypeDefinitionAt {
        row: usize,
        col: usize,
    },
    /// Editor body: LSP "Go to Implementations" of the abstraction at buffer
    /// `(row, col)`. Walks down from a trait / interface / abstract method to
    /// the concrete implementors; the server often returns many, in which case
    /// the results are offered as a picker built from `GoToLocation` items.
    GoToImplementationAt {
        row: usize,
        col: usize,
    },
    /// Editor body: LSP "Go to References" of the symbol at buffer `(row, col)`.
    /// Finds every use of the symbol project-wide (declaration included, like VS
    /// Code); the server almost always returns many, which are offered as a
    /// picker built from `GoToLocation` items.
    GoToReferencesAt {
        row: usize,
        col: usize,
    },
    /// Return to the location before the last navigation jump (#31).
    NavigateBack,
    NavigateForward,
    /// Editor body: LSP "Quick Fix" of the position at buffer `(row, col)`.
    QuickFixAt {
        row: usize,
        col: usize,
    },
    /// Jump straight to an already-resolved location (LSP line/character). Used
    /// for the entries of the multi-result "Go to Implementations" / "Go to
    /// References" pickers, where each row is one location; selecting it records
    /// nav history and opens the file at that position.
    GoToLocation {
        path: PathBuf,
        line: u32,
        col: u32,
    },
    /// Editor gutter: toggle a breakpoint on 1-based `line`. Built from a
    /// glyph-margin right-click; the label reads "Add Breakpoint" or "Remove
    /// Breakpoint" depending on whether one already sits on that line, but both
    /// resolve to the same toggle. Mirrors VS Code's glyph-margin menu.
    ToggleBreakpointAt {
        line: usize,
    },
    /// Editor gutter: open the breakpoint-condition editor for 1-based `line`,
    /// creating the breakpoint if absent. VS Code's "Add Conditional
    /// Breakpoint" / "Edit Condition".
    EditBreakpointConditionAt {
        line: usize,
    },
    /// Editor gutter: open the logpoint editor for 1-based `line`, creating
    /// the breakpoint if absent. VS Code's "Add Logpoint" / "Edit Logpoint".
    EditLogpointAt {
        line: usize,
    },
    /// Editor gutter: ask the resident navigator about 0-based `line`
    /// (opens the ask box scoped to that line).
    AskNavigatorAt {
        line: usize,
    },
    /// Editor body: ask the navigator about the selected 0-based inclusive
    /// line span (the selection's text rides the turn).
    AskNavigatorSelection {
        start: usize,
        end: usize,
    },
    /// CAPTURES row: ask the navigator about the selected captured line,
    /// with the pane rows around it (#372).
    AskNavigatorAboutCapture,
    /// PROBLEMS row: have the navigator fix this diagnostic as a streamed,
    /// cancellable edit (#374).
    FixProblemWithNavigator {
        path: PathBuf,
        item: crate::widgets::problems::ProblemItem,
    },
    /// Editor body: one level of the call hierarchy for the symbol at buffer
    /// `(row, col)` — callers when `incoming`, callees otherwise.
    ShowCallsAt {
        row: usize,
        col: usize,
        incoming: bool,
    },
    /// Settings gear → "Color Theme": replace the gear menu with the theme
    /// picker (the list of themes with a check on the active one).
    OpenThemePicker,
    /// Theme picker entry: switch the IDE color theme to `theme`, persist it,
    /// re-emit the session background, and re-bake the icon images.
    SetTheme(crate::theme::Theme),
    /// Explorer "Views and More Actions" (⋯) entry: flip the visibility of one
    /// stacked sub-view (Open Editors / Folders / Outline / Timeline / Rust
    /// Dependencies) and persist the choice.
    ToggleExplorerView(ExplorerView),
    /// Customize Layout: re-open the Customize Layout popup (so a toggle the
    /// user just flipped stays visible for the next one, like VS Code).
    OpenCustomizeLayout,
    /// Customize Layout: show/hide the left activity bar.
    ToggleActivityBar,
    /// Customize Layout: show/hide the primary side bar (same as ⌘B).
    ToggleSideBar,
    ToggleAutoHideSideBar,
    /// Customize Layout: show/hide the secondary side bar (the Outline).
    ToggleSecondarySideBar,
    /// Customize Layout: show/hide the bottom panel (the terminal, same as ⌃J).
    TogglePanel,
    /// Customize Layout: show/hide the bottom status bar.
    ToggleStatusBar,
    /// Customize Layout: dock the primary side bar to `position`.
    SetSideBarPosition(SideBarPosition),
    /// Customize Layout: set the bottom panel's horizontal alignment.
    SetPanelAlignment(PanelAlignment),
    /// Customize Layout: anchor the quick input at `position`.
    SetQuickInputPosition(QuickInputPosition),
    /// Customize Layout: toggle Zen Mode (hide all chrome / restore).
    ToggleZenMode,
    /// Terminal pane right-click: rename the pane at `idx`.
    RenameTerminal(usize),
    /// Terminal pane right-click: clear the pane at `idx`'s screen + scrollback.
    ClearTerminal(usize),
    /// Terminal pane right-click: maximize the pane at `idx` across the
    /// panel (or restore the even split when already maximized).
    ToggleMaximizeTerminal(usize),
    /// Terminal pane right-click: collapse the pane at `idx` to a strip, or
    /// expand it again (#313).
    ToggleCollapseTerminal(usize),
    /// Terminal pane right-click: copy the pane's selection to the clipboard.
    /// Offered only while the pane HAS one, so the entry never copies nothing.
    TerminalCopySelection,
    /// Terminal pane right-click: paste the host clipboard into the pane.
    TerminalPaste,
    /// Terminal pane right-click: enter quick-select hint mode on the pane.
    TerminalQuickSelect,
    /// Terminal pane right-click: enter copy mode (keyboard selection with
    /// vi motions) on the pane.
    TerminalCopyMode,
    /// Terminal pane right-click: open the durable command-history search.
    TerminalCommandHistory,
    /// Terminal pane right-click: dump the pane's scrollback into a scratch
    /// editor tab.
    OpenScrollbackInEditor,
    /// Terminal pane right-click: toggle broadcast input (keystrokes go to
    /// every pane at once; enabling routes through the confirm popup).
    ToggleBroadcastInput,
    /// Terminal pane right-click while broadcasting: toggle whether the
    /// active pane receives the mirrored input.
    ToggleBroadcastExclusion,
    /// Terminal pane right-click: restore the most recently closed pane
    /// while it is still inside the undo-close grace window.
    UndoCloseTerminal,
    /// Command decoration menu: copy the command's output span to the
    /// clipboard (pane `idx`, the clicked decoration embedded).
    CopyCommandOutput(usize, crate::widgets::terminal::CommandDecoration),
    /// Command decoration menu: select the command's output span in the pane.
    SelectCommandOutput(usize, crate::widgets::terminal::CommandDecoration),
    /// Command decoration menu: type the command at the shell again.
    RerunCommand(usize, crate::widgets::terminal::CommandDecoration),
    /// Terminal profile dropdown (`⌄`): open a new pane running this shell path.
    NewTerminalWithProfile(String),
    /// Minimap right-click menu: show/hide the editor minimap.
    ToggleMinimap,
    /// Minimap right-click menu: move the strip to the given editor edge.
    SetMinimapSide(MinimapSide),
    /// Status-bar language picker: set the active buffer's language mode.
    SetLanguage(Option<crate::highlight::LangKind>),
    /// Status-bar EOL picker: switch the buffer's line-ending style.
    SetLineEnding(crate::widgets::editor::LineEnding),
    /// Status-bar encoding picker: reopen the file decoded with this encoding.
    SetEncoding(&'static encoding_rs::Encoding),
    /// Status-bar indentation picker: pin spaces-vs-tabs and width for newly
    /// typed indentation.
    SetIndentStyle(crate::widgets::editor::IndentStyle),
    /// Status-bar indentation picker: rewrite existing leading indentation.
    /// `true` converts tabs to spaces, `false` converts spaces to tabs.
    ConvertIndentation(bool),
}

/// Return the macOS-style keyboard shortcut hint to display on the right
/// side of a context-menu row, when one exists. Mirrors the bindings in
/// `handle_tree_key` / `handle_explorer_shortcut` so the menu is a
/// discovery surface for the same accelerators the keyboard accepts.
fn shortcut_for(action: &MenuAction) -> Option<&'static str> {
    match action {
        MenuAction::Create(CreateKind::File) => Some("⌘F"),
        MenuAction::Create(CreateKind::Folder) => Some("⌘⇧N"),
        MenuAction::Cut(_) => Some("⌘X"),
        MenuAction::Copy(_) => Some("⌘C"),
        MenuAction::Paste(_) => Some("⌘V"),
        MenuAction::Rename(_) => Some("⌘R"),
        MenuAction::MakeRoot(_) => Some("⌘/"),
        MenuAction::AddWorkspaceFolder => None,
        MenuAction::RemoveWorkspaceFolder(_) => None,
        MenuAction::RevealInFinder(_) => Some("⌥⌘R"),
        MenuAction::CopyTabPath(_) => Some("⌥⌘C"),
        MenuAction::CopyTabRelativePath(_) => Some("⌥⇧⌘C"),
        MenuAction::RevealInExplorer(_) => Some("⌘K E"),
        MenuAction::Delete { .. } => Some("⌫"),
        MenuAction::CloseTab(_) => Some("⌘W"),
        MenuAction::CloseOtherTabs(_) => Some("⌥⌘T"),
        MenuAction::CloseAllTabs => Some("⌘K W"),
        MenuAction::CloseSavedTabs => Some("⌘K U"),
        MenuAction::KeepTabOpen(_) => Some("⌘K ⇧P"),
        MenuAction::ToggleTabPin(_) => Some("⌘K P"),
        MenuAction::SplitEditor => Some("⌘\\"),
        MenuAction::SplitEditorUp => Some("⌘K ⌘\\"),
        MenuAction::SplitInGroup => Some("⌘K ⇧⌘\\"),
        MenuAction::FocusGroupLeft => Some("⌥⌘←"),
        MenuAction::FocusGroupRight => Some("⌥⌘→"),
        MenuAction::CopyIntoNewWindow(_) => Some("⌘K O"),
        MenuAction::MoveIntoNewWindow(_) => Some("⌘K ⇧O"),
        MenuAction::RenameSymbolAt { .. } => Some("F2"),
        MenuAction::ChangeAllOccurrencesAt { .. } => Some("⌘F2"),
        MenuAction::GoToDefinitionAt { .. } => Some("F12"),
        MenuAction::GoToReferencesAt { .. } => Some("⇧F12"),
        MenuAction::NavigateBack => Some("⌃-"),
        MenuAction::NavigateForward => Some("⌃⇧-"),
        MenuAction::QuickFixAt { .. } => Some("⌘."),
        MenuAction::GoToDeclarationAt { .. } => Some("⌃⇧F12"),
        MenuAction::GoToTypeDefinitionAt { .. } => Some("⌃F12"),
        MenuAction::GoToImplementationAt { .. } => Some("⌘F12"),
        MenuAction::ToggleBreakpointAt { .. } => Some("F9"),
        MenuAction::EditBreakpointConditionAt { .. } => Some("⇧F9"),
        MenuAction::EditLogpointAt { .. } => Some("⇧⌥F9"),
        MenuAction::AskNavigatorAt { .. } => Some("⌘K Q"),
        MenuAction::AskNavigatorSelection { .. } => Some("⌘K Q"),
        MenuAction::AskNavigatorAboutCapture => Some("n"),
        MenuAction::FixProblemWithNavigator { .. } => None,
        MenuAction::ShowCallsAt { incoming: true, .. } => Some("⌘K H"),
        MenuAction::ShowCallsAt {
            incoming: false, ..
        } => Some("⌘K ⇧H"),
        MenuAction::OpenThemePicker => Some("⌘K ⌘T"),
        MenuAction::ToggleSideBar => Some("⌘B"),
        MenuAction::ToggleSecondarySideBar => Some("⌥⌘B"),
        MenuAction::TogglePanel => Some("⌃J"),
        MenuAction::ToggleMinimap => Some("⌥⌘M"),
        MenuAction::ToggleZenMode => Some("⌘K Z"),
        MenuAction::CloseTabsToRight(_) => Some("⌘K →"),
        MenuAction::SelectForCompare(_) => Some("⌘K S"),
        MenuAction::CompareWithSelected { .. } => Some("⌘K C"),
        MenuAction::RenameTerminal(_) => Some("⌘K R"),
        MenuAction::ClearTerminal(_) => Some("⌘K K"),
        MenuAction::ToggleMaximizeTerminal(_) => Some("⌘K M"),
        // No hint. The label alternates "Collapse Terminal" / "Expand
        // Terminal", but `Cmd+K [` only ever COLLAPSES: it acts on
        // `active_terminal`, which the focus invariant guarantees is never a
        // folded pane, so the expand branch is unreachable from the chord. Its
        // sibling `ToggleMaximizeTerminal` can carry `⌘K M` honestly because
        // that chord really does toggle both ways. Advertising a shortcut
        // beside a label it cannot perform is worse than showing none.
        MenuAction::ToggleCollapseTerminal(_) => None,
        MenuAction::TerminalCopySelection => Some("⌘C"),
        MenuAction::TerminalPaste => Some("⌘V"),
        MenuAction::TerminalQuickSelect => Some("⌃⇧Space"),
        MenuAction::TerminalCopyMode => Some("⌃⇧Y"),
        MenuAction::TerminalCommandHistory => Some("⌃⇧H"),
        MenuAction::OpenScrollbackInEditor => Some("⌘K D"),
        MenuAction::ToggleBroadcastInput => Some("⌘K I"),
        MenuAction::ToggleBroadcastExclusion => Some("⌘K ⇧I"),
        MenuAction::UndoCloseTerminal => Some("⌘K ⇧T"),
        MenuAction::CopyCommandOutput(..) => Some("⌘K ⇧C"),
        MenuAction::SelectCommandOutput(..) => Some("⌘K ⇧S"),
        MenuAction::RerunCommand(..) => Some("⌘K ⇧R"),
        _ => None,
    }
}

/// Display width (in cells) a menu entry needs: its label plus the right-aligned
/// shortcut hint (items) or the `▸` submenu indicator. Dividers need none.
fn menu_entry_width(entry: &MenuEntry) -> usize {
    match entry {
        MenuEntry::Item { label, action } => {
            let shortcut = shortcut_for(action)
                .map(|s| s.chars().count() + 2)
                .unwrap_or(0);
            label.chars().count() + shortcut
        }
        MenuEntry::Submenu { label, .. } => label.chars().count() + 2,
        MenuEntry::Header(label) => label.chars().count(),
        MenuEntry::Separator => 0,
    }
}

/// The end-of-session feedback line. When breakpoints were set but the program
/// exited without ever stopping, say so explicitly — that is the common "I set a
/// breakpoint and nothing happened" confusion (e.g. running a library module
/// whose breakpointed code is never called). Otherwise a plain end message.
/// What a parked launch does once its task exits 0.
///
/// Two shapes, because a compound's task and a config's task are different
/// steps (#318). A config's own task is the LAST thing before the adapter
/// starts, so the config is already resolved. A compound's task runs BEFORE
/// its member is considered at all, and the member may carry a task of its
/// own - VS Code runs both - so that continuation re-enters the normal launch
/// path rather than skipping to the adapter.
enum PendingLaunchStep {
    /// The config's own task just finished: start it. Boxed like the other
    /// variant so neither dominates the enum's size - a resolved config is
    /// several hundred bytes, and this type is held in an `Option` on `App`.
    Resolved(Box<crate::dap::configs::ResolvedConfig>),
    /// A compound's task just finished: launch its member from the top, which
    /// parks again if the member has a `preLaunchTask` too.
    Member(Box<crate::dap::configs::DebugConfig>),
}

/// A launch.json config launch parked behind its `preLaunchTask` (#250): the
/// task runs in a terminal pane, and the FinishedCommand sweep decides.
struct PendingDebugLaunch {
    /// Uid of the pane the task command was written to.
    pane: u64,
    /// The task's command line, matched against the pane's next finished
    /// command (OSC 133 reports what actually ran).
    command: String,
    /// What to do once the task exits 0.
    step: PendingLaunchStep,
    /// When the task was written, for the no-command-mark fallback below.
    started: std::time::Instant,
}

/// Whether a finished pane command settles the pending preLaunchTask: same
/// pane, and the captured command line is the task's (the shell may report
/// it with surrounding whitespace). Pure, for tests.
fn finished_settles_pending(pane: u64, cmd: &str, pending_pane: u64, pending_cmd: &str) -> bool {
    pane == pending_pane && cmd.trim() == pending_cmd.trim()
}

/// How long a parked launch waits before concluding the pane will never
/// report a command mark. Only consulted while the pane's foreground is back
/// to a plain shell — a long build keeps a non-shell foreground and waits
/// indefinitely, exactly like the FinishedCommand path.
const PRELAUNCH_MARK_GRACE: std::time::Duration = std::time::Duration::from_secs(15);

/// An lldb launch's `program`, resolved against the session's cwd (VS Code's
/// contract for relative programs, and NOT croft's own working directory) and
/// checked for existence, so the validation and the adapter can never read a
/// relative path differently. Returns the absolute path to hand the adapter.
fn resolve_lldb_program(program: &str, cwd: &Path) -> Result<PathBuf, String> {
    let resolved = crate::dap::configs::absolute_in(program, cwd);
    if resolved.exists() {
        Ok(resolved)
    } else {
        Err(format!(
            "program {} does not exist — does the preLaunchTask build it?",
            resolved.display()
        ))
    }
}

/// The FinishedCommand match is the settling signal for a parked launch, but
/// it depends on OSC 133 shell-integration marks. This is the fallback for
/// panes that will never produce one: the pane vanished, or its foreground
/// returned to a plain shell (the task is over) and the grace period passed
/// without a mark. Returns the abort reason, or `None` to keep waiting. Pure.
fn pending_abort_reason(
    pane_exists: bool,
    foreground_is_shell: bool,
    waited: std::time::Duration,
) -> Option<&'static str> {
    if !pane_exists {
        return Some("its terminal pane closed");
    }
    if foreground_is_shell && waited > PRELAUNCH_MARK_GRACE {
        return Some("the task produced no command mark (shell integration missing in that pane?)");
    }
    None
}

fn debug_end_message(had_breakpoints: bool, ever_stopped: bool) -> &'static str {
    if had_breakpoints && !ever_stopped {
        "Program exited without hitting a breakpoint"
    } else {
        "Debug session ended"
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ExplorerClipMode {
    Copy,
    Cut,
}

#[derive(Clone, Debug)]
struct ExplorerClipboard {
    mode: ExplorerClipMode,
    paths: Vec<PathBuf>,
}

/// Accumulated type-to-jump state for the Explorer. `prefix` lowercase
/// only; `last` is the instant of the most recent keystroke.
#[derive(Clone, Debug)]
struct TreeTypeahead {
    prefix: String,
    last: std::time::Instant,
}

/// Inter-keystroke gap that keeps the typeahead buffer alive. Anything
/// longer than this resets the prefix to a single character and cycles
/// past the current selection so repeating the same letter walks
/// through matches.
const TREE_TYPEAHEAD_WINDOW: std::time::Duration = std::time::Duration::from_millis(750);

/// State for an in-progress drag inside the explorer pane. The drag is only
/// "armed" once the pointer has actually moved off the original cell, so a
/// stationary mouse-down → mouse-up still behaves like a click.
#[derive(Clone, Debug)]
struct ExplorerDrag {
    /// Paths the drag is moving (or copying, when Alt is held).
    paths: Vec<PathBuf>,
    /// Tree row of the drop target under the pointer. `None` means the
    /// pointer is over empty space or outside the tree.
    target_idx: Option<usize>,
    /// True once we've seen a Drag event with a different cell from the
    /// initial Down. Until then we treat the gesture as a still-pending click.
    armed: bool,
    /// (instant, x, y) of the initiating mouse-down.
    started_at: (std::time::Instant, u16, u16),
    /// Index of the row the user pressed on. Used as the toggle target if
    /// the gesture turns out to be a stationary Alt-click rather than a drag.
    start_idx: usize,
    /// True when the initiating mouse-down was an Alt/Ctrl click. A
    /// non-armed release toggles the start row's mark; an armed release
    /// performs a copy-drop instead of the default move-drop.
    toggle_on_release: bool,
}

/// Build the right-click context-menu items for an editor tab strip
/// click on tab `idx`. `tab_count` is the total number of open tabs;
/// used to gate "Close Others" / "Close to the Right" so they don't
/// surface when they would be no-ops.
fn build_tab_context_menu_items(
    idx: usize,
    tab_count: usize,
    is_split: bool,
    clicked: Option<&Path>,
    reveal_enabled: bool,
    clicked_is_preview: bool,
    clicked_is_pinned: bool,
) -> Vec<MenuEntry> {
    let mut items: Vec<MenuEntry> = Vec::new();
    items.push(MenuEntry::item("Close", MenuAction::CloseTab(idx)));
    if tab_count > 1 {
        items.push(MenuEntry::item(
            "Close Others",
            MenuAction::CloseOtherTabs(idx),
        ));
    }
    if idx + 1 < tab_count {
        items.push(MenuEntry::item(
            "Close to the Right",
            MenuAction::CloseTabsToRight(idx),
        ));
    }
    if tab_count > 1 {
        items.push(MenuEntry::item("Close Saved", MenuAction::CloseSavedTabs));
    }
    items.push(MenuEntry::item("Close All", MenuAction::CloseAllTabs));
    // Copy Path: any tab backed by a real on-disk path, local or remote (it's
    // a clipboard write, not a host bridge). Sits between the close group and
    // Reveal in Finder, mirroring VS Code's tab-menu order.
    if let Some(path) = clicked {
        items.push(MenuEntry::item(
            "Copy Path",
            MenuAction::CopyTabPath(path.to_path_buf()),
        ));
        items.push(MenuEntry::item(
            "Copy Relative Path",
            MenuAction::CopyTabRelativePath(path.to_path_buf()),
        ));
    }
    // Reveal in Finder: local-macOS only, and only when the tab is backed by a
    // real on-disk path (a blank/untitled buffer has nothing to reveal). On a
    // remote SSH session the entry is withheld, matching the explorer menu.
    if let Some(path) = clicked.filter(|_| reveal_enabled) {
        items.push(MenuEntry::item(
            "Reveal in Finder",
            MenuAction::RevealInFinder(path.to_path_buf()),
        ));
    }
    // Reveal in Explorer View: select the file in croft's own tree. The tree
    // exists local and remote, so this is gated only on a real path.
    if let Some(path) = clicked {
        items.push(MenuEntry::item(
            "Reveal in Explorer View",
            MenuAction::RevealInExplorer(path.to_path_buf()),
        ));
    }
    // Keep Open: only meaningful for the replaceable preview tab (italic).
    // Promotes it so a subsequent single-click open won't replace it. VS Code
    // omits the entry on an already-permanent tab, so we do too.
    if clicked_is_preview {
        items.push(MenuEntry::item("Keep Open", MenuAction::KeepTabOpen(idx)));
    }
    // Pin / Unpin: always offered. A pinned tab reads "Unpin"; pinning keeps it
    // leftmost and shields it from Close Others / Close to the Right.
    items.push(MenuEntry::item(
        if clicked_is_pinned { "Unpin" } else { "Pin" },
        MenuAction::ToggleTabPin(idx),
    ));
    // A top-level "Split Right" (the common case), then a "Split & Move"
    // submenu holding every directional split, the four directional moves, and
    // Split in Group — mirroring VS Code's tab menu.
    items.push(MenuEntry::item("Split Right", MenuAction::SplitEditor));
    items.push(MenuEntry::Submenu {
        label: String::from("Split & Move"),
        items: vec![
            MenuEntry::item("Split Up", MenuAction::SplitEditorUp),
            MenuEntry::item("Split Down", MenuAction::SplitEditorDown),
            MenuEntry::item("Split Left", MenuAction::SplitEditorLeft),
            MenuEntry::item("Split Right", MenuAction::SplitEditor),
            MenuEntry::Separator,
            // VS Code's vertical labels: Above = Up, Below = Down.
            MenuEntry::item("Move Above", MenuAction::MoveEditorUp),
            MenuEntry::item("Move Below", MenuAction::MoveEditorDown),
            MenuEntry::item("Move Left", MenuAction::MoveEditorLeft),
            MenuEntry::item("Move Right", MenuAction::MoveEditorRight),
            MenuEntry::Separator,
            MenuEntry::item("Split in Group", MenuAction::SplitInGroup),
        ],
    });
    // VS Code's "Move into New Window" / "Copy into New Window". croft has no
    // OS windows, so a "window" is a full-screen, chrome-free editor surface
    // (Esc returns). Move works on any buffer (it carries the editor itself);
    // Copy reopens the file, so it needs a real on-disk path.
    items.push(MenuEntry::item(
        "Move into New Window",
        MenuAction::MoveIntoNewWindow(idx),
    ));
    if clicked.is_some() {
        items.push(MenuEntry::item(
            "Copy into New Window",
            MenuAction::CopyIntoNewWindow(idx),
        ));
    }
    // Focus-group navigation appears once a second group exists.
    if is_split {
        items.push(MenuEntry::item(
            "Focus Left Group",
            MenuAction::FocusGroupLeft,
        ));
        items.push(MenuEntry::item(
            "Focus Right Group",
            MenuAction::FocusGroupRight,
        ));
    }
    items
}

/// Build the right-click context-menu items for the explorer.
///
/// * Right-click on an entry (file or non-root folder) → entry-scoped
///   actions: Cut, Copy, Paste, Rename, Delete. Multi-select promotes
///   Delete to a count and keeps Rename on a single entry only.
/// * Right-click on empty tree space, or on the workspace root row →
///   workspace-scoped actions: New File, New Folder, Paste.
///
/// Test-side entry with no viewer lookup, so a viewer installed on the host
/// can never reach the built-in rows these tests assert; the app itself goes
/// through [`build_tree_context_menu_items_in_dir`] with the dir it carries.
#[cfg(test)]
fn build_tree_context_menu_items(
    node: Option<&crate::widgets::file_tree::Node>,
    root: &Path,
    selection: &[PathBuf],
    target_dir: &Path,
    clipboard: Option<&ExplorerClipboard>,
    compare_anchor: Option<&Path>,
) -> Vec<(String, MenuAction)> {
    // No viewer lookup at all: these tests assert the built-in rows, so the
    // lookup must find nothing whatever the host has installed.
    build_tree_context_menu_items_with(
        node,
        root,
        selection,
        target_dir,
        clipboard,
        compare_anchor,
        |_| None,
    )
}

/// [`build_tree_context_menu_items`] reading the viewers under an explicit
/// config dir: the app passes the dir it carries, so the row it builds and
/// the click that resolves the row read the same extensions.
fn build_tree_context_menu_items_in_dir(
    config_dir: &Path,
    node: Option<&crate::widgets::file_tree::Node>,
    root: &Path,
    selection: &[PathBuf],
    target_dir: &Path,
    clipboard: Option<&ExplorerClipboard>,
    compare_anchor: Option<&Path>,
) -> Vec<(String, MenuAction)> {
    build_tree_context_menu_items_with(
        node,
        root,
        selection,
        target_dir,
        clipboard,
        compare_anchor,
        |file| {
            crate::mcp::registry::viewer_for_path_in_dir(config_dir, file)
                .map(|v| (v.label.clone(), v.key()))
        },
    )
}

/// [`build_tree_context_menu_items`] with the viewer lookup injected (#465):
/// `viewer_for` answers "which installed viewer handles this file", as
/// `(label, id)`, so a test can offer one without an extensions dir.
fn build_tree_context_menu_items_with(
    node: Option<&crate::widgets::file_tree::Node>,
    root: &Path,
    selection: &[PathBuf],
    target_dir: &Path,
    clipboard: Option<&ExplorerClipboard>,
    compare_anchor: Option<&Path>,
    viewer_for: impl Fn(&Path) -> Option<(String, String)>,
) -> Vec<(String, MenuAction)> {
    let entry_target = crate::widgets::file_tree::delete_target_for(node, root);
    let mut items: Vec<(String, MenuAction)> = Vec::new();
    if let Some(p) = entry_target {
        // Right-click on any node (file or folder, nested or not):
        // surface New File… / New Folder… at the top so the user can
        // create a new entry next to / inside whatever they clicked,
        // without having to scroll up to the workspace root first.
        // `target_dir` is already routed by `create_target_dir_for`:
        // a folder click resolves to the folder itself, a file click
        // to the file's parent — same convention VS Code uses.
        items.push((
            String::from("New File"),
            MenuAction::Create(CreateKind::File),
        ));
        items.push((
            String::from("New Folder"),
            MenuAction::Create(CreateKind::Folder),
        ));
        let paths_for_action: Vec<PathBuf> = if selection.iter().any(|sp| sp == &p) {
            selection.to_vec()
        } else {
            vec![p.clone()]
        };
        items.push((
            String::from("Cut"),
            MenuAction::Cut(paths_for_action.clone()),
        ));
        items.push((
            String::from("Copy"),
            MenuAction::Copy(paths_for_action.clone()),
        ));
        if clipboard.is_some() {
            items.push((
                String::from("Paste"),
                MenuAction::Paste(target_dir.to_path_buf()),
            ));
        }
        if paths_for_action.len() == 1 {
            items.push((String::from("Rename"), MenuAction::Rename(p.clone())));
        }
        // Compare actions only make sense for a single regular file.
        let single_file_target = paths_for_action
            .first()
            .filter(|_| paths_for_action.len() == 1)
            .filter(|pp| pp.is_file());
        if let Some(file) = single_file_target {
            // An installed viewer for this file kind (#465): `Open in csvlens`
            // on a .csv, once the csvlens extension has been added.
            if let Some((label, id)) = viewer_for(file) {
                items.push((label, MenuAction::OpenInViewer(id, file.clone())));
            }
            match compare_anchor {
                Some(anchor) if anchor != file.as_path() => {
                    items.push((
                        format!(
                            "Compare with Selected ({})",
                            anchor
                                .file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_else(|| anchor.display().to_string()),
                        ),
                        MenuAction::CompareWithSelected {
                            anchor: anchor.to_path_buf(),
                            other: file.clone(),
                        },
                    ));
                }
                _ => {}
            }
            items.push((
                String::from("Select for Compare"),
                MenuAction::SelectForCompare(file.clone()),
            ));
        }
        // Two regular files selected: offer a direct diff between them,
        // skipping the two-step Select-for-Compare anchor dance. Folders
        // can't be diffed, so any folder in the selection suppresses it.
        if paths_for_action.len() == 2 && paths_for_action.iter().all(|p| p.is_file()) {
            items.push((
                String::from("Compare Selected"),
                MenuAction::CompareWithSelected {
                    anchor: paths_for_action[0].clone(),
                    other: paths_for_action[1].clone(),
                },
            ));
        }
        // "Make root" appears only for non-root folders. Re-roots the
        // workspace at the clicked folder so the user can dive into a
        // nested git repo without relaunching croft.
        let single_folder_target: Option<&PathBuf> = paths_for_action
            .first()
            .filter(|_| paths_for_action.len() == 1)
            .filter(|_| node.map(|n| n.is_dir).unwrap_or(false))
            .filter(|pp| pp.as_path() != root);
        if let Some(folder) = single_folder_target {
            items.push((
                String::from("Make root"),
                MenuAction::MakeRoot(folder.clone()),
            ));
        }
        let label = if paths_for_action.len() > 1 {
            format!("Delete {} items", paths_for_action.len())
        } else {
            String::from("Delete")
        };
        items.push((
            label,
            MenuAction::Delete {
                paths: paths_for_action,
            },
        ));
    } else {
        items.push((
            String::from("New File"),
            MenuAction::Create(CreateKind::File),
        ));
        items.push((
            String::from("New Folder"),
            MenuAction::Create(CreateKind::Folder),
        ));
        // Root section rows (multi-root, #147): grow the folder set from
        // any root row; drop a SECONDARY root from its own row. The
        // primary is the launch identity — Make Root changes it, never a
        // removal.
        if let Some(n) = node.filter(|n| n.depth == 0) {
            items.push((
                String::from("Add Folder to Workspace"),
                MenuAction::AddWorkspaceFolder,
            ));
            if n.path != root {
                items.push((
                    String::from("Remove Folder from Workspace"),
                    MenuAction::RemoveWorkspaceFolder(n.path.clone()),
                ));
            }
        }
        if clipboard.is_some() {
            items.push((
                String::from("Paste"),
                MenuAction::Paste(target_dir.to_path_buf()),
            ));
        }
    }
    items
}

/// Insert "Reveal in Finder" into a freshly-built tree context menu, but only
/// when the action can actually do something: `enabled` is true (a local macOS
/// session) and a concrete entry was clicked (`clicked`). On a remote SSH
/// session croft runs on the headless host where there is no Finder, so the
/// item is omitted entirely rather than shown as a dead no-op, keeping the
/// local and remote menus honest. The entry lands directly beneath the New
/// File / New Folder block to mirror VS Code's top "reveal" placement.
fn maybe_add_reveal_in_finder(
    items: &mut Vec<(String, MenuAction)>,
    clicked: Option<&Path>,
    enabled: bool,
) {
    let Some(path) = clicked.filter(|_| enabled) else {
        return;
    };
    // Insert directly after the leading New File / New Folder block: find the
    // first non-Create entry and slot in ahead of it. Deriving the position
    // this way (rather than a literal index) keeps the placement correct even
    // if the Create block grows or the empty-area menu shape changes.
    let pos = items
        .iter()
        .position(|(_, a)| !matches!(a, MenuAction::Create(_)))
        .unwrap_or(items.len());
    items.insert(
        pos,
        (
            String::from("Reveal in Finder"),
            MenuAction::RevealInFinder(path.to_path_buf()),
        ),
    );
}

/// One row of a context menu: a clickable action, a parent that opens a nested
/// submenu, or a divider. Most menus are a flat list of `Item`s; the editor tab
/// menu uses a `Submenu` ("Split & Move") whose children include `Separator`s.
#[derive(Clone, Debug)]
enum MenuEntry {
    Item {
        label: String,
        action: MenuAction,
    },
    Submenu {
        label: String,
        items: Vec<MenuEntry>,
    },
    Separator,
    /// A dimmed, non-selectable section label (e.g. "Side Bar Position" in the
    /// Customize Layout popup). The cursor skips it like a `Separator`.
    Header(String),
}

impl MenuEntry {
    fn item(label: impl Into<String>, action: MenuAction) -> Self {
        Self::Item {
            label: label.into(),
            action,
        }
    }

    fn header(label: impl Into<String>) -> Self {
        Self::Header(label.into())
    }

    /// The action a click on this entry dispatches, if it is a plain item.
    fn action(&self) -> Option<&MenuAction> {
        match self {
            Self::Item { action, .. } => Some(action),
            _ => None,
        }
    }

    /// True for a row the cursor may land on (items and submenu parents, not
    /// dividers or section headers).
    fn is_selectable(&self) -> bool {
        !matches!(self, Self::Separator | Self::Header(_))
    }
}

impl From<(String, MenuAction)> for MenuEntry {
    fn from((label, action): (String, MenuAction)) -> Self {
        Self::Item { label, action }
    }
}

struct ContextMenu {
    /// Top-left of the menu in absolute terminal coordinates.
    origin: (u16, u16),
    /// Items, in display order.
    items: Vec<MenuEntry>,
    /// Highlighted top-level row.
    selected: usize,
    /// Index into `items` of the currently open submenu (a `Submenu` entry), or
    /// `None` when no submenu is open.
    open_submenu: Option<usize>,
    /// Highlighted row WITHIN the open submenu (only meaningful when
    /// `open_submenu` is `Some`).
    submenu_selected: usize,
    /// Where any New File / New Folder should be created.
    target_dir: PathBuf,
}

impl ContextMenu {
    /// A flat menu from `(label, action)` tuples (the common case).
    fn flat(origin: (u16, u16), items: Vec<(String, MenuAction)>, target_dir: PathBuf) -> Self {
        Self {
            origin,
            items: items.into_iter().map(MenuEntry::from).collect(),
            selected: 0,
            open_submenu: None,
            submenu_selected: 0,
            target_dir,
        }
    }

    /// The entries at the active level: the open submenu's children, or the
    /// top-level items.
    fn level_entries(&self) -> &[MenuEntry] {
        match self.open_submenu {
            Some(i) => match &self.items[i] {
                MenuEntry::Submenu { items, .. } => items,
                _ => &self.items,
            },
            None => &self.items,
        }
    }

    fn level_selected(&self) -> usize {
        if self.open_submenu.is_some() {
            self.submenu_selected
        } else {
            self.selected
        }
    }

    fn set_level_selected(&mut self, idx: usize) {
        if self.open_submenu.is_some() {
            self.submenu_selected = idx;
        } else {
            self.selected = idx;
        }
    }

    /// Move the cursor up/down within the active level, skipping dividers and
    /// stopping at the ends.
    fn move_cursor(&mut self, down: bool) {
        let entries = self.level_entries();
        let n = entries.len();
        let mut i = self.level_selected();
        loop {
            i = if down {
                if i + 1 >= n {
                    return;
                }
                i + 1
            } else {
                if i == 0 {
                    return;
                }
                i - 1
            };
            if entries[i].is_selectable() {
                self.set_level_selected(i);
                return;
            }
        }
    }

    /// The entry currently under the cursor at the active level.
    fn cursor_entry(&self) -> Option<&MenuEntry> {
        self.level_entries().get(self.level_selected())
    }

    /// The action a cursor-on-item Enter/click dispatches (None on a submenu
    /// parent or divider).
    fn cursor_action(&self) -> Option<MenuAction> {
        match self.cursor_entry() {
            Some(MenuEntry::Item { action, .. }) => Some(action.clone()),
            _ => None,
        }
    }

    /// If the top-level cursor is on a submenu parent (and none is open yet),
    /// open it, selecting its first selectable child. Returns true when opened.
    fn open_cursor_submenu(&mut self) -> bool {
        if self.open_submenu.is_some() {
            return false;
        }
        if let Some(MenuEntry::Submenu { items, .. }) = self.items.get(self.selected) {
            self.submenu_selected = items.iter().position(MenuEntry::is_selectable).unwrap_or(0);
            self.open_submenu = Some(self.selected);
            return true;
        }
        false
    }

    /// Close any open submenu, returning to the top level. Returns true when a
    /// submenu was actually open.
    fn close_submenu(&mut self) -> bool {
        if self.open_submenu.take().is_some() {
            self.submenu_selected = 0;
            return true;
        }
        false
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
enum PromptKind {
    Create(CreateKind),
    /// Rename the entry at `path`. The prompt's `target_dir` holds the
    /// entry's parent; `buffer` is pre-filled with the current basename.
    Rename(PathBuf),
    /// LSP "Rename Symbol" (F2 in the editor): rename the identifier at
    /// `(row, col)` in `path`. `buffer` is pre-filled with the symbol; on
    /// commit the new name drives a `textDocument/rename` request.
    RenameSymbol {
        path: PathBuf,
        row: usize,
        col: usize,
    },
    /// Debugger "Add Conditional Breakpoint" / "Edit Condition": edit the
    /// boolean condition for the breakpoint on 1-based `line` of `path`. The
    /// buffer is pre-filled with any existing condition; on commit the
    /// breakpoint is created (if absent) and the condition attached/cleared,
    /// then pushed to a live session. A popup, never the status line.
    BreakpointCondition {
        path: PathBuf,
        line: usize,
    },
    /// Debugger "Add Logpoint" / "Edit Logpoint": edit the log message for
    /// the breakpoint on 1-based `line` of `path` (`{expr}` holes are
    /// interpolated by the adapter, which prints instead of pausing). Same
    /// commit shape as [`PromptKind::BreakpointCondition`].
    Logpoint {
        path: PathBuf,
        line: usize,
    },
    /// Rename the terminal pane at `idx`. The buffer is pre-filled with its
    /// current label; on commit the name overrides the auto label.
    RenameTerminal(usize),
    /// Annotate a span of terminal output on pane `pane` (Cmd+K N with a
    /// selection). `existing` edits that annotation in place; otherwise
    /// `line`/`start`/`len` pin a new one. A blank commit cancels (or, for
    /// an existing note, deletes it).
    AnnotateTerminal {
        pane: usize,
        line: i32,
        /// Scroll-clock reading `line` was captured against when the prompt
        /// OPENED. The commit anchors with this pair: sampling a fresh
        /// baseline at commit would mis-pin the note by every row that
        /// streamed while the user typed it.
        clock: i64,
        start: u16,
        len: u16,
        existing: Option<usize>,
    },
}

struct Prompt {
    label: String,
    buffer: String,
    kind: PromptKind,
    target_dir: PathBuf,
    error: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingDiscard {
    rel_path: String,
    untracked: bool,
}

/// A revert-hunk request waiting on its confirm popup. Holds the
/// single-hunk patch built when the user pressed R, so the confirm
/// reverse-applies exactly what they were looking at.
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingRevertHunk {
    rel_path: String,
    patch: String,
}

/// Why the branch picker is open, deciding what its Enter does. `Checkout`
/// is the default (click the branch name / "Checkout to"); the others are
/// reached from the Branch submenu and act on the highlighted *existing*
/// branch (or, for `CreateFrom`, use it as the base for a new branch).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BranchPurpose {
    #[default]
    Checkout,
    CreateFrom,
    Delete,
    Merge,
    Rebase,
}

/// The live ssh-pane workspace offer (#364): which pane's foreground became
/// `ssh <host>`, the resolved config alias, and when the offer appeared (it
/// expires on its own if neither accepted nor dismissed).
#[derive(Clone, Debug, PartialEq, Eq)]
struct SshOffer {
    pane: u64,
    host: String,
    since: std::time::Instant,
}

/// A left press forwarded to a mouse-tracking child (#474): which pane got
/// it, the host cell it landed on, and whether the drag since has become
/// croft's own text selection (a child that asked only for clicks cannot use
/// a drag, so croft keeps it). See `App::terminal_pointer_forwarded`.
///
/// The pane is held by its stable `uid`, NOT its index in `App::terminals`:
/// a pane closed while the button is held (the close chord, the header
/// button) shifts every later pane one slot left, and an index would then
/// deliver the release to the neighbour while the child that got the press
/// keeps a button it thinks is still down.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ForwardedPointer {
    pane: u64,
    press: (u16, u16),
    selecting: bool,
}

/// State for edge auto-scroll during a terminal drag-selection. `dir` is
/// -1 (pointer above the top edge, scroll into history) or +1 (below the
/// bottom edge, scroll toward live); `col` is the last drag column so the
/// re-pinned selection head tracks the pointer horizontally; `last` rate-
/// limits the scroll so it advances at a readable speed rather than once
/// per main-loop wakeup.
#[derive(Clone, Copy)]
struct TerminalSelectAutoScroll {
    dir: i32,
    col: u16,
    last: std::time::Instant,
}

/// Active quick-select session on the focused terminal pane: the labelled
/// matches overlaid on the viewport, the label prefix typed so far, and
/// whether any typed char was UPPERCASE (commit then pastes the match into
/// the shell as well as copying it, WezTerm's convention).
pub struct QuickSelectState {
    /// Index into `App::terminals` of the pane the labels were scraped
    /// from: hints, pastes and re-pushes are bound to it, and any gesture
    /// that activates a sibling pane closes the mode (the copy-mode rule).
    pane: usize,
    /// Scroll-clock reading the hint lines were captured at (one snapshot
    /// with the lines themselves); every re-push reuses it so the pane's
    /// render-time translation keeps labels on their scrolled matches.
    clock: i64,
    hints: Vec<QuickHint>,
    typed: String,
    shifted: bool,
}

/// One labelled quick-select match: where it sits (absolute grid line plus
/// char span in the spacer-skipped row text), the text a committed label
/// copies, and the label itself.
#[derive(Clone)]
struct QuickHint {
    line: i32,
    start: usize,
    len: usize,
    text: String,
    label: String,
    /// Continuation segments `(absolute line, start, len)` when the match
    /// wraps the pane edge: highlighted alongside the head span, but the
    /// label glyph only ever paints on the head.
    tail: Vec<(i32, usize, usize)>,
}

/// Active copy-mode session on the focused terminal pane (WezTerm / tmux
/// copy mode): a keyboard cursor over the grid plus the selection anchor
/// and kind once v / V / Ctrl+V arms one. The pane paints the cursor and
/// the selection; this state owns the motions.
pub struct CopyModeState {
    /// Pane index the mode opened on. The coordinates and clock below are
    /// meaningless against any other pane (each pane owns an independent
    /// scroll clock), so a gesture that moves `active_terminal` while the
    /// mode is up closes it instead of hijacking the new pane.
    pane: usize,
    /// Cursor cell: absolute grid line + grid column.
    line: i32,
    col: u16,
    /// Selection anchor cell; `None` until v / V / Ctrl+V arms a selection.
    anchor: Option<(i32, u16)>,
    kind: CopySelKind,
    /// Scroll-clock reading the coordinates above are valid against. The
    /// pane re-anchors its painted selection to streaming content between
    /// keypresses; every key handler folds the clock movement into these
    /// coordinates first, or the keystroke would teleport the highlight
    /// back to the stale absolute lines.
    clock: i64,
}

/// Which shape the copy-mode selection takes: vim's v / V / Ctrl+V.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CopySelKind {
    Char,
    Line,
    Block,
}

/// How long a closed terminal pane stays parked (child alive, hidden)
/// before the tick drops it for real. Ghostty and iTerm2 default their
/// undo-close window to 5s; croft doubles it because the hint lives in a
/// TUI status line that is easier to miss than a native toast.
pub const UNDO_CLOSE_GRACE: std::time::Duration = std::time::Duration::from_secs(10);

/// How many closed editor tabs Cmd+K ⇧W can walk back through.
const CLOSED_TAB_STACK_CAP: usize = 20;

/// A closed editor tab, reopenable via Cmd+K ⇧W (VS Code "Reopen Closed
/// Editor"): the file plus the view state needed to restore the tab as the
/// user left it. Unlike [`ClosedTerminal`] there is no live process to
/// park, so entries never expire; the stack is just bounded.
pub struct ClosedTab {
    pub path: PathBuf,
    pub pinned: bool,
    pub cursor: (usize, usize),
    pub scroll: usize,
}

/// A terminal pane parked by close for the undo-close grace window: the
/// live pane, the slot it occupied (so restore puts it back where it was),
/// and when it was closed (for expiry).
pub struct ClosedTerminal {
    pub term: crate::widgets::terminal::PtyTerminal,
    pub idx: usize,
    pub closed_at: std::time::Instant,
}

/// A `cargo test --no-run` running on a background thread: the receiver for
/// its result, the test's name, and the workspace root it builds for (so a
/// re-root mid-build discards the binary instead of debugging it in the
/// wrong workspace).
type PendingTestDebug = (
    std::sync::mpsc::Receiver<Result<PathBuf, String>>,
    String,
    PathBuf,
);

/// A COMMITS graph reply: the root and revspec it answers, and the rows.
/// Tagged rather than bare so a reply for a since-left root or a superseded
/// view is discarded on drain (#348).
type GraphReply = (
    PathBuf,
    Option<String>,
    Vec<crate::widgets::commit_graph::GraphRow>,
);
type GraphReplyRx = std::sync::mpsc::Receiver<GraphReply>;
type GraphReplyTx = std::sync::mpsc::Sender<GraphReply>;

pub struct App {
    pub tree: FileTree,
    pub search: SearchPanel,
    pub remote: RemotePanel,
    pub source_control: SourceControlPanel,
    /// The Source Control COMMITS section: the repo-wide commit graph with
    /// lane rails, stacked under the change list. See [`CommitGraphPanel`].
    pub commit_graph: crate::widgets::commit_graph::CommitGraphPanel,
    /// Background `git log --topo-order` + lane layout for the COMMITS
    /// section, tagged by the root it describes so a stale reply after a
    /// Make Root is ignored on drain.
    graph_rx: GraphReplyRx,
    graph_tx: GraphReplyTx,
    /// What the COMMITS panel is currently showing: `None` for the root's
    /// own history, `Some("base..lane")` for a worktree lane's diff (#348).
    ///
    /// The reply tag carries this too, so a history refresh landing while a
    /// lane diff is up is discarded rather than replacing it - the panel
    /// already discarded replies for a since-left ROOT, and this is the same
    /// rule at the resolution the lane diff needs.
    graph_revspec: Option<String>,
    /// A graph fetch is running; suppresses duplicate spawns when a burst of
    /// StatusAndChanges responses lands. Cleared when the reply drains.
    graph_fetch_inflight: bool,
    /// A refresh was requested while a fetch was in flight (Make Root, a
    /// newer HEAD): re-fire once the stale reply drains instead of dropping
    /// the request (see [`Self::refresh_commit_graph`]).
    graph_refetch_queued: bool,
    pub run_debug: RunDebugPanel,
    /// The Testing side panel: the suite tree with live pass/fail status.
    pub testing: crate::widgets::testing::TestingPanel,
    /// Background `cargo test` worker feeding the Testing panel.
    test_worker: crate::testing::worker::TestWorker,
    /// The Extensions side panel: bundled + installed extensions with toggles.
    pub extensions: crate::widgets::extensions::ExtensionsPanel,
    /// Extension ids VS Code reported installed, from the last
    /// "Extensions: Compare with VS Code" (#352). Empty until the user asks,
    /// since listing them spawns `code`. Workspace recommendations are read
    /// from `.vscode/extensions.json` on every refresh instead.
    pub vscode_listed: Vec<String>,
    /// The Explorer's OPEN EDITORS section: the open editor tabs, projected
    /// from the active `editor` group each frame. See [`OpenEditorsPanel`].
    pub open_editors: OpenEditorsPanel,
    /// The Explorer's OUTLINE section, stacked below the file tree: the active
    /// editor's `documentSymbol` tree. See [`OutlinePanel`].
    pub outline: OutlinePanel,
    /// The Explorer's TIMELINE section: the active file's git history, fetched
    /// off-thread via [`crate::git::file_history`]. See [`TimelinePanel`].
    pub timeline: TimelinePanel,
    /// The Explorer's DEPENDENCIES section: the workspace's packages, resolved
    /// off-thread per detected ecosystem. See [`DependenciesPanel`].
    pub dependencies: DependenciesPanel,
    /// Package ecosystems detected at the workspace root (by manifest file),
    /// recomputed on every re-root. Empty means no recognised manifest, which
    /// hides the DEPENDENCIES section entirely and drops it from the ⋯ menu —
    /// the rule every reference editor follows. Drives the section's header
    /// label too. Cached so the cheap detection never runs on the render path.
    dep_ecosystems: Vec<Ecosystem>,
    /// Which Explorer sub-views are shown, toggled from the ⋯ menu. Persisted.
    pub explorer_views: ExplorerViewVisibility,
    /// Every file of the layered-settings chain (#251), for hot-reload
    /// matching on save; rebuilt by `remerge_settings`.
    settings_chain: Vec<PathBuf>,
    /// Which layer set each top-level settings key, for the hub's
    /// provenance suffix ("· workspace").
    settings_provenance: std::collections::BTreeMap<String, crate::config_layers::LayerKind>,
    /// Extension ids the user has disabled in the Extensions panel. Loaded once
    /// from prefs at startup and persisted on every toggle, mirroring how
    /// `explorer_views` is held in memory rather than re-read each access. The
    /// gates for the bundled features (PDF/CSV/Vim/LSPs) consult this set.
    disabled_extensions: std::collections::BTreeSet<String>,
    /// User key bindings from `~/.config/croft/keybindings.json`, consulted
    /// ahead of the built-in chords so a rebind wins over the default.
    keymap: crate::keymap::Keymap,
    /// Live macro recording (#255), `None` when not recording. Carries the
    /// vim register it will be stored under, or `None` for the palette
    /// recorder, whose macro is the unnamed "last recording".
    macro_recording: Option<crate::macros::Recording>,
    /// The most recent finished recording: what "Replay Last" and vim's `@@`
    /// run, and what a `q` with no register stores into.
    macro_last: Option<crate::macros::Macro>,
    /// Named registers (`qa` … `q`), loaded from macros.json at startup.
    macro_registers: std::collections::HashMap<String, crate::macros::Macro>,
    /// True while a replay is feeding keys back through `handle_key`, so a
    /// replayed key is never recorded and a macro cannot invoke itself.
    macro_replaying: bool,
    /// The store path, held so tests can point saves at a tempdir.
    macros_path: std::path::PathBuf,
    /// The click a user mouse binding is running for (#259), set only for
    /// the duration of that dispatch. Position-carrying commands read it;
    /// `None` everywhere else, so a keyboard invocation of the same command
    /// can never act on a stale click.
    last_mouse_pos: Option<(u16, u16)>,
    /// User snippets from `~/.config/croft/snippets.json`. Typing a snippet's
    /// prefix and pressing Tab expands it with tab-stop navigation.
    snippets: crate::snippets::SnippetSet,
    /// VS Code `editor.formatOnSave`: when true, `Cmd+S` first asks the language
    /// server to format the buffer, then writes once the reply lands. Loaded
    /// from prefs at startup, toggled from the palette / `Cmd+K F`.
    format_on_save: bool,
    /// VS Code `terminal.integrated.copyOnSelection`: a finished terminal
    /// mouse selection lands on the clipboard without an explicit Cmd+C.
    /// Loaded from prefs at startup, toggled in the Settings hub.
    copy_on_select: bool,
    /// Tailspin highlighting in rendered log views (#466): the inverse of
    /// the `disable_log_highlight` preference. Pushed into `log_view`'s
    /// default for views opened later and into every open view on toggle.
    log_highlight: bool,
    /// Built-in secret redaction rules are in the trigger set (#360).
    /// Settings "Terminal: Redact Secrets"; stored inverted in config.json
    /// as `disable_secret_redaction` so the default is on.
    secret_redaction: bool,
    /// "Terminal: Reveal Redacted Secrets": masks paint as their real text
    /// until this instant, then mask again on the next frame.
    redaction_reveal_until: Option<std::time::Instant>,
    /// VS Code's `files.autoSave: afterDelay`: dirty buffers write
    /// themselves to disk once the delay elapses after the last edit.
    auto_save: bool,
    /// VS Code's `files.autoSave: onFocusChange`: a dirty buffer writes
    /// itself the moment it loses focus. Independent of `auto_save`.
    pub auto_save_on_focus_change: bool,
    /// The focus signature (pane, group, active path) seen by the last
    /// auto-save tick. A change means something lost focus, which is the
    /// only trigger `onFocusChange` fires on. `None` until the first tick
    /// so opening croft never writes anything on its own.
    last_focus_signature: Option<(usize, usize, Option<PathBuf>)>,
    /// Latch set while a save is waiting on a format reply. `drain_lsp_format`
    /// consumes it to write the (now formatted) buffer to disk.
    save_after_format: Option<PathBuf>,
    /// Background `git log` results for the TIMELINE, keyed by the file they
    /// describe so a stale reply for a since-closed file is ignored on drain.
    timeline_rx: std::sync::mpsc::Receiver<(PathBuf, Vec<crate::git::FileHistoryEntry>)>,
    timeline_tx: std::sync::mpsc::Sender<(PathBuf, Vec<crate::git::FileHistoryEntry>)>,
    /// The file the TIMELINE has been fetched (or is being fetched) for, so the
    /// fetch fires exactly once per active-file change.
    timeline_fetched: Option<PathBuf>,
    /// Off-thread per-line git blame for the active editor (GitLens-style
    /// inline annotation). Fetched once per (file, HEAD) like the gutter.
    blame_rx: std::sync::mpsc::Receiver<(PathBuf, Vec<crate::git::BlameLine>)>,
    blame_tx: std::sync::mpsc::Sender<(PathBuf, Vec<crate::git::BlameLine>)>,
    /// The file blame has been fetched (or is in flight) for; reset to `None`
    /// on HEAD move so the annotation refreshes after a commit / checkout.
    blame_fetched: Option<PathBuf>,
    /// User pref: show the current-line inline blame annotation (default on).
    inline_blame_enabled: bool,
    /// The provenance lens (#349): who typed each line, in the gutter and
    /// the blame annotation. Session-only for now; the persisted half of
    /// #349 (the map beside local history) is a later slice. Pushed onto
    /// every editor in every group by `sync_focus_flags`, since the gutter
    /// bar paints in every pane, not only the focused one.
    provenance_overlay: bool,
    /// Indentation guides (#129), VS Code `editor.guides.indentation`: on by
    /// default, pushed to every editor by the per-frame focus sync.
    indent_guides_enabled: bool,
    /// Bracket-pair colorization (#131): on by default, pushed to every
    /// editor by the per-frame focus sync like the indent guides.
    bracket_colors_enabled: bool,
    /// Whitespace rendering mode (#133), frame-synced to every editor;
    /// "selection" by default, the palette command cycles it.
    whitespace_mode: crate::widgets::editor::WhitespaceMode,
    /// Default ignore-whitespace mode applied to newly opened diffs (#258).
    diff_ws_default: crate::widgets::diff::DiffWhitespace,
    /// Debugger inline values (#135): on by default; rebuilt on every
    /// `InspectionUpdated`, cleared wherever the stop arrow clears.
    inline_values_enabled: bool,
    /// Auto-closing pairs (#121), persisted; synced onto the active editor
    /// beside the blame flag.
    auto_close_pairs: bool,
    /// LSP inlay hints (inline type / parameter annotations), on by default
    /// like VS Code's `editor.inlayHints.enabled`; toggled from the palette
    /// and persisted as `disable_inlay_hints` in config.json.
    inlay_hints_enabled: bool,
    /// Local-history root (`~/.config/croft/history`), cached so tests can
    /// redirect snapshots to a tempdir.
    history_root: PathBuf,
    /// The snapshot currently shown in a local-history diff, `(live file,
    /// snapshot millis, snapshot contents)`, so "Local History: Restore
    /// Snapshot" can write it back and carry its seats (#349). Cleared when a
    /// non-snapshot diff opens.
    history_restore: Option<(PathBuf, u64, Vec<u8>)>,
    /// Completed off-thread history recordings, drained to refresh the
    /// TIMELINE once the snapshot actually exists on disk.
    history_done_rx: std::sync::mpsc::Receiver<PathBuf>,
    history_done_tx: std::sync::mpsc::Sender<PathBuf>,
    /// The whole-project check's result: where it ran, and what the process
    /// did (#256). The `io::Result` carries a spawn failure separately from
    /// a run that produced output, because those need different messages.
    #[allow(clippy::type_complexity)]
    project_check_rx: std::sync::mpsc::Receiver<(PathBuf, std::io::Result<std::process::Output>)>,
    #[allow(clippy::type_complexity)]
    project_check_tx: std::sync::mpsc::Sender<(PathBuf, std::io::Result<std::process::Output>)>,
    /// Whether a sweep is in flight, so a second invocation says so rather
    /// than stacking compilers.
    project_check_running: bool,
    /// How many rows the last sweep produced (#256), counted before its
    /// items join a store shared with every other producer.
    project_check_rows: usize,
    /// Whether the sweep may run unasked (#256): `auto`, `on` or `off`.
    /// Read at startup; an unrecognised value behaves as `auto`.
    problems_project_scope: String,
    /// Signals that this workspace is too large for `auto` to run the sweep
    /// unasked (#256). Sent from the sweep's worker, since deciding it is a
    /// whole-workspace walk.
    project_hint_rx: std::sync::mpsc::Receiver<()>,
    project_hint_tx: std::sync::mpsc::Sender<()>,
    /// One hint per session, not per run: repeating it every sweep would
    /// train the user to ignore the status line.
    project_check_hinted: bool,
    /// Replies from the background test-source locator (the workspace grep is
    /// too slow for the render thread): the root the search ran under, the
    /// test name, and the hit. A reply from before a re-root is dropped.
    #[allow(clippy::type_complexity)]
    test_jump_rx: std::sync::mpsc::Receiver<(PathBuf, String, Option<(PathBuf, u32)>)>,
    #[allow(clippy::type_complexity)]
    test_jump_tx: std::sync::mpsc::Sender<(PathBuf, String, Option<(PathBuf, u32)>)>,
    /// Background per-ecosystem dependency-resolution result for DEPENDENCIES.
    deps_rx: std::sync::mpsc::Receiver<Vec<Dependency>>,
    deps_tx: std::sync::mpsc::Sender<Vec<Dependency>>,
    /// The workspace root DEPENDENCIES was detected/fetched for, so detection
    /// and the fetch fire once per root (re-fired by Make Root / re-root).
    deps_fetched: Option<PathBuf>,
    /// Push-to-talk voice input (Termux OSK mic). The worker streams its
    /// transcript over this channel; `voice_handle` lets the mic release kill
    /// the in-flight recognizer.
    voice_rx: std::sync::mpsc::Receiver<crate::voice::VoiceMsg>,
    voice_tx: std::sync::mpsc::Sender<crate::voice::VoiceMsg>,
    voice_handle: Option<crate::voice::VoiceHandle>,
    /// Set when a mic tap cancels a live session, so the resulting empty result
    /// is reported as "canceled" rather than "no speech detected".
    voice_canceling: bool,
    pub editor: EditorTabs,
    /// The editor group layout tree. `editor` (above) is ALWAYS the active
    /// (focused) group, hoisted out of the tree's single active leaf, so the
    /// 430-odd `self.editor` call sites keep operating on whichever group has
    /// focus. The tree holds every OTHER group plus the spatial split
    /// structure; a single unsplit leaf is the just-launched state. Splitting,
    /// moving focus, and collapsing all go through [`editor_layout`].
    pub editor_layout: editor_layout::EditorLayout,
    /// One-shot latch armed when a save is refused because the file changed
    /// on disk. The next `save()` overwrites anyway, giving the user a
    /// "press Cmd+S again to overwrite" escape hatch without a modal.
    force_save_armed: bool,
    pub terminals: Vec<PtyTerminal>,
    pub active_terminal: usize,
    perf: PerfHud,
    /// The workspace's root-folder set (#143). One entry today; the
    /// multi-root slices grow it. Read the primary via `workspace_root()`.
    roots: crate::workspace::WorkspaceRoots,
    sidebar_view: SidebarView,
    sidebar_areas: SidebarAreas,
    /// Active IDE color theme. Drives every explicit-background surface
    /// (baked icon PNGs, editor image/sheet/diff canvases, the `SetColors`
    /// session fill); `Color::Reset` surfaces follow the session bg for free.
    /// Toggled from the activity-bar gear menu; persisted via `crate::prefs`.
    theme: crate::theme::Theme,
    focus: Pane,
    show_tree: bool,
    show_terminal: bool,
    /// `Ctrl+Shift+J` maximizes the terminal pane: the editor / welcome
    /// collapses to zero height and the terminal fills the entire right
    /// column next to the Explorer. Pressing the chord again, or hiding
    /// the terminal entirely with `Ctrl+J`, clears the flag.
    terminal_maximized: bool,
    /// Layout (Customize Layout popup): whether the left activity bar is
    /// shown. Persisted via `crate::prefs`.
    activity_bar_visible: bool,
    /// Layout: whether the bottom status bar is shown. Persisted.
    status_bar_visible: bool,
    /// Layout: which edge the primary side bar (+ activity bar) docks to.
    /// Persisted.
    side_bar_position: SideBarPosition,
    /// Layout: whether the secondary side bar (the active file's Outline) is
    /// shown, on the edge opposite the primary side bar (⌥⌘B). Persisted.
    secondary_side_bar_visible: bool,
    /// Layout: horizontal span/alignment of the bottom panel. Persisted.
    panel_alignment: PanelAlignment,
    /// Layout: where the quick input (command palette / Go to File) anchors.
    /// Persisted.
    quick_input_position: QuickInputPosition,
    /// Layout: Zen Mode hides the activity bar, both side bars, the panel,
    /// and the status bar; toggling off restores `pre_zen`.
    zen_mode: bool,
    /// Auto-hide the sidebar when focus moves to the editor or a terminal
    /// (#260, `sidebar_auto_hide`). Off by default. The sidebar comes back
    /// on any deliberate sidebar action — Cmd+B, an activity-bar icon, or a
    /// sidebar-targeting command like reveal-in-explorer.
    sidebar_auto_hide: bool,
    /// Set while a focus move is happening for a reason other than the user
    /// asking for it (async results, launch, sidebar-internal activation).
    sidebar_auto_hide_suspended: bool,
    /// One-shot exemption: the next auto-hide collapse is skipped and the
    /// flag consumed. Cmd+B reveals the sidebar WITHOUT moving focus, so a
    /// sticky flag would stay set (focus never lands on the tree to clear
    /// it) and silently disable auto-hide for the rest of the session.
    /// Consuming it on the next attempt keeps the reveal usable while
    /// guaranteeing the feature re-arms itself.
    sidebar_pinned_open: bool,
    /// Grace delay between focus leaving the sidebar and auto-hide collapsing
    /// it (#302), so a click passing through the panel does not take it away
    /// under the pointer.
    sidebar_dwell: SidebarDwell,
    /// Pre-Zen visibility snapshot; `None` whenever not in Zen Mode.
    pre_zen: Option<PreZenLayout>,
    /// Hit-test rects for the top-right layout-control icons.
    layout_icon_areas: LayoutIconAreas,
    status: String,
    /// Orange status-bar badge shown for the whole session when this is a
    /// remote (SSH) croft not running under dtach, so it can't survive a
    /// transport drop. Set once at startup; rendered separately from `status`
    /// so transient messages never clobber it. `None` otherwise.
    persistence_warning: Option<&'static str>,
    quit: bool,
    drop_to_local: bool,
    is_remote: bool,
    context_menu: Option<ContextMenu>,
    prompt: Option<Prompt>,
    fs_watch: FsWatch,
    /// One extra watcher per SECONDARY workspace root (#147), sharing the
    /// primary's watch-cap budget. The primary `fs_watch` also owns the
    /// adaptive poll (its dir-mtime snapshot walks the whole tree, all
    /// roots included) and the open-file stats; extras are event-only.
    fs_watch_extra: Vec<FsWatch>,
    /// One git worker per SECONDARY workspace root (#149), keyed by the
    /// root path. `git` stays the primary's worker. Each discovers its
    /// own repo toplevel; replies are root-scoped by construction.
    git_extra: Vec<(PathBuf, GitWorker)>,
    /// The workspace root whose repository the Source Control panel and
    /// the status line follow: the root owning the focused editor's
    /// file, falling back to the primary. Recomputed each drain tick; a
    /// change re-seeds the panel from that worker and re-requests its
    /// change list.
    active_scm_root: PathBuf,
    /// A repositories-overview click pins the panel to that folder's repo
    /// (#161); the pin clears when the FOCUS-derived folder changes, so
    /// the panel resumes following the file the user works in.
    scm_pin: Option<PathBuf>,
    /// The last focus-derived folder, for detecting the change that
    /// releases `scm_pin`.
    scm_follow_root: PathBuf,
    /// The workspace root the Testing panel and worker are bound to —
    /// follows the focused file's folder like the SCM surfaces (#151).
    active_test_root: PathBuf,
    /// Folder set from an explicitly opened `.code-workspace` (#163):
    /// consumed by `change_workspace_root` INSTEAD of the automatic
    /// per-primary restore, so the file defines the arrangement exactly.
    pending_workspace_folders: Option<Vec<PathBuf>>,
    /// Per-workspace-root last-seen HEAD oid, for gutter-baseline and
    /// commit-graph invalidation per repository (#149).
    git_head_oids: std::collections::BTreeMap<PathBuf, Option<String>>,
    git: GitWorker,
    cursor_blink: CursorBlink,
    editor_click: ClickTracker,
    tree_click: ClickTracker,
    terminal_click: ClickTracker,
    /// Modified clicks, so `ctrl+double_click` and friends can be recognised
    /// without arming the unmodified trackers above (see the type's docs).
    /// One tracker, not one per region: it is only ever read by the binding
    /// dispatch, and a double needs both clicks at the same cell, so two
    /// regions cannot be confused for one another.
    modified_click: ModifiedClickTracker,
    /// Double-click tracking for PORTS rows: a second click on the same row
    /// opens that port, the same as pressing Enter on it.
    ports_click: ClickTracker,
    /// Active edge auto-scroll while drag-selecting in the terminal: set
    /// when the drag pointer is pinned past the top/bottom edge, serviced
    /// each main-loop tick to keep growing the selection through
    /// scrollback. `None` whenever the pointer is inside the pane or the
    /// button is released.
    terminal_select_autoscroll: Option<TerminalSelectAutoScroll>,
    /// Pane whose scrollbar is currently being dragged with the left mouse button.
    scrollbar_drag: Option<Pane>,
    /// True while the editor's horizontal scrollbar thumb is being dragged.
    /// Only the editor has a horizontal bar, so a bool suffices.
    editor_hscrollbar_drag: bool,
    /// A left-drag is moving the OUTLINE panel's scrollbar thumb. The outline
    /// is not a focusable `Pane`, so it gets its own drag latch rather than
    /// riding `scrollbar_drag`.
    outline_scrollbar_drag: bool,
    /// Scrollbar-thumb drag latches for the other stacked Explorer sub-views,
    /// matching `outline_scrollbar_drag` (none is a focusable `Pane`).
    open_editors_scrollbar_drag: bool,
    timeline_scrollbar_drag: bool,
    deps_scrollbar_drag: bool,
    testing_scrollbar_drag: bool,
    graph_scrollbar_drag: bool,
    welcome: WelcomeState,
    /// One-shot background refresh of the remote extension index. Polled in the
    /// main loop; rebuilds the Extensions panel once if the verified cache
    /// changed. `None` once consumed (or on a disarmed build, immediately).
    ext_index_refresh: Option<std::sync::mpsc::Receiver<bool>>,
    /// True when the in-flight refresh was triggered by the user (the ⟳ button),
    /// so its completion reports a status line; the silent startup refresh
    /// doesn't, to avoid clobbering more useful startup messages.
    ext_index_manual_refresh: bool,
    /// Channel to the background search worker. Each keystroke or toggle
    /// flip pushes a `(query, opts)` request here; the worker debounces
    /// and runs `search_workspace` off the UI thread.
    search_query_tx: std::sync::mpsc::Sender<crate::widgets::search::SearchRequest>,
    /// Results coming back from the search worker: `(query, hits)`. The
    /// query is echoed so we can drop stale results when the user has
    /// typed past the query that produced them.
    search_results_rx: std::sync::mpsc::Receiver<crate::widgets::search::SearchEvent>,
    /// Pixel size of one terminal cell, captured in `init_graphics`.
    /// Required to bake OSC-1337 images at exact viewport pixel size so
    /// iTerm draws them with no stretching or letterboxing.
    cell_pixel: Option<(u32, u32)>,
    /// Last wheel step applied to a PDF preview (when, in which direction,
    /// and on which document), so a momentum flick's same-direction burst
    /// coalesces instead of queueing one blocking rasteriser run per event.
    /// Keyed by document: switching to another PDF starts fresh - a reader's
    /// first gesture there is not a repeat.
    last_pdf_wheel: Option<(std::time::Instant, i32, Option<PathBuf>)>,
    /// One-shot consent to overwrite FORMULA cells on the next xlsx
    /// save (#178/#194): armed by the save that held them back, distinct
    /// from `force_save_armed` (the disk-conflict consent).
    formula_overwrite_armed: bool,
    /// Pre-encoded inline-image for the source-control change-count badge (an
    /// accent pill + count, VS Code's `activityBarBadge`), emitted at z=1 over
    /// the SCM activity icon's bottom-right. `None` when there are no changes,
    /// not in a repo, or image rendering is off (the glyph path draws a text
    /// badge instead). Rebuilt by `refresh_scm_change_badge` when the change
    /// set, theme, or cell size shifts.
    scm_change_badge: Option<String>,
    /// Change count the cached `scm_change_badge` was built for; drives the
    /// dirty check and the badge's on-screen cell width.
    scm_change_badge_count: usize,
    /// Pre-encoded inline-image for the Explorer change badge: the count of
    /// open editors with unsaved edits (VS Code's Explorer activity badge),
    /// emitted at z=1 over the Explorer icon's bottom-right. `None` when nothing
    /// is unsaved or image rendering is off. Mirrors the SCM badge plumbing;
    /// rebuilt by `refresh_explorer_unsaved_badge`.
    explorer_unsaved_badge: Option<String>,
    /// Unsaved-file count the cached `explorer_unsaved_badge` was built for.
    explorer_unsaved_count: usize,
    /// Pre-encoded inline-image for the Remote icon's forwarded-ports badge
    /// (VS Code's Ports view count), emitted at z=1 over the Remote icon. `None`
    /// when no port is forwarded or image rendering is off. Same plumbing as the
    /// other count badges; rebuilt by `refresh_remote_ports_badge`.
    remote_ports_badge: Option<String>,
    /// Forwarded-port count the cached `remote_ports_badge` was built for.
    remote_ports_count: usize,
    /// Pre-encoded inline-image for the Testing icon's failing-test count badge
    /// (red pill, VS Code's Testing badge), emitted at z=1 over the beaker icon.
    /// `None` when nothing is failing or image rendering is off. Same plumbing as
    /// the other count badges; rebuilt by `refresh_testing_badge`.
    testing_badge: Option<String>,
    /// Failing-test count the cached `testing_badge` was built for.
    testing_badge_count: usize,
    /// Problem count the cached `overlays.problems_badge` circle was built for;
    /// gates the per-frame rebuild in `refresh_problems_badge`.
    problems_badge_count: usize,
    /// Anchor cell (top-left) where the PROBLEMS-tab circle badge should be
    /// emitted this frame, recorded by `paint_panel_tabs` in images mode. `None`
    /// when the panel strip isn't drawn or the count is zero; the post-frame
    /// `flush_problems_badge_overlay` clears the image when it's `None`.
    problems_badge_cell: Option<(u16, u16)>,
    /// Which inline-image protocol the host terminal speaks, resolved once at
    /// startup (env-fixed). Drives the [`crate::iterm2_inline::build_inline_image`]
    /// dispatch (iTerm2 OSC-1337 vs Kitty graphics) and the Kitty-only
    /// delete-all eviction on the clear chain.
    inline_protocol: crate::iterm2_inline::InlineImageProtocol,
    /// Set once by the runtime DA1 probe (`run`) when the host terminal lacks an
    /// env-advertised protocol (iTerm2/Kitty) but answers DA1 with sixel
    /// support. `init_graphics` promotes `inline_protocol` to `Sixel` when this
    /// is true, and preserves it across the theme-switch re-detect that would
    /// otherwise reset to `None` (sixel has no env signal to re-derive from).
    sixel_supported: bool,
    /// One-shot: a WINCH arrived, so the next frame must wipe and repaint every
    /// cell on EVERY protocol. A dtach reattach fires WINCH (`-r winch`) against
    /// a blank physical screen while ratatui's buffer still says everything is
    /// painted, so the diff alone emits nothing; the Kitty path skips the
    /// image-eviction wipe (the typing-blink fix), so resize owns its own.
    resize_repaint_needed: bool,
    /// VS Code-style editor minimap (rasterized document preview in a right/left
    /// strip). On by default; toggled and re-sided from the strip's right-click
    /// menu.
    minimap_visible: bool,
    minimap_side: MinimapSide,
    /// Cached whole-file raster; recomposited (not rebaked) on scroll.
    minimap_base: Option<MinimapBase>,
    /// Hit-test rect of the on-screen minimap image (text-aligned rows), for
    /// click-to-scroll and the right-click menu. Empty when the minimap is off.
    minimap_img_rect: Rect,
    /// Pixel height the lines are mapped into within the image (top-aligned;
    /// `<=` the image's pixel height for short files). Click mapping divides by
    /// this, not the full strip height, so clicks land on the right line.
    minimap_content_h: u32,
    /// A left-drag is panning the view via the minimap strip.
    minimap_drag: bool,
    /// Clipboard read entrypoint. Production uses the host clipboard; tests
    /// can swap in a deterministic reader for Cmd+V routing assertions.
    clipboard_reader: fn() -> Option<String>,
    /// Whether this croft is a relay session: a `croft remote` child whose
    /// LOCAL launcher runs the drop pump, so the clipboard the user pastes
    /// from lives on the other machine (#538).
    ///
    /// Resolved ONCE here rather than read per copy. `CROFT_RELAY_KEY` is
    /// process-global, and `deliver_copied_text` asks this question on every
    /// copy: a relay test that sets the variable would otherwise reroute the
    /// copy of every test running beside it, which is exactly what it did
    /// (three suites broke). Inert under `cfg(test)` for the same reason the
    /// collab channel's read is — a test opts in by setting the field — so no
    /// test can be steered by another's environment.
    is_relay_session: bool,
    remote_launch: Option<RemoteLaunch>,
    pending_remote_launch_host: Option<String>,
    pending_remote_launch_path: Option<String>,
    /// The ssh-pane offer currently shown in the status bar (#364), if any.
    /// Accepted with Cmd+K G, dismissed with Esc, dropped when the pane's
    /// ssh ends or after `SSH_OFFER_TTL`.
    ssh_offer: Option<SshOffer>,
    /// What each pane (by uid) was last seen connected to, so an ssh session
    /// is offered once when it starts rather than on every sample.
    ssh_offer_seen: std::collections::BTreeMap<u64, Option<String>>,
    /// The label thread's ssh samples (#364): `(shell pid, resolved host)`
    /// per pane it looked at, shipped beside the names it already resolves
    /// so the argv read and the `~/.ssh/config` parse stay off the loop.
    ssh_rx: std::sync::mpsc::Receiver<Vec<(i32, Option<String>)>>,
    ssh_tx: std::sync::mpsc::Sender<Vec<(i32, Option<String>)>>,
    /// `disable_remote_offer` from prefs (#364).
    remote_offer_disabled: bool,
    /// `remote_offer_excluded_hosts` from prefs (#364).
    remote_offer_excluded: Vec<String>,
    /// `fleet_groups` from prefs (#363): named host sets a fleet run can
    /// expand, so a fleet is named once rather than retyped per run.
    fleet_groups: std::collections::BTreeMap<String, Vec<String>>,
    /// Hosts whose provisioning failed recently (#364), loaded from the
    /// cache file at startup and extended when an install fails.
    remote_offer_refused: crate::remote::RefusedHosts,
    /// The `agents.json` row a new worktree lane starts in its pane (#348);
    /// `None` opens a plain shell. From `lane_agent` in settings.json.
    lane_agent: Option<String>,
    /// Which panes are worktree lanes' (#348), by pane uid: saved with the
    /// terminal session so a relaunch seats the agent again, and consulted
    /// when a lane closes so its pane goes with it.
    lane_panes: std::collections::BTreeMap<u64, crate::terminal_session::LaneRecord>,
    /// Explorer-scoped Cut/Copy buffer. Independent from the OS clipboard
    /// (which carries text), this stores filesystem paths and the intent
    /// (move vs. copy) until the next Paste consumes it.
    tree_clipboard: Option<ExplorerClipboard>,
    /// Explorer type-to-jump buffer. Each printable keystroke within
    /// `TREE_TYPEAHEAD_WINDOW` of the previous one accumulates; a
    /// keystroke after the gap resets the buffer and cycles past the
    /// current selection. Matches VS Code's tree typeahead.
    tree_typeahead: Option<TreeTypeahead>,
    /// File the user picked via the explorer's "Select for Compare" menu
    /// action. None until they pick one; cleared once they invoke
    /// "Compare with Selected" against another file.
    compare_anchor: Option<PathBuf>,
    /// Whole-screen rect captured at the start of every `render`. The
    /// context-menu hit-test reads this to clamp the menu's bounds the
    /// same way the renderer does, so a menu that gets shifted up to fit
    /// on screen still maps clicks to the right item.
    last_frame_area: Rect,
    /// The Explorer/sidebar column rect from the last render (`None` when
    /// the sidebar is collapsed). The zoxide jump popup anchors over this
    /// so it drops from the Explorer rather than centering on the frame.
    last_sidebar_area: Option<Rect>,
    /// Active explorer drag-and-drop, if any.
    tree_drag: Option<ExplorerDrag>,
    /// Pending SCP uploads queued by a Finder drag-drop onto the Remote
    /// Explorer. These are intentionally NOT run inline — the main loop
    /// drains the queue after suspending the alt-screen so scp can use
    /// the host shell for password / FIDO / known_hosts prompts and the
    /// user actually sees what's happening.
    pending_scp_uploads: Vec<ScpUpload>,
    /// Drops awaiting reverse-pull from the user's local Mac via the
    /// drop-relay launched by the local croft parent. Polled each frame.
    pending_remote_pulls: Vec<PendingRemotePull>,
    /// This croft's `croft view` listener (#362).
    ///
    /// `None` when the bind failed: a croft that cannot offer `croft view`
    /// must still start, so the failure costs the feature and nothing else.
    /// Panes then see no `CROFT_VIEW_SOCK` and the client says so plainly,
    /// which is the same message a pane outside croft gets.
    ///
    /// No path is kept alongside it. The doc used to promise "the socket path
    /// to unlink when it goes away" and nothing unlinked it: there is no
    /// `Drop for App`, both readers discarded the second element, and the
    /// launch-time sweep is what actually reclaims a dead croft's socket -
    /// deliberately, since an unclean exit leaves no `Drop` to run either.
    /// A field carrying a promise the code does not keep is worse than no
    /// field.
    view_listener: Option<std::os::unix::net::UnixListener>,
    /// URL awaiting the user's local-browser confirmation (remote-
    /// launched croft only). When `Some`, a modal asks Y/A/N and all
    /// other keys are swallowed.
    pending_local_open: Option<String>,
    /// Source Control entry awaiting Y/N confirmation for destructive
    /// `Discard Changes`. Holds the relative path and whether it was an
    /// Untracked entry (Untracked discard deletes the file from disk;
    /// tracked discard runs `git checkout HEAD -- <path>`). Both paths
    /// destroy uncommitted work, so the modal must always run first.
    pending_discard: Option<PendingDiscard>,
    /// Armed by R in a Source-Control diff; reverting a hunk destroys
    /// uncommitted work, so the confirm modal always runs first.
    pending_revert_hunk: Option<PendingRevertHunk>,
    /// The tasks backing the open Run Task picker; the picker row `id`
    /// indexes into this list.
    run_tasks: Vec<crate::tasks::Task>,
    /// The most recently run task, for "Tasks: Rerun Last Task".
    last_task: Option<crate::tasks::Task>,
    /// Set on startup (after `init_graphics` resolves the inline-image
    /// protocol) when the host terminal can't render croft's icons/images
    /// and the user hasn't silenced the nudge. Drawn as a dismissible modal
    /// recommending iTerm2 (macOS) / Ghostty (macOS/Linux).
    pending_terminal_warning: bool,
    /// True while the Source Control commit dropdown (▾ caret) is open.
    /// The caret button toggles this; clicking a menu row, the commit
    /// button, or anywhere outside the menu closes it.
    commit_menu_open: bool,
    /// Cached default-branch name (e.g. "main" / "master"), refreshed
    /// when the workspace root changes. Surfaced in the commit dropdown's
    /// "View Changes vs <name>" label so users know which branch the
    /// diff compares against. `None` until the resolver succeeds.
    default_branch_label: Option<String>,
    /// Last HEAD oid the git-gutter baselines were synced against. When the
    /// git worker reports a different oid (commit, checkout, pull), the cached
    /// per-tab HEAD snapshots are invalidated so the gutter refetches.
    /// True after the user has chosen "Always for this session" on the
    /// local-browser confirmation. Subsequent link clicks dispatch to
    /// the relay silently.
    trust_local_browser: bool,
    /// Width in cells of the sidebar (Explorer / Search / Remote pane).
    /// Defaults to 32 cells; user can drag the splitter between sidebar
    /// and editor to widen or narrow.
    sidebar_width: u16,
    /// Height in cells of the bottom terminal pane. `None` = use the
    /// default 35% split; Some = a user-specified pinned height. Stored
    /// in cells (not percent) so it doesn't drift on window resize.
    terminal_height: Option<u16>,
    /// Active splitter drag, if any. Cleared on mouse-up.
    splitter_drag: Option<SplitterDrag>,
    /// Last-rendered geometry of the vertical splitter column (between
    /// sidebar and editor) and the horizontal splitter row (between
    /// editor and terminal). Used by the mouse handler to hit-test cleanly
    /// without recomputing layout outside of `render`.
    sidebar_splitter_x: Option<u16>,
    terminal_splitter_y: Option<u16>,
    /// Every draggable seam between editor groups, as laid out by the most
    /// recent render. Empty when unsplit. Drives both the focus-on-click guard
    /// (a press on a seam must not steal focus) and the seam-drag hit-test, for
    /// a grid of any depth.
    editor_seams: Vec<editor_layout::Seam>,
    /// Hit-test rectangles of the "[+]" buttons - one per terminal pane,
    /// indexed in lock-step with `terminals`. Empty when the pane is hidden
    /// or every pane is too narrow for the label.
    terminal_add_buttons: Vec<Rect>,
    /// Hit-test rectangles of the profile-caret (`⌄`) buttons - one per pane,
    /// in lock-step with `terminals`. Clicking one opens the profile picker.
    terminal_profile_buttons: Vec<Rect>,
    /// Hit-test rectangles of the "[-]" buttons - one per terminal pane,
    /// indexed in lock-step with `terminals`. Empty when only one terminal
    /// is open (closing the last one would leave the pane empty, which we
    /// explicitly forbid) or the pane is hidden.
    terminal_close_buttons: Vec<Rect>,
    /// Hit-test rectangles of the maximize / restore (`⛶`) buttons - one per
    /// pane, in lock-step with `terminals`. Hidden panes hold an empty rect
    /// so a button's position still names its terminal index.
    terminal_max_buttons: Vec<Rect>,
    /// Hit-test rectangles of the maximize-mode rail rows down the panel's
    /// right edge, in lock-step with `terminals`. Clicking one hands that
    /// terminal the maximized pane. Empty outside maximize mode.
    terminal_rail_rects: Vec<Rect>,
    /// The maximize rail's own column, so the wheel can scroll it. Empty
    /// whenever the rail is not on screen.
    terminal_rail_area: Rect,
    /// First terminal shown in the rail when there are more terminals than
    /// rows. Clamped during paint, so nothing else has to keep it honest.
    terminal_rail_scroll: usize,
    /// Which terminal the rail last scrolled into view, so the reveal fires
    /// when the active pane changes and never fights a deliberate wheel.
    terminal_rail_revealed: Option<usize>,
    /// Hit-test rectangles of the pane name pills at each pane's top-left, in
    /// lock-step with `terminals`. A press on one starts a drag-reorder;
    /// hidden or unlabeled panes hold an empty rect. Empty with one terminal.
    terminal_label_rects: Vec<Rect>,
    /// Hit-test rectangles of the collapse (`‹`) buttons, in lock-step with
    /// `terminals` (#313). A pane that is hidden, already collapsed, too
    /// narrow for the glyph, or maximized holds an empty rect.
    terminal_collapse_buttons: Vec<Rect>,
    /// Extensions whose programs the user has allowed to run (the MCP
    /// consent set, loaded once from prefs and kept current when a consent
    /// is granted here), so a viewer's gate is a set lookup rather than a
    /// prefs read per click, and a test can seed it without a prefs file.
    consented_extensions: std::collections::BTreeSet<String>,
    /// The config dir this app reads extensions and consent from. Carried
    /// rather than re-derived so a test can point one app at a scratch dir
    /// instead of mutating the process-wide environment, which this repo
    /// has twice seen take an unrelated test down.
    config_dir: PathBuf,
    /// Where "open scrollback in an editor tab" writes the pane's coloured
    /// scrollback so the rendered log view can index it from disk (#257).
    /// `~/.cache/croft/scrollback` normally; a test points it at a temp dir.
    scrollback_dir: PathBuf,
    /// Hit-test rectangles of the one-column strips collapsed panes leave
    /// behind, in lock-step with `terminals` (#313). Clicking anywhere down a
    /// strip gives that pane its width back; expanded panes hold an empty
    /// rect. The WHOLE strip is the target, not just the chevron: one column
    /// is already a small thing to hit without also demanding the right row.
    terminal_strip_rects: Vec<Rect>,
    /// Index of the terminal being drag-reordered (grabbed by its pane label
    /// or its maximize-rail row). The reorder is live: crossing another pane
    /// or rail row moves the terminal there immediately, and this follows it.
    terminal_drag_from: Option<usize>,
    /// A left press that was FORWARDED to a pane because its child tracks
    /// the mouse (#474), live until the release. The release goes to the
    /// same pane, clamped to its grid if the pointer left it. What the drag
    /// in between does depends on what the child asked for: motion reports
    /// under 1002/1003, croft's own text selection anchored at the press
    /// cell under click-only 1000 (Claude Code's mode), since a child that
    /// never asked for motion cannot use the drag and the user still needs
    /// to copy text out of it. The pane is named by `uid`, so a pane closed
    /// or reordered mid-press is found again (or found gone) rather than
    /// confused with whichever pane now holds its old index. Every later
    /// event of the gesture -- motion, selection extension, release,
    /// copy-on-select -- is aimed at THAT pane, never at the active one:
    /// the keyboard can move the active pane while the button is held.
    ///
    /// Same hole as `terminal_drag_from`: a modal that takes the screen
    /// while the button is held swallows the mouse-up in `handle_mouse`'s
    /// overlay gates, so the latch stays set until the next release. Two
    /// consequences the older latch never had: the child keeps a button it
    /// believes is down until its next click, and the auto-scroll tick keeps
    /// standing down for a pane that is not active. Reaching it needs a
    /// keystroke with the button held.
    terminal_pointer_forwarded: Option<ForwardedPointer>,
    /// True while one terminal pane fills the panel's width and the others
    /// are listed in the right-side rail (the per-pane `⛶` button / Cmd+K M).
    /// Distinct from `terminal_maximized`, which grows the panel vertically
    /// over the editor. Only meaningful with 2+ terminals; closing down to
    /// one resets it.
    terminal_pane_maximized: bool,
    /// Which tab the bottom panel group is showing (TERMINAL or PROBLEMS).
    bottom_panel_tab: BottomPanelTab,
    /// The PROBLEMS view: aggregated workspace diagnostics, projected from
    /// `lsp_diagnostics`. Rendered into the panel content when its tab is active.
    problems: crate::widgets::problems::ProblemsPanel,
    /// The OUTPUT view: a read-only per-channel log viewer over the in-process
    /// `crate::output` bus. Rendered into the panel content when its tab active.
    output: crate::widgets::output::OutputPanel,
    /// The PORTS view: the registry of detected loopback ports, fed by the
    /// terminal output scrape and the periodic socket poll. Rendered into the
    /// panel content when its tab is active.
    ports: crate::widgets::ports::PortsPanel,
    /// The CAPTURES view: output lines collected by `capture` triggers
    /// (iTerm2's Capture Output); Enter / click jumps back to the line.
    pub captures: crate::widgets::captures::CapturesPanel,
    /// Transient click-only notification for a freshly detected browsable port,
    /// offering forward / open. `None` when nothing is pending.
    port_toast: Option<PortToast>,
    /// Last time the socket poll was kicked off, so it fires on a low cadence
    /// rather than every tick.
    last_port_poll: std::time::Instant,
    /// Socket-poll snapshots arrive here from a one-shot background thread (one
    /// complete listener set per cycle), so the blocking `lsof`/`ps` never runs
    /// on the event loop (keeps input at 0ms). A full set, not individual hits,
    /// so the app can reconcile ports that stopped listening.
    port_poll_rx: std::sync::mpsc::Receiver<PortPoll>,
    /// Results of a running fleet command (#363), delivered off the event
    /// loop. A fleet run waits on the network for up to `FLEET_TIMEOUT`, and
    /// blocking the loop for that would freeze the editor — the user could
    /// not scroll, type, or cancel while their fleet answered.
    fleet_rx: std::sync::mpsc::Receiver<Vec<crate::fleet::HostResult>>,
    fleet_tx: std::sync::mpsc::Sender<Vec<crate::fleet::HostResult>>,
    /// True while a run is in flight, so a second invocation says so rather
    /// than starting a competing fleet against the same hosts.
    fleet_running: bool,
    port_poll_tx: std::sync::mpsc::Sender<PortPoll>,
    /// True while a poll thread is in flight, so cadence ticks don't pile up
    /// overlapping `lsof` invocations.
    port_poll_inflight: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Auto-label refresh for terminal panes: `(shell_pid, process_name)` pairs
    /// resolved off the event loop, applied to the pane with that shell pid.
    last_label_refresh: std::time::Instant,
    label_rx: std::sync::mpsc::Receiver<Vec<(i32, String)>>,
    label_tx: std::sync::mpsc::Sender<Vec<(i32, String)>>,
    label_inflight: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Hit-test rect of the "PROBLEMS" tab in the panel tab strip. Empty when
    /// the panel is hidden.
    problems_tab_rect: Rect,
    /// Hit-test rect of the "OUTPUT" tab in the panel tab strip. Empty when the
    /// panel is hidden.
    output_tab_rect: Rect,
    /// Hit-test rect of the "PORTS" tab in the panel tab strip. Empty when the
    /// panel is hidden.
    ports_tab_rect: Rect,
    /// Hit-test rect of the "CAPTURES" tab in the panel tab strip.
    captures_tab_rect: Rect,
    /// Hit-test rect of the "TERMINAL" tab in the panel tab strip. Empty when
    /// the panel is hidden.
    terminal_tab_rect: Rect,
    /// Last pointer cell reported by a `Moved` event. Render-time hover
    /// hit-testing (the Black theme's teal pill behind the terminal `-`/`+`
    /// buttons) reads this instead of tracking enter/leave transitions.
    pointer_cell: Option<(u16, u16)>,
    /// Which activity-bar icon the pointer is currently over, if any. Drives
    /// the hover variant of the icon (brightened glyph, no selection pill).
    /// Changing it arms `overlays.activity.mark_dirty()` so the swapped
    /// pre-baked image is re-emitted; it never triggers a re-bake.
    hovered_activity_icon: Option<ActivityIcon>,
    /// Which layout toolbar icon the pointer is over (0 = side bar, 1 = panel,
    /// 2 = customize), so a hover change can re-emit the brighter image variant
    /// like [`Self::hovered_activity_icon`] does for the activity bar.
    hovered_layout_icon: Option<usize>,
    /// On-screen keyboard for touch-only environments (Termux). `Some`
    /// while the bottom keyboard band is visible; taps on its keys
    /// synthesize `KeyEvent`s through `handle_key`, so they reach the
    /// editor, terminal PTY, and modals exactly like hardware keystrokes.
    osk: Option<crate::widgets::osk::Osk>,
    /// True when taps in editable areas (editor text, terminal panes, the
    /// Search input) auto-raise the on-screen keyboard. Armed on Termux,
    /// where active mouse tracking permanently suppresses the native soft
    /// keyboard; `CROFT_FORCE_OSK=1` arms it elsewhere for testing.
    osk_auto: bool,
    /// Total width / height of the right-hand content area, captured on
    /// every render so a splitter drag can clamp to the live viewport.
    last_content_width: u16,
    last_content_height: u16,
    /// Optional LSP orchestrator. None when LspManager::new failed at
    /// startup (e.g. the background tokio runtime couldn't spawn); the
    /// rest of the editor stays fully functional without it.
    pub lsp: Option<crate::lsp::LspManager>,
    /// Per-path snapshot of the last edit_seq we forwarded to the LSP
    /// manager. sync_lsp diffs every tick against the current tabs to
    /// emit did_open / did_change / did_close.
    lsp_last_seen: std::collections::HashMap<PathBuf, u64>,
    /// Newest semantic-token request generation already applied per path.
    /// `seq` alone is not enough: two full requests can be in flight at the
    /// same seq (`sync_lsp` plus a server-driven refresh), and the request
    /// retry loop emits an EMPTY batch once its backoff is exhausted, so a
    /// late empty loser would otherwise blank a good overlay and be written
    /// to the content-keyed disk cache.
    semantic_generation_seen: std::collections::HashMap<PathBuf, u64>,
    /// Diagnostics store: per file, the latest set from each server. Servers
    /// push complete sets via `textDocument/publishDiagnostics`, so the inner
    /// map is keyed by server name (ty + ruff can both publish for one file)
    /// and a server's entry is replaced wholesale on each batch (an empty
    /// batch removes it). The merged value for the visible file is handed to
    /// the editor; the store outlives tab switches so re-focusing a file shows
    /// its squiggles again without waiting for the next server push.
    /// Open-buffer paths as of the last PROBLEMS rebuild. Open Files scope
    /// filters on this set, so the panel must refresh when the set changes —
    /// not only when diagnostics do, or opening a file with stored
    /// diagnostics would show nothing until unrelated churn happened by.
    problems_open_set: std::collections::BTreeSet<PathBuf>,
    lsp_diagnostics: std::collections::HashMap<
        PathBuf,
        std::collections::HashMap<String, Vec<crate::lsp::manager::Diagnostic>>,
    >,
    /// Live LSP work-done progress, keyed by server name (e.g. "rust-analyzer"
    /// -> "Indexing 112/340 33%"). An entry exists only while that server has
    /// an active task; the status bar surfaces it so a busy-priming server is
    /// never mistaken for a dead one. Cleared on the server's `End`.
    lsp_progress: std::collections::HashMap<String, String>,
    /// Active completion popup, when a completion request has been issued
    /// and the user hasn't dismissed the result. Populated by drain_lsp_completion
    /// once the worker sends a CompletionResult back.
    pub completion_popup: Option<crate::widgets::completion_popup::CompletionPopup>,
    /// Most recent completion request id; later responses with a stale
    /// id are dropped so a slow earlier response cannot clobber a fresh
    /// one (e.g. user already moved past the original trigger).
    completion_request_id: Option<u64>,
    /// Signature Help (parameter hints) popup, anchored to the caret while the
    /// user is inside a call. Populated by `drain_lsp_signature_help`.
    pub signature_help_popup: Option<crate::widgets::signature_help_popup::SignatureHelpPopup>,
    signature_help_request_id: Option<u64>,
    /// (cursor_row, cursor_col, edit_seq) at the last signatureHelp request, so
    /// the tick can re-query when the caret moves or the buffer changes while
    /// the popup is open and close it once the caret leaves the call.
    signature_help_anchor: Option<(usize, usize, u64)>,
    hover: HoverDwell,
    hover_popup: Option<crate::widgets::hover_popup::HoverPopup>,
    hover_request_id: Option<u64>,
    hover_anchor: Option<(u16, u16)>,
    hover_word: Option<(usize, usize, usize)>,
    /// Diagnostic block for the point a hover is anchored to, captured
    /// synchronously when the dwell fires (server diagnostics already live in
    /// the editor). Stacked above the async LSP hover reply by `compose_hover`
    /// so a squiggle's message shows even when the server returns no type info.
    hover_diagnostic: Option<String>,
    /// Separate dwell timer for the editor tab strip. Hovering a tab for
    /// `HOVER_DELAY` surfaces `tab_tooltip` with the tab's full path so
    /// same-named files can be told apart. Kept distinct from `hover`
    /// (which drives LSP word hover in the editor body) so the two never
    /// fight over the same timer.
    tab_hover: HoverDwell,
    tab_tooltip: Option<crate::widgets::hover_popup::HoverPopup>,
    tab_hover_idx: Option<usize>,
    /// Shared dwell + popup for chrome button hints (search-panel actions and
    /// toggles, activity-bar icons, …). One timer for all chrome controls,
    /// keyed on the label so the dwell only restarts when the pointer crosses
    /// to a different control; extending coverage to a new surface is one arm
    /// in `ui_tooltip_at`.
    ui_hover: HoverDwell,
    ui_tooltip: Option<crate::widgets::hover_popup::HoverPopup>,
    ui_tooltip_label: Option<&'static str>,
    /// The chrome tooltip's final on-screen rect from the most recent render
    /// (after the activity-bar shift / viewport clamp), or `None` when no
    /// tooltip is showing. Read by the post-draw flush so the box can be
    /// re-painted on top of any sidebar illustration it overlaps, since
    /// OSC-1337 images composite above ratatui's text layer.
    ui_tooltip_area: Option<Rect>,
    definition_request_id: Option<u64>,
    /// In-flight Peek Definition request (#115): same LSP request as the
    /// jump, different consumer — the response opens the peek popup at the
    /// caret instead of moving it.
    peek_definition_request_id: Option<u64>,
    /// The open peek popup, rendered beside `hover_popup` against the whole
    /// frame; `peek_target` is where Enter jumps.
    peek_popup: Option<crate::widgets::hover_popup::HoverPopup>,
    peek_target: Option<(PathBuf, u32, u32)>,
    declaration_request_id: Option<u64>,
    type_definition_request_id: Option<u64>,
    /// The `(active file, last-seen LSP edit seq)` the OUTLINE was last synced
    /// to, so `sync_outline` re-requests symbols exactly once per tab switch or
    /// edit batch. `None` seq means the file has no language server.
    outline_synced: Option<(PathBuf, Option<u64>)>,
    implementation_request_id: Option<u64>,
    references_request_id: Option<u64>,
    call_hierarchy_request_id: Option<u64>,
    /// In-flight documentHighlight request, with the (path, row, col,
    /// edit_seq) it was fired for so a reply for a caret or buffer state the
    /// editor has since left is dropped.
    occurrences_request: Option<(u64, PathBuf, usize, usize, u64)>,
    /// In-flight linkedEditingRange request (#254): (id, path, edit_seq).
    linked_request: Option<(u64, PathBuf, u64)>,
    /// Last observed `(path, row, col, seq)` for the linked-editing
    /// debounce, and when it settled — occurrences' idle pattern.
    linked_observed: Option<(PathBuf, usize, usize, u64)>,
    linked_observed_at: std::time::Instant,
    /// In-flight Expand Selection request (#254). Extra Shift+Alt+Right
    /// presses while the chains are in flight stack up and apply
    /// together on drain; an `unsupported` verdict resolves them via
    /// tree-sitter instead. The reply is gated on id + path + edit_seq
    /// AND the exact cursor positions the request was fired for — a
    /// caret move without an edit leaves `edit_seq` unchanged, and a
    /// chain computed for the old caret must not apply at the new one.
    selection_range_request: Option<PendingSelectionRanges>,
    /// The caret state `tick_occurrences` last observed, and when it changed.
    /// A caret resting on one spot for `OCCURRENCES_IDLE` fires one request.
    occ_observed: Option<(PathBuf, usize, usize, u64)>,
    occ_observed_at: std::time::Instant,
    rename_request_id: Option<u64>,
    /// In-flight prepareRename (#254): (id, path, row, col, edit_seq) —
    /// the deferred rename prompt's context.
    prepare_rename_request: Option<(u64, PathBuf, usize, usize, u64)>,
    format_request_id: Option<u64>,
    /// True when the in-flight format request is Format Selection (#254)
    /// — the drain words its statuses accordingly.
    format_request_selection: bool,
    /// VS Code's `editor.formatOnType` (#254): typing a server trigger
    /// character runs onTypeFormatting at the spot. Off by default.
    format_on_type: bool,
    /// In-flight on-type request: (id, the edit_seq it was computed
    /// against, the tab's path). The reply applies only while that same
    /// tab is active and its buffer has not moved since — `edit_seq` is
    /// per-tab, so the seq alone cannot tell tabs apart.
    on_type_request: Option<(u64, u64, PathBuf)>,
    code_action_request_id: Option<u64>,
    /// True when the in-flight code-action request is a `codeAction/resolve`
    /// (the reply is one resolved action to apply directly) rather than the
    /// initial `textDocument/codeAction` (whose reply opens the picker).
    code_action_pending_resolve: bool,
    /// The actions from the in-flight `textDocument/codeAction` reply, indexed
    /// by the row `id` the Quick Fix [`ListPicker`] presents.
    pending_code_actions: Vec<crate::lsp::manager::CodeActionItem>,
    /// Review threads loaded onto a file, as `(the file, its threads)` (#366).
    ///
    /// A SEPARATE field from `editor.comment_boxes`, which the render loop
    /// rebuilds from `navigator_notes` on every frame — assigning review
    /// threads there directly meant they were wiped before the user saw
    /// one, while the status line still reported having loaded them.
    ///
    /// Keyed by PATH because the merge runs on every frame: keyed only by
    /// "whatever was loaded last", one file's objections would hang off the
    /// next file's line numbers, against unrelated code. That is the harm
    /// `threads_are_filtered_to_the_file_being_viewed` prevents on the
    /// filter axis, and it re-enters through the lifetime axis if the boxes
    /// outlive the buffer they describe.
    ///
    /// Holds `Thread`s rather than finished `CommentBox`es so the geometry
    /// is derived against the LIVE buffer each frame. `box_line` clamps a
    /// box past the end back into view; computed once at load, that clamp
    /// goes stale the moment the user edits, and the box it was protecting
    /// becomes invisible again.
    review_boxes: Option<(PathBuf, Vec<crate::review_threads::Thread>)>,
    /// An open asciicast recording (#356): the writer, the file it appends
    /// to, and when it started. `None` when nothing is being recorded.
    recording: Option<(
        crate::asciicast::Recorder,
        std::fs::File,
        std::time::Instant,
    )>,
    /// The terminal size the open recording last wrote (#356). A resize is
    /// an `r` event, and a player that never receives one keeps rendering
    /// the header's size — so a session resized mid-recording plays back
    /// with every later frame wrapped at the wrong width.
    recorded_size: (u16, u16),
    /// The symbol a symbol tab is showing (#369): its name and the byte
    /// range it spans, which follows edits through
    /// `SymbolRange::after_edit`. `None` when no symbol tab is open.
    symbol_tab: Option<(String, PathBuf, crate::symbol_range::SymbolRange)>,
    /// The open history scrubber (#371), or `None` when the editor is
    /// showing the live buffer. `Some` at `Position::Working` is a real
    /// state: the scrubber is open and parked at the user's own edits.
    scrubber: Option<crate::scrubber::Scrubber>,
    /// A breakpoint croft set itself at the assertion the last run failed
    /// on (#373), as `(file, 1-based line)`. It is NOT one of the user's
    /// breakpoints: it is added to the launch set, rendered hollow-red like
    /// any unverified one, and removed when the session ends — a debugger
    /// that silently left breakpoints behind would be worse than one that
    /// set none.
    debug_temp_breakpoint: Option<(PathBuf, usize)>,
    /// Human-readable note about that breakpoint, folded into whichever
    /// launch message the user actually ends up seeing.
    debug_temp_note: Option<String>,
    /// Per-agent ledger of files changed while an agent was working (#345),
    /// and the review baselines that decide which of them still need a
    /// look.
    pub agent_ledger: crate::agent_lane::AgentLedger,
    /// When the running Fix with Navigator turn started (#374): the clock
    /// its PROBLEMS-row spinner runs on, and the flag that keeps the main
    /// loop repainting while it runs. `None` when no fix is streaming.
    problems_fix_started: Option<std::time::Instant>,
    /// The in-flight `.http` request's channel (#370). One at a time: the
    /// worker owns the socket, the drain owns the tab, and a second send
    /// while one runs is refused rather than queued.
    http_run: Option<std::sync::mpsc::Receiver<HttpRunOutcome>>,
    /// The presentation edits behind the open Change Color Presentation
    /// picker (#254), indexed by row id; cleared after a pick.
    pending_color_presentations: Vec<(String, Vec<crate::widgets::editor::TextSpanEdit>)>,
    /// The (path, edit_seq) the pending presentations were computed
    /// against; a pick is refused when either moved while the picker was
    /// open (an FS-sync reload bumps the seq without user edits).
    pending_color_context: Option<(PathBuf, u64)>,
    /// In-flight colorPresentation request: (id, path, edit_seq).
    color_presentations_request: Option<(u64, PathBuf, u64)>,
    nav: NavHistory,
    editor_vim_chord: EditorVimChord,
    /// `Cmd+K` leader: armed when the user presses the prefix, holding the
    /// instant it started so the next key within `CMD_K_LEADER_TIMEOUT`
    /// completes a `Cmd+K`-prefixed chord (VS Code's two-key model). `None`
    /// when no chord is in flight.
    cmd_k_leader: Option<std::time::Instant>,
    /// Native modal (vim-style) editing for the editor pane. When enabled it
    /// supersedes the always-on `editor_vim_chord` convenience layer.
    vim: crate::vim::VimState,
    /// Last `f`/`t`/`F`/`T` target, replayed by `;` and `,`.
    vim_last_find: Option<(crate::vim::FindKind, char)>,
    /// Whether the active visual selection is linewise (`V`), so the pending
    /// visual operator deletes/yanks whole lines.
    vim_visual_line: bool,
    shortcuts_modal: Option<crate::widgets::shortcuts::ShortcutsModal>,
    shortcuts_hit_rect: Option<Rect>,
    /// Status-bar clickable-segment hit rects, recorded each render. Empty when
    /// the bar is hidden or the segment doesn't fit. Diagnostics → PROBLEMS;
    /// encoding / EOL / language → their respective "change" pickers.
    status_diag_rect: Rect,
    status_indent_rect: Rect,
    status_encoding_rect: Rect,
    status_eol_rect: Rect,
    status_language_rect: Rect,
    connect_dialog: Option<crate::widgets::connect_dialog::ConnectDialog>,
    connect_auth: Option<crate::remote_connect::SshAuth>,
    install_session: Option<crate::install_session::InstallSession>,
    /// Background self-update watcher, present only on a remote-launched
    /// croft (gated by `CROFT_REMOTE_AUTOUPDATE`). Polls the install-stamp
    /// the local cross-build writes when it finishes shipping a newer
    /// binary, so the running croft can re-exec into it in place.
    update_watch: Option<crate::update_watch::UpdateWatch>,
    /// One-shot startup probe (#242): does the repo this binary was built
    /// from now sit at a different commit/dirty state than the binary has
    /// baked in? Local-only — a remote-launched croft is re-stamped by its
    /// launcher instead. Dropped once its verdict is drained.
    drift_probe: Option<crate::update_watch::DriftProbe>,
    /// The repo's current hash label when the probe found drift ("def456",
    /// "def456-dirty"). Arms the "F9 to rebuild" status-bar hint. Kept
    /// through a running rebuild — the Idle guards hide the hint while it
    /// runs, and a failure then re-arms F9 for a retry instead of
    /// silently reverting the key to its breakpoint meaning.
    local_drift: Option<String>,
    /// Background `cargo install --path <repo>` reinstalling the local
    /// croft after the user pressed F9 on a drift hint. Reported through
    /// the same UpdateEvent lifecycle as the remote watcher.
    self_install: Option<crate::update_watch::SelfInstall>,
    /// One-shot startup check (#333): is a newer release published than
    /// the version this binary carries? Local-only, throttled to a daily
    /// network request by its cache file. Dropped once its verdict lands.
    update_check: Option<crate::update_check::UpdateCheck>,
    /// The "vX available" popup, present from the offer landing until the
    /// user picks Update, Later, or (once staged) Relaunch.
    update_toast: Option<UpdateToast>,
    /// A background `cargo install --root <cache>/staged` of the offered
    /// release. Reported through the same UpdateEvent lifecycle as the
    /// remote watcher; the binary on PATH is untouched until Relaunch.
    staged_install: Option<crate::update_check::StagedInstall>,
    /// The staged release build's own lifecycle (#333). `update_status`
    /// belongs to the remote watcher and the drift rebuild; the two cells
    /// are never written by the other's producer, so a rebuild starting or
    /// failing after the release landed cannot disarm Relaunch, and the
    /// reverse. Readers that mean "any update" consult both.
    staged_status: UpdateStatus,
    update_status: UpdateStatus,
    /// When a background self-update is in progress, the instant it started.
    /// Drives the spinning update glyph in the status bar (and the redraw
    /// cadence that animates it). `None` whenever no update is running.
    update_spinner_start: Option<std::time::Instant>,
    /// Set when an update landed and croft should re-exec after the main
    /// loop unwinds and the alt-screen is surrendered. Read by `run`.
    pending_reexec: bool,
    overlays: OverlayManager,
    /// VS Code-style Cmd+F in-editor find overlay. None when closed.
    pub editor_find: Option<crate::widgets::editor_find::EditorFind>,
    /// Cmd+F find-in-terminal overlay: searches the active pane's grid +
    /// scrollback (like iTerm2 / Ghostty scrollback search). Reuses the
    /// editor find widget; the replace row is never shown. None when closed.
    pub terminal_find: Option<crate::widgets::editor_find::EditorFind>,
    /// The pane index `terminal_find` opened on. Find is bound to that pane
    /// like quick-select and copy mode: a gesture that activates a sibling
    /// closes it (per-frame invariant in `sync_focus_flags`), so its
    /// highlight and jump anchor never stray onto another pane's grid.
    terminal_find_pane: usize,
    /// The active terminal-find match as `(clock, abs_grid_line, col, len)`,
    /// the anchor next/prev navigation walks from — the line is stamped with
    /// the scroll-clock reading of the snapshot it was found in, and every
    /// use re-bases it first, so output streaming under an open find bar
    /// cannot leave navigation walking from a phantom row. None until the
    /// first match.
    terminal_find_match: Option<(i64, i32, usize, usize)>,
    /// Ctrl+Shift+Space quick-select hint mode on the active terminal pane
    /// (WezTerm's quick-select): every labelled match on the viewport plus
    /// the label prefix typed so far. None when the mode is off.
    pub terminal_quick_select: Option<QuickSelectState>,
    /// Durable cross-session command history (atuin's model): every
    /// finished command from a shell-integrated pane, with cwd / exit /
    /// duration / timestamp, persisted as JSONL under the config dir.
    pub command_history: crate::command_history::CommandHistory,
    /// Ctrl+Shift+H search popup over [`Self::command_history`]. None when
    /// closed.
    pub command_history_popup: Option<crate::widgets::history_popup::HistoryPopup>,
    /// Where the terminal-session snapshot lives
    /// (`terminal_sessions.json`); a field so tests point it at a tempdir.
    pub terminal_session_path: PathBuf,
    /// The most recent terminal-session persistence failure, latched by
    /// `save_terminal_session` and cleared by a later success; composed
    /// into structural-change statuses by `terminal_status` so a corrupt
    /// store is never silently ignored (#157/#158).
    terminal_store_error: Option<String>,
    /// The persisted folder-set store (#153); a field so tests redirect it.
    pub workspace_folders_path: PathBuf,
    /// A pane reorder is pending a session write. `move_terminal` runs once
    /// per motion report during a drag, and the write is a full
    /// read-modify-write of the session file plus a cwd syscall per pane, so
    /// it is marked here and flushed once per tick instead of inline.
    pub terminal_session_dirty: bool,
    /// Ctrl+Shift+Y copy mode on the active terminal pane (WezTerm / tmux):
    /// vi keys walk a cursor through the scrollback, v / V / Ctrl+V select,
    /// y copies. None when the mode is off.
    pub terminal_copy_mode: Option<CopyModeState>,
    /// The user's terminal trigger set (`triggers.json`), pushed into every
    /// pane on the drain tick and swapped wholesale on config reload.
    pub triggers: std::sync::Arc<crate::triggers::TriggerSet>,
    /// The agents croft recognises in a pane's foreground (#344): built in
    /// plus `agents.json`, reloaded on save.
    agents: crate::agents::AgentTable,
    /// Agent transitions from the last sample, drained on the tick.
    agent_events: std::collections::VecDeque<crate::agents::AgentEvent>,
    /// Hit rect of the status bar's agents chip; empty when no agent is seated.
    status_agents_rect: Rect,
    /// User-defined problem matchers (#252): `matchers.json` (user config
    /// dir + workspace `.croft/`), batch-scanned at the FinishedCommand
    /// boundary alongside the built-in table. Swapped wholesale on reload.
    pub matchers: std::sync::Arc<crate::problem_matchers::MatcherSet>,
    /// The background-capable subset of `matchers`, pushed into every pane
    /// on the drain tick exactly like the trigger set.
    pub watch_set: std::sync::Arc<crate::problem_matchers::WatchSet>,
    /// tasks.json `problemMatcher` assignments: pane uid → the matcher the
    /// task running there declared. Exclusive for that pane's batch scans
    /// (VS Code's model: an explicit matcher replaces the defaults).
    task_matcher_by_pane:
        std::collections::HashMap<u64, std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
    /// Panes whose PROBLEMS batch a watch matcher currently owns. The
    /// watcher eventually exiting fires a FinishedCommand whose whole-
    /// history rescan would resurrect every error of every past cycle, so
    /// that one scan is skipped (the flag clears with it — the pane's next
    /// ordinary command scans normally).
    watch_published_panes: std::collections::HashSet<u64>,
    /// Broadcast input (Cmd+K I, iTerm2's Cmd+Opt+I): while on, shell-bound
    /// keystrokes and pastes in the terminal go to every pane instead of
    /// just the focused one. Session-scoped; never persisted.
    pub broadcast_input: bool,
    /// True while the "enable broadcast?" confirm popup is up (enabling is
    /// gated: the classic footgun is typing into panes you forgot were
    /// listening).
    pub pending_broadcast_enable: bool,
    /// A runnable fence waiting on the confirm popup (#353): destructive-
    /// looking blocks and `{confirm}` fences ask before they type.
    pending_run_block: Option<PendingRunBlock>,
    /// Blocks whose output croft is still waiting for (#354).
    pending_captures: Vec<PendingCapture>,
    /// Captured output per fence, keyed by the pane name (which already
    /// encodes the document's path under the workspace) and the fence
    /// opener's source line. In memory for the session unless the fence
    /// said `{persist}`.
    block_outputs: std::collections::HashMap<(String, usize), crate::markdown::BlockOutput>,
    /// Paint the terminal panes' right-edge arrival-time gutter ("Terminal:
    /// Toggle Timestamps"). Session-scoped, off by default.
    pub show_terminal_timestamps: bool,
    /// Notification sinks from config.json `notifications` (#358).
    notifier: crate::notifications::Notifier,
    /// Compiled per-host pane accent rules from config.json `host_accents`.
    /// First match wins.
    host_accents: Vec<HostAccent>,
    /// Recently closed terminal panes parked for the undo-close grace window
    /// (Ghostty's undo, iTerm2's Undo Close Session): the PTY and child stay
    /// alive but hidden until Cmd+K ⇧T restores the newest or the tick reaps
    /// entries older than [`UNDO_CLOSE_GRACE`]. Newest last.
    pub closed_terminals: Vec<ClosedTerminal>,
    /// Recently closed editor tabs (VS Code "Reopen Closed Editor"): the
    /// path plus enough view state (pin, cursor, scroll) to restore the tab
    /// as it was. Newest last; Cmd+K ⇧W pops. Bounded at
    /// [`CLOSED_TAB_STACK_CAP`]; entries whose file has since vanished are
    /// skipped at reopen time.
    pub closed_tabs: Vec<ClosedTab>,
    /// VS Code-style Cmd+P / Ctrl+P quick-open file finder. None when
    /// the modal is closed.
    pub file_finder: Option<crate::widgets::file_finder::FileFinder>,
    /// The range the last hinted quick-open pick installed, and the file it
    /// was installed in: the next pick clears it if it is still the
    /// selection there, and nothing else, so a selection the user made by
    /// hand (or extended from it) survives a re-pick of the same file.
    quick_open_range: Option<(PathBuf, crate::widgets::editor::EditorSelection)>,
    /// VS Code-style Cmd+Shift+P / Ctrl+Shift+P command palette. None when
    /// the modal is closed.
    pub command_palette: Option<crate::widgets::command_palette::CommandPalette>,
    /// VS Code-style Cmd+Shift+O / Ctrl+Shift+O "Go to Symbol in Editor"
    /// picker (also Go to Line via a `:` prefix). None when the modal is closed.
    pub go_to_symbol: Option<crate::widgets::symbol_picker::SymbolPicker>,
    /// "Go to Symbol in Workspace" (`#` in Quick Open): query + merged
    /// `workspace/symbol` results across every running language server.
    pub workspace_symbols: Option<crate::widgets::workspace_symbols::WorkspaceSymbolPicker>,
    /// The newest `workspace/symbol` request id; stale replies are dropped.
    ws_symbols_request_id: Option<u64>,
    /// Armed by a picker keystroke; `workspace_symbols_dispatch_due` fires
    /// the request once the query has been still for the debounce window.
    ws_symbols_pending: Option<std::time::Instant>,
    /// Receiver for an in-flight MCP sidecar command's result (the off-thread
    /// worker delivers one [`crate::mcp::McpOutcome`] then disconnects). `None`
    /// when no extension command is running; polled each frame by `poll_mcp`.
    mcp_rx: Option<std::sync::mpsc::Receiver<crate::mcp::McpOutcome>>,
    /// While an extension command runs: when it started (drives the status-bar
    /// spinner frame) and its human label (the animated badge text). Both `None`
    /// when idle; set in `spawn_mcp_command`, cleared in `poll_mcp`.
    mcp_started: Option<std::time::Instant>,
    mcp_busy_label: Option<String>,
    /// "Debug: Attach to Python Process" picker (PEP 768). None when closed.
    /// Lists running CPython 3.14+ processes; selecting one spawns
    /// `pdb -p <pid>` in a PTY.
    pub process_picker: Option<crate::widgets::process_picker::ProcessPicker>,
    /// Active debug session: a debugpy DAP launch. None when not debugging.
    /// Polled each frame by [`App::poll_dap`], which mirrors the paused location
    /// into `editor.stop_line`.
    pub dap_session: Option<crate::dap::session::DapSession>,
    /// launch.json configurations discovered for the picker (#250); refreshed
    /// on every picker open so edits are picked up without a restart.
    debug_configs: Vec<crate::dap::configs::DebugConfig>,
    /// Compounds declared beside those configurations. Listed in the picker so
    /// a workspace's compounds are visible; launching one needs the
    /// multi-session model tracked in #310.
    debug_compounds: Vec<crate::dap::configs::Compound>,
    /// Name of the launch.json configuration F5 starts. `None` = the
    /// zero-config "Debug active file" behavior.
    selected_debug_config: Option<String>,
    /// A config launch parked behind its `preLaunchTask`: the task runs in
    /// its pane, and the FinishedCommand sweep launches (exit 0) or aborts
    /// (non-zero) when the matching command completes. Replaced by a newer
    /// F5, so only one launch can be pending.
    pending_debug_launch: Option<PendingDebugLaunch>,
    /// In-flight background `cargo test --no-run` for debug-a-test: the
    /// receiver yields the picked binary (or the build error) and the test
    /// name rides along for the launch. Drained per tick; a second request
    /// while one is pending is refused with a status line.
    pending_test_debug: Option<PendingTestDebug>,
    /// Variable `variablesReference`s the user has expanded in the Variables
    /// panel. Persisted across polls so re-fetched variables stay open.
    pub debug_expanded: std::collections::HashSet<i64>,
    /// Debugger watch expressions (#112), in display order. Session-scoped.
    pub watch_exprs: Vec<String>,
    /// Latest evaluate result per expression: `(value, success)`.
    pub watch_vals: std::collections::HashMap<String, (String, bool)>,
    /// The previous stop's values, for the changed-value highlight.
    watch_prev: std::collections::HashMap<String, String>,
    /// Armed by every `Stopped` event, consumed by the first
    /// `InspectionUpdated` that follows: the baseline rotates exactly once
    /// per stop. `InspectionUpdated` also fires for frame switches and
    /// variable expansions within the same stop, and rotating on those
    /// clobbered the baseline with the stop's own values — the changed
    /// highlight never fired (#112).
    watch_baseline_pending: bool,
    /// Debug console log: program stdout/stderr (DAP output events) plus REPL
    /// echoes and results. Capped; the tail is shown in the Run & Debug panel.
    pub debug_console: Vec<String>,
    /// True once the current/just-ended debug session stopped at least once
    /// (breakpoint / step / exception). Drives the "exited without hitting a
    /// breakpoint" end message. Reset when a new session starts.
    debug_ever_stopped: bool,
    /// zoxide-backed Explorer jump popup (Cmd+Z). None when closed. Opens
    /// only from the Explorer pane, so it never collides with the editor's
    /// Cmd+Z undo.
    pub zoxide_jump: Option<crate::widgets::zoxide_jump::ZoxideJump>,
    /// True while the zoxide popup is picking a folder to ADD to the
    /// workspace (#147) rather than re-rooting; reset on close.
    pub zoxide_add_folder: bool,
    pub branch_picker: Option<crate::widgets::branch_picker::BranchPicker>,
    /// Why the branch picker is open, so its Enter dispatches the right
    /// verb (checkout vs merge vs rebase vs delete vs create-from base).
    pub branch_purpose: BranchPurpose,
    /// The Source Control "⋯" title menu (open/expanded state + hit rects).
    pub scm_menu: crate::widgets::scm_menu::ScmMenuState,
    /// Single-line input modal for SCM ops that need a typed value
    /// (clone URL, branch rename, remote name/URL, tag name).
    pub input_prompt: Option<crate::widgets::input_prompt::InputPrompt>,
    /// Single-choice picker for SCM ops that act on one of a git-owned list
    /// (apply/pop/drop a stash, delete a tag, remove/push-to a remote).
    pub list_picker: Option<crate::widgets::list_picker::ListPicker>,
    /// Privileged control channel to this session's host when running under
    /// a persistent multiplayer session (docs/MULTIPLAYER.md); drives the
    /// participants picker's grant/revoke/disconnect actions. None outside
    /// a session host.
    pub session_channel: Option<crate::session_host::InnerChannel>,
    /// Roster last read from the session host's presence sidecar.
    pub session_participants: Vec<crate::session_host::Participant>,
    /// Whether the host's stale-image marker (#238) has already been
    /// announced, so the status hint fires once per session, not per poll.
    session_host_stale_seen: bool,
    /// Multiplayer: the participant whose keystrokes are currently flowing
    /// into this croft (from the host's typing attribution frames).
    session_typist: Option<u64>,
    /// Multiplayer: every participant's last-known caret, stashed when the
    /// typist changes and restored when they type again, so interleaved
    /// input drives per-participant carets in the shared buffer.
    session_carets: std::collections::HashMap<u64, SessionCaret>,
    /// Sidecar mtime at the last roster read, so the poll is a cheap stat.
    session_presence_mtime: Option<std::time::SystemTime>,
    /// Cadence gate for the presence poll (stat every 500ms, not every tick).
    last_session_presence_poll: std::time::Instant,
    /// Phase D independent-viewport collab session (docs/MULTIPLAYER.md):
    /// per-file replicated documents over the workspace's collab relay.
    /// None until the lazy connect in `poll_collab` succeeds.
    collab: Option<crate::collab::CollabSession>,
    /// The collab socket and role the launch tail exported, read once at
    /// startup. None when this croft is not a collab participant.
    collab_config: Option<(PathBuf, crate::collab::CollabRole)>,
    /// Throttle for the lazy relay connect (the owner starts before any
    /// guest has spawned the relay, so the first attempts fail by design).
    last_collab_connect: Option<std::time::Instant>,
    /// Per-file merge base harvested when the relay link died: the last
    /// replicated text every participant agreed on. A reconnect bootstrap
    /// replays only this side's offline delta against it (three-way with the
    /// owner's snapshot), so owner edits made during the outage survive.
    collab_offline_base: std::collections::HashMap<String, String>,
    /// Peers' last-known carets by site id. Painted as ghost carets in the
    /// peer's color when their file is active, with a name tag while the
    /// caret is inside its fade window.
    collab_carets: std::collections::HashMap<u64, CollabCaret>,
    /// The last caret this croft broadcast, so an unmoved cursor sends
    /// nothing on the tick.
    collab_caret_sent: Option<(String, usize, usize)>,
    /// Whether any caret name tag was inside its fade window last tick;
    /// flipping to false is the one redraw an expiring tag needs.
    collab_labels_visible: bool,
    /// Some while an AI pilot (`croft pair`) streams an edit into a shared
    /// file: drives the status badge and the gutter stop button; cleared by
    /// the pilot's StreamState(inactive) broadcast.
    collab_stream: Option<CollabStreamInfo>,
    /// The resident navigator (docs/MULTIPLAYER.md): the in-process pilot
    /// host, seated while the workspace's pair record is enabled. Dropping
    /// it tears the seat down (revert, hang up, grace-kill).
    pair_host: Option<crate::pair_host::PairHost>,
    /// Where the workspace's pair activation record lives. A field so tests
    /// point it at a tempdir instead of the real sessions dir.
    pair_record_path: PathBuf,
    /// The collab socket the navigator (and a self-appointed owner seat)
    /// uses. A field for the same test reason.
    pair_socket: PathBuf,
    /// Path of the single-host lock (see [`pair_host_lock`]). A field for the
    /// same test reason.
    pair_host_lock_path: PathBuf,
    /// Cadence gate for the pair-record stat (1s, not every tick).
    last_pair_check: Option<std::time::Instant>,
    /// Per-file (0-based row, body) snapshots of the navigator's anchored
    /// notes, refreshed each tick from the host; drives the gutter ◆ marks
    /// and the note popup.
    navigator_notes: std::collections::HashMap<String, Vec<(u64, usize, String)>>,
    /// The navigator's prose accumulated over the streaming turn; lands as
    /// one comment box at the turn's origin when the turn ends (boxes are
    /// the navigator's single voice — there is no OUTPUT channel for it).
    pair_commentary_buf: String,
    /// Where the current turn was invoked: (collab file key, 0-based row).
    /// Anchors the turn's commentary box.
    pair_turn_origin: Option<(String, usize)>,
    /// Notes the navigator left since its turn started, so the TurnDone
    /// status can surface them instead of overwriting the NoteAdded status.
    pair_notes_this_turn: usize,
    /// The file the turn's notes LAST landed in (anchors the turn's prose
    /// when the invocation origin is unknown).
    pair_last_noted_file: Option<String>,
    /// Every file the turn's notes landed in: the TurnDone hint names the
    /// file only when there is exactly one ("3 comments in b.rs" was a lie
    /// when two of them sat in a.rs).
    pair_noted_files: std::collections::BTreeSet<String>,
    /// Held while this croft is the self-appointed navigator owner: exactly
    /// one plain croft per workspace may host the pilot (and claim collab
    /// owner site 1). Released by the OS on exit, so a crashed host hands off.
    pair_host_lock: Option<crate::session::PairHostLock>,
    /// Set when the pilot died or failed to seat: suppresses the 1s re-seat
    /// so a broken claude (unauthenticated, missing, crashing) is not
    /// respawned forever. Cleared when the record is deactivated OR
    /// rewritten (any `croft pair` run re-arms seating, as the CLI
    /// promises), so an explicit off/on (or toggle) re-activates. Matches
    /// the LSP precedent: no auto-respawn within a session; a fresh croft
    /// retries.
    navigator_down: bool,
    /// The pair record's raw bytes at the last 1s check: changed bytes mean
    /// someone ran `croft pair` (even enabled→enabled — every write stamps
    /// the record, so no rewrite is byte-identical) and clear
    /// [`navigator_down`]. Content, not mtime: a same-grain rewrite on a
    /// coarse-timestamp filesystem keeps its mtime.
    last_pair_record_raw: Option<Vec<u8>>,
    /// Which host-lock refusal has already been announced: the losing
    /// window keeps polling for takeover every second, and re-announcing
    /// each poll clobbered its status line forever (and forced a 1 Hz
    /// repaint). The KIND is latched, not just the fact, so a refusal that
    /// changes reason (an fd limit clears and another window now holds the
    /// lock, or the reverse) is announced again rather than leaving a
    /// message that is no longer true (#337). Per kind, not per message: an
    /// open failure whose errno changes keeps the first announcement.
    pair_lock_denied: Option<PairLockDenial>,
    /// Proactive navigator looks (docs/MULTIPLAYER.md): a completed new
    /// construct plus a typing pause hands the seated navigator a
    /// comment-only turn on its own. Opt-out via
    /// `Prefs::disable_proactive_navigator` / the palette toggle.
    proactive_navigator_enabled: bool,
    /// Per file, the edit_seq the proactive trigger last scanned: one
    /// buffer state is parsed at most once, however long the pause lasts
    /// and however often the driver switches tabs across visited files.
    proactive_scanned: std::collections::HashMap<PathBuf, u64>,
    /// Test seam: builds the PairHost from the config (the real path spawns
    /// the claude CLI, which a test must never do).
    #[cfg(test)]
    #[allow(clippy::type_complexity)]
    pair_spawn_override:
        Option<Box<dyn Fn(&crate::pair::PairConfig) -> anyhow::Result<crate::pair_host::PairHost>>>,
    /// Rolling log of git commands croft has run and their summaries, shown
    /// read-only by the "Show Git Output" action (VS Code's Git channel).
    pub git_output_log: Vec<String>,
    /// Build diagnostics from the problem matchers (#119): finished-command
    /// output scanned into PROBLEMS entries, keyed by resolved file path.
    /// Paired with the producer that installed it (the pane uid, or
    /// `PROJECT_CHECK_ID` for the whole-project sweep). Without the pairing
    /// a re-run removed the whole entry and took the OTHER producer's rows
    /// with it, and the second producer to reach a file could not clear its
    /// own rows at all (#532).
    build_diagnostics:
        std::collections::HashMap<PathBuf, Vec<(u64, crate::widgets::problems::ProblemItem)>>,
    /// Which files each terminal pane contributed, keyed by the pane's
    /// STABLE uid (Vec positions shift on close/insert/reorder), so a
    /// pane's next scanned command replaces its previous run's diagnostics
    /// (VS Code clears a task's problems when the task re-runs).
    build_diag_files_by_pane: std::collections::HashMap<u64, Vec<PathBuf>>,
    /// True while the "Discard All Changes" confirmation modal is up.
    pub pending_discard_all: bool,
    /// The Replace All confirmation (#123): `(occurrences, files, dirty
    /// files to be skipped)` counted without writing; the modal shows them,
    /// Enter/Y commits, Esc cancels.
    pending_replace_all: Option<(usize, usize, usize)>,
    /// Cached workspace file index. Built lazily on first Cmd+P and
    /// shared across reopens so repeated invocations are instant.
    file_finder_index: Option<std::sync::Arc<Vec<crate::widgets::file_finder::FileEntry>>>,
    /// Background-build receiver: App::new spawns a thread that walks
    /// the workspace and sends the index here; Cmd+P opens against the
    /// hot index instead of walking on the UI thread. None once the
    /// index has been received (or if a build was never kicked off).
    file_finder_index_rx:
        Option<std::sync::mpsc::Receiver<Vec<crate::widgets::file_finder::FileEntry>>>,
    /// Set when a rebuild was requested while one was already in flight.
    /// poll_file_finder_index drains it on completion and re-kicks the
    /// background walker so a long-running rebuild (multi-GB monorepo)
    /// can never miss a later FS event that landed mid-walk.
    file_finder_index_dirty: bool,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum VimOp {
    #[default]
    None,
    G,
    Y,
}

#[derive(Clone, Copy, Debug, Default)]
struct EditorVimChord {
    op: VimOp,
    count: usize,
}

impl EditorVimChord {
    fn reset(&mut self) {
        self.op = VimOp::None;
        self.count = 0;
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EditorImageLayout {
    pub cell_x: u16,
    pub cell_y: u16,
    pub cell_w: u16,
    pub cell_h: u16,
    pub path: PathBuf,
    /// Which page of a PDF is baked into this overlay (1 for anything else).
    /// Part of the re-emit key so paging re-bakes on its own: without it the
    /// path and rect are unchanged on a page turn and the stale picture stays
    /// on screen unless every call site remembers to invalidate the layout.
    pub page: u32,
    /// Content stamp of the baked bytes ([`crate::widgets::editor::ImageView::generation`]).
    /// Part of the re-emit key so a file rebuilt on disk re-bakes even when
    /// the path, rect and page are all unchanged (a pdflatex rebuild lands
    /// on the same page the reader was on).
    pub generation: u64,
}

/// Re-emit key for the terminal pane's inline-image overlay: the cell rect
/// the picture occupies plus which image (per-pane `seq`) and pane it is.
/// Scrolling moves the anchor row, changing `cell_y` — a layout mismatch —
/// so the overlay clears and re-emits at the new position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TerminalImageLayout {
    pub cell_x: u16,
    pub cell_y: u16,
    pub cell_w: u16,
    pub cell_h: u16,
    pub seq: u64,
    pub pane: usize,
}

/// Markdown-preview inline image placement (#176): geometry plus the
/// bake identity (path + mtime), so an externally rewritten picture
/// re-bakes and a pure scroll reuses the payload.
#[derive(Clone, Debug, PartialEq)]
pub struct MarkdownImageLayout {
    pub cell_x: u16,
    pub cell_y: u16,
    pub cell_w: u16,
    pub cell_h: u16,
    pub path: PathBuf,
    pub mtime_ms: u128,
}

/// Which edge of the editor pane the minimap strip sits on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MinimapSide {
    Left,
    Right,
}

/// Width of the minimap strip in cells (the user picked the ~6-cell option).
const MINIMAP_WIDTH_CELLS: u16 = 6;
/// Minimum editor-text width that must remain after carving the strip; below
/// this the minimap is suppressed so the code never gets squeezed to nothing.
const MINIMAP_MIN_EDITOR_WIDTH: u16 = 44;
/// Maximum pixel height per source line in the minimap. Only kicks in for very
/// short files: it caps a six-line file to a compact sliver instead of
/// stretching those lines down the whole strip. Any file long enough that its
/// natural fit is already <= this (roughly > a screenful) fills the strip
/// exactly as a plain whole-file fit would, so normal files are unaffected.
const MINIMAP_MAX_LINE_PX: u32 = 6;

/// Cached full-document raster for the minimap. The expensive part (walking
/// every line's syntax spans) runs only when `sig` changes; scrolling reuses
/// `rgba` and just re-composites the viewport box on top.
struct MinimapBase {
    rgba: Vec<u8>,
    w: u32,
    h: u32,
    /// (path, edit_seq, canvas_w_px, canvas_h_px, bg) — a change rebakes.
    sig: (Option<PathBuf>, u64, u32, u32, (u8, u8, u8)),
}

/// Re-emit key for the minimap overlay. Differs from the base sig: the
/// viewport fields move on scroll (recomposite, no rebake), the cell fields
/// move on resize/layout.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MinimapLayout {
    cell_x: u16,
    cell_y: u16,
    cell_w: u16,
    cell_h: u16,
    top: usize,
    rows: usize,
    total: usize,
    edit_seq: u64,
    side: MinimapSide,
    /// Theme editor bg; a change here (theme switch) forces a rebake.
    bg: (u8, u8, u8),
    /// Active selection `(start_row, end_row)`; a change recomposites the band.
    selection: Option<(usize, usize)>,
}

/// One socket-poll result. `hits` is the pane-subtree scan that decides what to
/// surface; `listening` is every loopback port on the box, the only set that can
/// say a port has stopped. `None` when neither probe ran.
struct PortPoll {
    hits: Vec<crate::port_detect::PortHit>,
    listening: Option<std::collections::HashSet<u16>>,
}

/// The per-frame minimap overlays (everything not baked into the raster).
struct MinimapOverlay {
    /// First visible line, and number of visible lines (the viewport box).
    top: usize,
    rows: usize,
    total: usize,
    light: bool,
    /// Active selection `(start_row, end_row)`, marked by a thin left accent.
    selection: Option<(usize, usize)>,
    sel_rgb: (u8, u8, u8),
    /// Pixel height the lines are mapped into (top-aligned); `<= h` for short
    /// files so the viewport box and selection accent track the raster.
    content_h: u32,
}

/// Composite the per-frame overlays onto the cached raster: the translucent
/// viewport box (style A) blending the visible-line rows toward white (dark
/// theme) or black (light), plus a thin left-edge accent in the selection color
/// marking the selected rows. The accent is deliberately tiny so the minimap's
/// look and feel is unchanged. Returns a fresh buffer.
fn composite_minimap_viewport(base: &[u8], w: u32, h: u32, ov: MinimapOverlay) -> Vec<u8> {
    let MinimapOverlay {
        top,
        rows,
        total,
        light,
        selection,
        sel_rgb,
        content_h,
    } = ov;
    let mut buf = base.to_vec();
    if total == 0 || w == 0 || h == 0 {
        return buf;
    }
    // Map a 0-based line index to a pixel row, matching `minimap_rgba`'s
    // top-aligned `content_h` scale.
    let row_y = |line: usize| (line as u64 * content_h as u64 / total as u64) as u32;
    // Blend cols `x0..x1` of rows `r0..r1` toward `tint` by alpha `a` (0..=255).
    let band = |buf: &mut [u8], r0: u32, r1: u32, x0: u32, x1: u32, tint: [u16; 3], a: u16| {
        for y in r0..r1.min(h) {
            for x in x0..x1.min(w) {
                let idx = ((y * w + x) * 4) as usize;
                for k in 0..3 {
                    let c = buf[idx + k] as u16;
                    buf[idx + k] = ((c * (255 - a) + tint[k] * a) / 255) as u8;
                }
            }
        }
    };
    // Viewport box: a translucent fill plus a crisp bright border so "where am
    // I" is unmistakable. Clamp the visible range to the line count so an
    // all-visible short file's box covers only its content, not the empty
    // strip below it.
    let y0 = row_y(top);
    let y1 = row_y((top + rows).min(total)).clamp(y0 + 1, h);
    // Fill (toward white on dark, black on light), then the four edges at a
    // much higher alpha so the rectangle outline reads against both the dark
    // strip and the colored code.
    let fill: [u16; 3] = if light { [0, 0, 0] } else { [255, 255, 255] };
    let edge: [u16; 3] = if light { [20, 20, 20] } else { [235, 240, 250] };
    band(&mut buf, y0, y1, 0, w, fill, 46);
    band(&mut buf, y0, y0 + 1, 0, w, edge, 200); // top
    band(&mut buf, y1.saturating_sub(1), y1, 0, w, edge, 200); // bottom
    band(&mut buf, y0, y1, 0, 1, edge, 200); // left
    band(&mut buf, y0, y1, w.saturating_sub(1), w, edge, 200); // right
    // Selection: a thin (~2-3px) accent stripe down the left edge of the
    // selected rows, in the selection color. Tiny on purpose.
    if let Some((s, e)) = selection {
        let r0 = row_y(s);
        let r1 = row_y(e + 1).clamp(r0 + 1, h);
        let aw = (w / 12).clamp(1, 3);
        band(
            &mut buf,
            r0,
            r1,
            0,
            aw,
            [sel_rgb.0 as u16, sel_rgb.1 as u16, sel_rgb.2 as u16],
            210,
        );
    }
    buf
}

/// Encode an RGBA pixel buffer to PNG (the format `build_inline_image` wants).
fn rgba_to_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
    let img: image::RgbaImage = image::ImageBuffer::from_raw(w, h, rgba)?;
    let mut out = Vec::new();
    image::DynamicImage::ImageRgba8(img)
        .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
        .ok()?;
    Some(out)
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum SplitterDrag {
    Sidebar,
    Terminal,
    /// Dragging a seam between two editor groups in the grid. Carries the seam
    /// snapshot taken at mouse-down (stable for the drag's duration), so the
    /// drag adjusts exactly that boundary in a grid of any depth.
    EditorSeam(editor_layout::Seam),
}

/// Minimum width in cells of either editor column while split, so a drag
/// can't collapse a pane to nothing.
const EDITOR_SPLIT_MIN: u16 = 10;

/// Maximum pinned sticky-scroll header rows (VS Code's default is 5).
const STICKY_SCROLL_MAX: usize = 5;

const SIDEBAR_WIDTH_DEFAULT: u16 = 32;
const SIDEBAR_WIDTH_MIN: u16 = 12;
const TERMINAL_HEIGHT_MIN: u16 = 3;
const EDITOR_HEIGHT_MIN: u16 = 3;
/// Shortest frame that still shows the on-screen keyboard band; below this
/// the workspace would be unusably squeezed, so the band collapses instead.
const OSK_MIN_FRAME_HEIGHT: u16 = 16;
const RIGHT_PANE_MIN: u16 = 20;
/// Minimum width of the zoxide jump popup. The Explorer column it anchors
/// over is typically ~32 cells, too narrow to read frecency paths like
/// `~/Documents/platform/app/...`, so the box widens rightward to at least
/// this many cells (capped to the frame) while staying left-anchored on
/// the Explorer.
const ZOXIDE_JUMP_MIN_WIDTH: u16 = 56;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WelcomeLayout {
    cell_x: u16,
    cell_y: u16,
    cell_w: u16,
    cell_h: u16,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScpUpload {
    pub alias: String,
    pub src: PathBuf,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingRemotePull {
    pub request_id: String,
    pub src_display: String,
    pub basename: String,
    pub dest_dir: PathBuf,
    pub started_at: std::time::Instant,
    pub kind: RemotePullKind,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RemotePullKind {
    /// File or directory copied from the user's local Mac into the
    /// inbox; on completion the relay file is moved into `dest_dir`.
    File,
    /// Local-Mac clipboard contents staged at `<inbox>/<id>/clipboard.txt`;
    /// on completion the bytes are pasted into the focused terminal.
    Clipboard,
    /// URL handed to the user's local Mac `open(1)`; on completion croft
    /// just surfaces a status confirmation. No payload is shipped back.
    Open,
    /// Remote loopback port forwarded home over the SSH master; the `.ok`
    /// payload carries the chosen local port, which croft records so the PORTS
    /// panel can label and open it. `remote_port` is the port being forwarded.
    Forward { remote_port: u16 },
}

const REMOTE_PULL_TIMEOUT: Duration = Duration::from_secs(120);

/// How long the port-detection toast lingers before auto-dismissing.
const PORT_TOAST_TTL: Duration = Duration::from_secs(12);
/// How often the socket-table poll runs (the output scrape is continuous;
/// this is the backstop for servers that announce nothing).
const PORT_POLL_INTERVAL: Duration = Duration::from_secs(3);
/// How often terminal pane labels are refreshed from their foreground process.
const TERMINAL_LABEL_INTERVAL: Duration = Duration::from_millis(1500);

struct RemoteLaunch {
    host: String,
    path: Option<String>,
    adopted: Option<crate::remote::AdoptedMaster>,
}

fn split_at_char_count(s: &str, count: usize) -> (String, String) {
    let left: String = s.chars().take(count).collect();
    let right: String = s.chars().skip(count).collect();
    (left, right)
}

fn wrap_cells_variable_width(text: &str, first_width: u16, rest_width: u16) -> Vec<String> {
    let first_width = first_width.max(1) as usize;
    let rest_width = rest_width.max(1) as usize;
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return vec![String::new()];
    }

    let mut lines = Vec::new();
    let mut current = String::new();
    for word in trimmed.split_whitespace() {
        let mut remaining = word.to_string();
        while !remaining.is_empty() {
            let width = if lines.is_empty() {
                first_width
            } else {
                rest_width
            };
            let sep = usize::from(!current.is_empty());
            let remaining_len = remaining.chars().count();
            let current_len = current.chars().count();
            if current_len + sep + remaining_len <= width {
                if sep == 1 {
                    current.push(' ');
                }
                current.push_str(&remaining);
                break;
            }
            if !current.is_empty() {
                lines.push(std::mem::take(&mut current));
                continue;
            }
            let (head, tail) = split_at_char_count(&remaining, width);
            lines.push(head);
            remaining = tail;
        }
    }
    if !current.is_empty() {
        lines.push(current);
    }
    if lines.is_empty() {
        vec![String::new()]
    } else {
        lines
    }
}

/// Cells reserved at the left of each highlight row for the kind glyph plus
/// a one-cell gap before the summary text.
const WELCOME_NOTE_GUTTER: u16 = 2;

fn welcome_note_summary_width(block_w: u16) -> u16 {
    block_w.saturating_sub(WELCOME_NOTE_GUTTER).max(1)
}

fn wrapped_welcome_note_summary(
    note: &crate::release_notes::ReleaseNote,
    block_w: u16,
) -> Vec<String> {
    let w = welcome_note_summary_width(block_w);
    wrap_cells_variable_width(note.summary, w, w)
}

fn welcome_note_row_height(note: &crate::release_notes::ReleaseNote, block_w: u16) -> u16 {
    wrapped_welcome_note_summary(note, block_w).len().max(1) as u16
}

/// Width of the release-note card's content area for a card spanning
/// `block_w` cells: one border cell plus a one-cell inset on each side.
/// The height measure and the paint pass MUST both wrap through this —
/// measuring 2 cells wider than the paint made the paint produce more
/// wrapped lines than the card reserved rows for, and the overflow rows
/// were silently dropped, ending the note mid-sentence (#99).
fn welcome_card_inner_width(block_w: u16) -> u16 {
    block_w.saturating_sub(4)
}

fn welcome_recents_height(notes: &[crate::release_notes::ReleaseNote], block_w: u16) -> u16 {
    if notes.is_empty() {
        return 0;
    }
    // Header row + one blank row + each highlight (which may wrap).
    let notes_h: u16 = notes
        .iter()
        .map(|n| welcome_note_row_height(n, block_w))
        .sum();
    1 + 1 + notes_h
}

const WELCOME_TAGLINE: &str = "LIGHTWEIGHT.  BLAZINGLY FAST.  BUILT FOR DEVELOPERS.";

use crate::gradient::{GRAD_TL, GRAD_TR, POPUP_SEL_BG, paint_gradient_box, rgb_color};

fn open_url(url: &str) -> Result<()> {
    #[cfg(target_os = "macos")]
    let mut cmd = {
        let mut c = std::process::Command::new("open");
        c.arg(url);
        c
    };
    #[cfg(target_os = "linux")]
    let mut cmd = {
        let mut c = std::process::Command::new("xdg-open");
        c.arg(url);
        c
    };
    #[cfg(target_os = "windows")]
    let mut cmd = {
        let mut c = std::process::Command::new("cmd");
        c.args(["/C", "start", "", url]);
        c
    };
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let mut cmd = {
        let mut c = std::process::Command::new("open");
        c.arg(url);
        c
    };
    // Detach the opener's stdio: croft is on the alternate screen in raw
    // mode, and `open`/`xdg-open` chatter ("No application knows how to
    // open URL ...") would land straight on the grid.
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    cmd.spawn().with_context(|| format!("opening {url}"))?;
    Ok(())
}

/// Short label for this machine, shown as the origin of a remote port in the
/// PORTS panel (`⇄ build-box`). Resolved once via `hostname`, falling back to a
/// generic word so the column is never blank.
fn remote_host_label() -> String {
    static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    HOST.get_or_init(|| {
        std::process::Command::new("hostname")
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().split('.').next().unwrap_or("remote").to_string())
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| String::from("remote"))
    })
    .clone()
}

/// What activating a PORTS row (Enter / double-click) should do, computed from
/// the entry and whether this is a remote (relay-active) session. Pure so it's
/// testable without spawning a browser or standing up a relay.
#[derive(Debug, Clone, PartialEq, Eq)]
enum PortOpenAction {
    /// Remote port not yet forwarded: forward it home, then open.
    Forward(u16),
    /// A locally reachable address to open in the user's browser via the relay
    /// — a remote session, so the opener must run on the local Mac, not the
    /// headless remote.
    OpenViaRelay(String),
    /// A locally reachable address to open directly (local session).
    OpenDirect(String),
    /// Nothing actionable.
    Nothing,
}

fn plan_port_open(entry: &crate::widgets::ports::PortEntry, relay_active: bool) -> PortOpenAction {
    use crate::widgets::ports::PortOrigin;
    if matches!(entry.origin, PortOrigin::Remote(_)) && !entry.forwarded {
        return PortOpenAction::Forward(entry.port);
    }
    match entry.open_url() {
        Some(url) if relay_active => PortOpenAction::OpenViaRelay(url),
        Some(url) => PortOpenAction::OpenDirect(url),
        None => PortOpenAction::Nothing,
    }
}

impl App {
    pub fn new(root: PathBuf) -> Result<Self> {
        // Reap any js-debug adapter tree a previous croft left orphaned (a
        // crash or force-quit skips `DapTransport`'s `Drop`, so the server +
        // its detached watchdog get reparented to init and linger). Runs on a
        // detached thread to stay off the time-to-first-frame critical path,
        // and is safe even while another croft session is live: only processes
        // reparented to init are touched. See `crate::dap::reaper`.
        crate::dap::reaper::reap_orphaned_js_debug_async(std::time::Duration::ZERO);
        let tree = FileTree::new(root.clone());
        let search = SearchPanel::new(root.clone());
        let remote = RemotePanel::new();
        let source_control = SourceControlPanel::new();
        let run_debug = RunDebugPanel::new();
        let extensions = crate::widgets::extensions::ExtensionsPanel::new();
        let outline = OutlinePanel::new();
        let open_editors = OpenEditorsPanel::new();
        let timeline = TimelinePanel::new();
        let mut dependencies = DependenciesPanel::new();
        // Detect the workspace's package ecosystems up front so the DEPENDENCIES
        // section's visibility, ⋯-menu entry, and header are correct before the
        // first sync tick. Re-detected on every re-root (see sync_explorer_panels).
        let dep_ecosystems = crate::widgets::dependencies::detect_ecosystems(&root);
        dependencies.set_header(crate::widgets::dependencies::header_label(&dep_ecosystems));
        // Layered settings (#251): defaults ← user ← user-local ← workspace
        // layers of the primary root, one merged view. Warnings (refused
        // workspace keys, parse errors) land in the Settings OUTPUT channel.
        let merged_settings = crate::config_layers::load_merged(Some(&root));
        for w in &merged_settings.warnings {
            crate::output::push("Settings", crate::output::OutputLevel::Warn, w);
        }
        let loaded_prefs = merged_settings.prefs.clone();
        // Seed the log view's opening default from the saved preference
        // BEFORE any log can be opened (#466): the toggle keeps the two in
        // step afterwards, but a startup that set only `App::log_highlight`
        // opened the first log highlighted despite a saved opt-out. Test-
        // inert like the keymap and matcher loads below: the suite builds
        // hundreds of apps on parallel threads, and an unguarded write to
        // the process-wide default from each would race the tests that
        // read it; those call `seed_log_highlight_default` explicitly.
        seed_log_highlight_default_at_startup(!loaded_prefs.disable_log_highlight);
        // Same treatment for keybindings: a row croft refused (an unknown
        // command id, a gesture that can never fire, a reserved bare click)
        // used to vanish silently, which reads as croft being broken rather
        // than the binding being wrong (#259).
        // Under test an empty keymap, exactly like the matcher set below: the
        // developer's real keybindings.json must never steer app tests. That
        // mattered less when a user keymap only rebound key chords, which no
        // test dispatches; a mouse row now gates an early return at the top
        // of `handle_mouse` that every mouse test flows through, so one line
        // in a file the suite does not control could redirect thousands of
        // tests. Tests that want a keymap assign `app.keymap` themselves.
        let loaded_keymap = if cfg!(test) {
            crate::keymap::Keymap::default()
        } else {
            crate::keymap::Keymap::load(&crate::keymap::keybindings_path())
        };
        // `Keymap::load` already reports its own warnings to OUTPUT ·
        // Keybindings, so nothing to do here.
        // Problem matchers (#252). Under test an empty set: the developer's
        // real matchers.json must never steer app tests; tests inject their
        // own. Compile warnings surface once, in OUTPUT · Matchers.
        let matchers = std::sync::Arc::new(if cfg!(test) {
            crate::problem_matchers::MatcherSet::default()
        } else {
            crate::problem_matchers::MatcherSet::load(
                &crate::problem_matchers::matchers_path(),
                Some(&crate::problem_matchers::workspace_matchers_path(&root)),
            )
        });
        for w in &matchers.warnings {
            crate::output::push("Matchers", crate::output::OutputLevel::Warn, w);
        }
        let watch_set = std::sync::Arc::new(matchers.watch_set());
        let explorer_views = ExplorerViewVisibility::from_prefs(loaded_prefs.explorer_views);
        let disabled_extensions = loaded_prefs.disabled_extensions.clone();
        let (timeline_tx, timeline_rx) = std::sync::mpsc::channel();
        let (history_done_tx, history_done_rx) = std::sync::mpsc::channel();
        let (project_check_tx, project_check_rx) = std::sync::mpsc::channel();
        let (project_hint_tx, project_hint_rx) = std::sync::mpsc::channel();
        let (test_jump_tx, test_jump_rx) = std::sync::mpsc::channel();
        let (graph_tx, graph_rx) = std::sync::mpsc::channel();
        let (blame_tx, blame_rx) = std::sync::mpsc::channel();
        let (deps_tx, deps_rx) = std::sync::mpsc::channel();
        let (voice_tx, voice_rx) = std::sync::mpsc::channel();
        let editor = EditorTabs::new();
        // Bound before the first pane, so that pane's shell carries the
        // socket like every later one. `spawn_with_preamble` reads
        // `view_ipc::SOCK_PATH` at spawn time, so this ordering is what
        // decides whether the startup pane can use `croft view` at all (#362).
        let view_listener = Self::bind_view_socket();
        let view_bind_error = VIEW_BIND_ERROR.lock().unwrap().take();
        let term = PtyTerminal::new(&root).context("spawning terminal")?;

        // Background git worker: every `git status` / `git status
        // --porcelain` shell-out goes through this channel instead of
        // running on the UI thread. The very first request seeds the
        // status-bar badge; subsequent ones come from the FS watcher
        // and from sidebar-icon clicks (see `refresh_source_control`,
        // `refresh_git_status_debounced`). Removes the 15-50 ms
        // input-to-paint stall that used to fire on every Source
        // Control click.
        let git = GitWorker::spawn(root.clone());

        let welcome = WelcomeState::new();
        let ext_index_refresh = Some(crate::mcp::registry_index::spawn_refresh());

        let (search_query_tx, search_query_rx) = std::sync::mpsc::channel();
        let (search_results_tx, search_results_rx) = std::sync::mpsc::channel();
        let (port_poll_tx, port_poll_rx) = std::sync::mpsc::channel();
        let (fleet_tx, fleet_rx) = std::sync::mpsc::channel();
        let (label_tx, label_rx) = std::sync::mpsc::channel();
        let (ssh_tx, ssh_rx) = std::sync::mpsc::channel();
        let search_root = root.clone();
        std::thread::spawn(move || {
            crate::widgets::search::search_worker_loop(
                search_root,
                search_query_rx,
                search_results_tx,
            );
        });
        // Pre-build the Cmd+P file index on a background thread so the
        // first Cmd+P keystroke does not stall the UI for the length
        // of a workspace walk. The result is delivered via channel;
        // open_file_finder calls poll_file_finder_index to consume it.
        let (file_finder_index_tx, file_finder_index_rx) =
            std::sync::mpsc::channel::<Vec<crate::widgets::file_finder::FileEntry>>();
        let index_root = root.clone();
        std::thread::spawn(move || {
            let entries = crate::widgets::file_finder::build_file_index(&index_root);
            let _ = file_finder_index_tx.send(entries);
        });
        let fs_watch = FsWatch::spawn(&root, &tree);
        // Persisted layout preferences (Customize Layout popup). Skipped under
        // test so the suite never reads/writes the developer's ~/.config,
        // mirroring the theme load above.
        let layout_prefs = if cfg!(test) {
            crate::prefs::LayoutPrefs::default()
        } else {
            loaded_prefs.layout
        };
        let mut app = Self {
            tree,
            search,
            remote,
            source_control,
            commit_graph: crate::widgets::commit_graph::CommitGraphPanel::new(),
            graph_rx,
            graph_revspec: None,
            graph_tx,
            graph_fetch_inflight: false,
            graph_refetch_queued: false,
            run_debug,
            testing: crate::widgets::testing::TestingPanel::new(),
            test_worker: crate::testing::worker::TestWorker::spawn(root.clone()),
            extensions,
            vscode_listed: Vec::new(),
            disabled_extensions,
            // Built from `loaded_keymap` above, which applies the same
            // cfg!(test) guard main landed here independently: the
            // developer's real keybindings.json must never steer app tests.
            // Hoisted rather than inlined so the parse warnings can be
            // reported once, in OUTPUT · Keybindings.
            keymap: loaded_keymap,
            last_mouse_pos: None,
            macro_recording: None,
            macro_last: None,
            macro_registers: crate::macros::load(&crate::macros::macros_path()),
            macro_replaying: false,
            macros_path: crate::macros::macros_path(),
            snippets: crate::snippets::SnippetSet::load(&crate::snippets::snippets_path()),
            format_on_save: loaded_prefs.format_on_save,
            copy_on_select: loaded_prefs.copy_on_select,
            log_highlight: !loaded_prefs.disable_log_highlight,
            secret_redaction: !loaded_prefs.disable_secret_redaction,
            redaction_reveal_until: None,
            auto_save: loaded_prefs.auto_save,
            auto_save_on_focus_change: loaded_prefs.auto_save_on_focus_change,
            last_focus_signature: None,
            save_after_format: None,
            outline,
            open_editors,
            timeline,
            dependencies,
            dep_ecosystems,
            explorer_views,
            settings_chain: merged_settings.chain,
            settings_provenance: merged_settings.provenance,
            timeline_rx,
            timeline_tx,
            history_done_rx,
            history_done_tx,
            project_check_rx,
            project_check_tx,
            project_check_running: false,
            project_check_rows: 0,
            project_hint_rx,
            project_hint_tx,
            project_check_hinted: false,
            problems_project_scope: if loaded_prefs.problems_project_scope.is_empty() {
                String::from("auto")
            } else {
                loaded_prefs.problems_project_scope.clone()
            },
            test_jump_rx,
            test_jump_tx,
            timeline_fetched: None,
            blame_rx,
            blame_tx,
            blame_fetched: None,
            inline_blame_enabled: !loaded_prefs.disable_inline_blame,
            provenance_overlay: false,
            indent_guides_enabled: !loaded_prefs.disable_indent_guides,
            bracket_colors_enabled: !loaded_prefs.disable_bracket_colors,
            whitespace_mode: crate::widgets::editor::WhitespaceMode::from_pref(
                &loaded_prefs.render_whitespace,
            ),
            diff_ws_default: crate::widgets::diff::DiffWhitespace::from_config(
                &loaded_prefs.diff_ignore_whitespace,
            ),
            inline_values_enabled: !loaded_prefs.disable_inline_values,
            auto_close_pairs: !loaded_prefs.disable_auto_close_pairs,
            inlay_hints_enabled: !loaded_prefs.disable_inlay_hints,
            // Keep the suite off the user's real ~/.config/croft/history: a
            // per-process temp root in test builds, the real dir otherwise.
            history_root: if cfg!(test) {
                std::env::temp_dir().join(format!("croft-test-history-{}", std::process::id()))
            } else {
                crate::history::history_dir()
            },
            history_restore: None,
            deps_rx,
            deps_tx,
            deps_fetched: None,
            voice_rx,
            voice_tx,
            voice_handle: None,
            voice_canceling: false,
            editor,
            editor_layout: editor_layout::EditorLayout::single(),
            force_save_armed: false,
            terminals: vec![term],
            active_terminal: 0,
            perf: PerfHud::default(),
            roots: crate::workspace::WorkspaceRoots::single(root.clone()),
            sidebar_view: SidebarView::Explorer,
            sidebar_areas: SidebarAreas::default(),
            // Read the persisted theme from the real config only outside tests;
            // under test fall back to the default so the suite stays hermetic
            // and never depends on (nor mutates) the developer's ~/.config. This
            // mirrors the cfg!(test) write-skip in `apply_theme`.
            theme: if cfg!(test) {
                crate::theme::Theme::default()
            } else {
                loaded_prefs.theme()
            },
            focus: Pane::Tree,
            show_tree: true,
            show_terminal: true,
            terminal_maximized: false,
            activity_bar_visible: layout_prefs.activity_bar,
            status_bar_visible: layout_prefs.status_bar,
            side_bar_position: layout_prefs.side_bar_position,
            secondary_side_bar_visible: layout_prefs.secondary_side_bar,
            panel_alignment: layout_prefs.panel_alignment,
            quick_input_position: layout_prefs.quick_input_position,
            zen_mode: false,
            sidebar_auto_hide: loaded_prefs.sidebar_auto_hide,
            sidebar_auto_hide_suspended: false,
            sidebar_pinned_open: false,
            sidebar_dwell: SidebarDwell::default(),
            pre_zen: None,
            layout_icon_areas: LayoutIconAreas::default(),
            status: view_status(view_bind_error.as_deref()),
            persistence_warning: remote_persistence_status(
                is_remote_session(),
                std::env::var_os("CROFT_SESSION_PERSISTENT").is_some(),
            ),
            quit: false,
            drop_to_local: false,
            is_remote: is_remote_session(),
            context_menu: None,
            prompt: None,
            fs_watch,
            fs_watch_extra: Vec::new(),
            git_extra: Vec::new(),
            active_scm_root: root.clone(),
            scm_pin: None,
            scm_follow_root: root.clone(),
            active_test_root: root.clone(),
            pending_workspace_folders: None,
            git_head_oids: std::collections::BTreeMap::new(),
            git,
            cursor_blink: CursorBlink::new(),
            editor_click: ClickTracker::default(),
            tree_click: ClickTracker::default(),
            terminal_click: ClickTracker::default(),
            modified_click: ModifiedClickTracker::default(),
            ports_click: ClickTracker::default(),
            terminal_select_autoscroll: None,
            scrollbar_drag: None,
            editor_hscrollbar_drag: false,
            outline_scrollbar_drag: false,
            open_editors_scrollbar_drag: false,
            timeline_scrollbar_drag: false,
            deps_scrollbar_drag: false,
            testing_scrollbar_drag: false,
            graph_scrollbar_drag: false,
            welcome,
            ext_index_refresh,
            ext_index_manual_refresh: false,
            search_query_tx,
            search_results_rx,
            cell_pixel: None,
            last_pdf_wheel: None,
            formula_overwrite_armed: false,
            scm_change_badge: None,
            scm_change_badge_count: 0,
            explorer_unsaved_badge: None,
            explorer_unsaved_count: 0,
            remote_ports_badge: None,
            remote_ports_count: 0,
            testing_badge: None,
            testing_badge_count: 0,
            problems_badge_count: 0,
            problems_badge_cell: None,
            inline_protocol: crate::iterm2_inline::detect_inline_image_protocol(),
            sixel_supported: false,
            resize_repaint_needed: false,
            minimap_visible: true,
            minimap_side: MinimapSide::Right,
            minimap_base: None,
            minimap_img_rect: Rect::default(),
            minimap_content_h: 0,
            minimap_drag: false,
            clipboard_reader: read_system_clipboard,
            is_relay_session: !cfg!(test) && std::env::var_os("CROFT_RELAY_KEY").is_some(),
            remote_launch: None,
            pending_remote_launch_host: None,
            pending_remote_launch_path: None,
            ssh_offer: None,
            ssh_offer_seen: std::collections::BTreeMap::new(),
            ssh_rx,
            ssh_tx,
            remote_offer_disabled: loaded_prefs.disable_remote_offer,
            remote_offer_excluded: loaded_prefs.remote_offer_excluded_hosts.clone(),
            fleet_groups: loaded_prefs.fleet_groups.clone(),
            remote_offer_refused: crate::remote::load_refused_hosts(
                &crate::remote::refused_hosts_path(&croft_cache_dir()),
                std::time::SystemTime::now(),
            ),
            lane_agent: loaded_prefs.lane_agent.clone(),
            lane_panes: std::collections::BTreeMap::new(),
            tree_clipboard: None,
            tree_typeahead: None,
            compare_anchor: None,
            last_frame_area: Rect::default(),
            last_sidebar_area: None,
            tree_drag: None,
            pending_scp_uploads: Vec::new(),
            pending_remote_pulls: Vec::new(),
            view_listener,
            pending_local_open: None,
            pending_discard: None,
            pending_revert_hunk: None,
            run_tasks: Vec::new(),
            last_task: None,
            pending_terminal_warning: false,
            commit_menu_open: false,
            default_branch_label: None,
            trust_local_browser: false,
            sidebar_width: SIDEBAR_WIDTH_DEFAULT,
            terminal_height: None,
            splitter_drag: None,
            editor_seams: Vec::new(),
            sidebar_splitter_x: None,
            terminal_splitter_y: None,
            terminal_add_buttons: Vec::new(),
            terminal_profile_buttons: Vec::new(),
            terminal_close_buttons: Vec::new(),
            terminal_collapse_buttons: Vec::new(),
            consented_extensions: crate::prefs::Prefs::load_or_default().mcp_consented,
            config_dir: crate::prefs::config_dir(),
            scrollback_dir: crate::session_state::dirs_cache_croft().join("scrollback"),
            terminal_strip_rects: Vec::new(),
            terminal_max_buttons: Vec::new(),
            terminal_rail_rects: Vec::new(),
            terminal_rail_area: Rect::default(),
            terminal_rail_scroll: 0,
            terminal_rail_revealed: None,
            terminal_label_rects: Vec::new(),
            terminal_drag_from: None,
            terminal_pointer_forwarded: None,
            terminal_pane_maximized: false,
            bottom_panel_tab: BottomPanelTab::Terminal,
            problems: crate::widgets::problems::ProblemsPanel::new(),
            output: crate::widgets::output::OutputPanel::new(),
            ports: crate::widgets::ports::PortsPanel::new(),
            captures: crate::widgets::captures::CapturesPanel::new(),
            port_toast: None,
            last_port_poll: std::time::Instant::now(),
            port_poll_rx,
            fleet_rx,
            fleet_tx,
            fleet_running: false,
            port_poll_tx,
            port_poll_inflight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            last_label_refresh: std::time::Instant::now(),
            label_rx,
            label_tx,
            label_inflight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            problems_tab_rect: Rect::default(),
            output_tab_rect: Rect::default(),
            ports_tab_rect: Rect::default(),
            captures_tab_rect: Rect::default(),
            terminal_tab_rect: Rect::default(),
            pointer_cell: None,
            hovered_activity_icon: None,
            hovered_layout_icon: None,
            osk: None,
            osk_auto: crate::iterm2_inline::detect_osk_auto(),
            last_content_width: 0,
            last_content_height: 0,
            lsp: match crate::lsp::LspManager::new(root.clone()) {
                Ok(m) => Some(m),
                Err(e) => {
                    eprintln!("lsp manager init failed: {e}");
                    None
                }
            },
            lsp_last_seen: std::collections::HashMap::new(),
            semantic_generation_seen: std::collections::HashMap::new(),
            problems_open_set: std::collections::BTreeSet::new(),
            lsp_diagnostics: std::collections::HashMap::new(),
            lsp_progress: std::collections::HashMap::new(),
            completion_popup: None,
            editor_vim_chord: EditorVimChord::default(),
            cmd_k_leader: None,
            vim: crate::vim::VimState::new(),
            vim_last_find: None,
            vim_visual_line: false,
            shortcuts_modal: None,
            shortcuts_hit_rect: None,
            status_diag_rect: Rect::default(),
            status_indent_rect: Rect::default(),
            status_encoding_rect: Rect::default(),
            status_eol_rect: Rect::default(),
            status_language_rect: Rect::default(),
            connect_dialog: None,
            connect_auth: None,
            install_session: None,
            update_watch: None,
            drift_probe: None,
            local_drift: None,
            self_install: None,
            update_check: None,
            update_toast: None,
            staged_install: None,
            staged_status: UpdateStatus::Idle,
            update_status: UpdateStatus::Idle,
            update_spinner_start: None,
            pending_reexec: false,
            overlays: {
                let mut overlays = OverlayManager::default();
                overlays.welcome.mark_dirty();
                overlays.hero.mark_dirty();
                overlays.activity.mark_dirty();
                overlays
            },
            editor_find: None,
            terminal_find: None,
            terminal_find_pane: 0,
            terminal_find_match: None,
            terminal_quick_select: None,
            // Under test, both durable stores point at per-process scratch
            // files so app tests that run commands or split panes can never
            // touch (or race on) the user's real history / session files;
            // tests that exercise the stores inject their own paths.
            command_history: crate::command_history::CommandHistory::load(&if cfg!(test) {
                std::env::temp_dir().join(format!(
                    "croft-test-command-history-{}.jsonl",
                    std::process::id()
                ))
            } else {
                crate::command_history::history_path()
            }),
            command_history_popup: None,
            terminal_session_dirty: false,
            terminal_store_error: None,
            terminal_session_path: if cfg!(test) {
                std::env::temp_dir().join(format!(
                    "croft-test-terminal-sessions-{}.json",
                    std::process::id()
                ))
            } else {
                crate::terminal_session::path()
            },
            workspace_folders_path: if cfg!(test) {
                std::env::temp_dir().join(format!(
                    "croft-test-workspace-folders-{}.json",
                    std::process::id()
                ))
            } else {
                crate::workspace::folders_store_path()
            },
            terminal_copy_mode: None,
            triggers: load_trigger_set(!loaded_prefs.disable_secret_redaction),
            agents: crate::agents::AgentTable::load(&crate::agents::agents_path()),
            agent_events: std::collections::VecDeque::new(),
            status_agents_rect: Rect::default(),
            matchers,
            watch_set,
            task_matcher_by_pane: std::collections::HashMap::new(),
            watch_published_panes: std::collections::HashSet::new(),
            broadcast_input: false,
            pending_broadcast_enable: false,
            pending_run_block: None,
            pending_captures: Vec::new(),
            block_outputs: std::collections::HashMap::new(),
            show_terminal_timestamps: false,
            notifier: crate::notifications::Notifier::new(&loaded_prefs.notifications),
            host_accents: compile_host_accents(&loaded_prefs.host_accents),
            closed_terminals: Vec::new(),
            closed_tabs: Vec::new(),
            file_finder: None,
            quick_open_range: None,
            command_palette: None,
            go_to_symbol: None,
            workspace_symbols: None,
            ws_symbols_request_id: None,
            ws_symbols_pending: None,
            mcp_rx: None,
            mcp_started: None,
            mcp_busy_label: None,
            process_picker: None,
            dap_session: None,
            debug_configs: Vec::new(),
            debug_compounds: Vec::new(),
            selected_debug_config: None,
            pending_debug_launch: None,
            pending_test_debug: None,
            debug_expanded: std::collections::HashSet::new(),
            watch_exprs: Vec::new(),
            watch_vals: std::collections::HashMap::new(),
            watch_prev: std::collections::HashMap::new(),
            watch_baseline_pending: false,
            debug_console: Vec::new(),
            debug_ever_stopped: false,
            zoxide_jump: None,
            zoxide_add_folder: false,
            branch_picker: None,
            branch_purpose: BranchPurpose::Checkout,
            scm_menu: crate::widgets::scm_menu::ScmMenuState::default(),
            input_prompt: None,
            list_picker: None,
            session_channel: crate::session_host::InnerChannel::from_env(),
            session_participants: Vec::new(),
            session_host_stale_seen: false,
            session_typist: None,
            session_carets: std::collections::HashMap::new(),
            session_presence_mtime: None,
            last_session_presence_poll: std::time::Instant::now(),
            collab: None,
            collab_config: crate::collab::CollabChannel::env_config(),
            last_collab_connect: None,
            collab_offline_base: std::collections::HashMap::new(),
            collab_carets: std::collections::HashMap::new(),
            collab_caret_sent: None,
            collab_stream: None,
            pair_host: None,
            pair_record_path: crate::session::pair_record_path(&root),
            pair_socket: crate::session::collab_socket_path(&root),
            pair_host_lock_path: crate::session::pair_host_lock_path(&root),
            last_pair_check: None,
            navigator_notes: std::collections::HashMap::new(),
            pair_commentary_buf: String::new(),
            pair_turn_origin: None,
            pair_notes_this_turn: 0,
            pair_last_noted_file: None,
            pair_host_lock: None,
            navigator_down: false,
            last_pair_record_raw: None,
            pair_lock_denied: None,
            pair_noted_files: std::collections::BTreeSet::new(),
            proactive_navigator_enabled: !loaded_prefs.disable_proactive_navigator,
            proactive_scanned: std::collections::HashMap::new(),
            #[cfg(test)]
            pair_spawn_override: None,
            collab_labels_visible: false,
            git_output_log: Vec::new(),
            build_diagnostics: std::collections::HashMap::new(),
            build_diag_files_by_pane: std::collections::HashMap::new(),
            pending_discard_all: false,
            pending_replace_all: None,
            file_finder_index: None,
            file_finder_index_rx: Some(file_finder_index_rx),
            file_finder_index_dirty: false,
            completion_request_id: None,
            signature_help_popup: None,
            signature_help_request_id: None,
            signature_help_anchor: None,
            rename_request_id: None,
            prepare_rename_request: None,
            format_request_id: None,
            format_request_selection: false,
            format_on_type: loaded_prefs.format_on_type,
            on_type_request: None,
            code_action_request_id: None,
            code_action_pending_resolve: false,
            pending_code_actions: Vec::new(),
            review_boxes: None,
            recording: None,
            recorded_size: (0, 0),
            symbol_tab: None,
            scrubber: None,
            debug_temp_breakpoint: None,
            debug_temp_note: None,
            agent_ledger: crate::agent_lane::AgentLedger::new(),
            problems_fix_started: None,
            http_run: None,
            pending_color_presentations: Vec::new(),
            pending_color_context: None,
            color_presentations_request: None,
            hover: HoverDwell::default(),
            hover_popup: None,
            hover_request_id: None,
            hover_anchor: None,
            hover_word: None,
            hover_diagnostic: None,
            tab_hover: HoverDwell::default(),
            tab_tooltip: None,
            tab_hover_idx: None,
            ui_hover: HoverDwell::default(),
            ui_tooltip: None,
            ui_tooltip_label: None,
            ui_tooltip_area: None,
            definition_request_id: None,
            peek_definition_request_id: None,
            peek_popup: None,
            peek_target: None,
            outline_synced: None,
            declaration_request_id: None,
            type_definition_request_id: None,
            implementation_request_id: None,
            references_request_id: None,
            call_hierarchy_request_id: None,
            occurrences_request: None,
            linked_request: None,
            linked_observed: None,
            linked_observed_at: std::time::Instant::now(),
            selection_range_request: None,
            occ_observed: None,
            occ_observed_at: std::time::Instant::now(),
            nav: NavHistory::default(),
        };
        // Initialise the per-pane focus/gradient flags to match the starting
        // pane (Tree) and persisted theme. Without this, the explorer boots
        // focused-but-not-gradient: the Black-theme gradient border only
        // arms on the first focus change because nothing ran the sync at
        // construction time.
        // #256: the PROBLEMS scope comes from prefs; set it after
        // construction so the panel keeps one plain `new()`.
        app.problems.scope =
            crate::widgets::problems::ProblemScope::from_config(&loaded_prefs.problems_scope);
        app.sync_focus_flags();
        // Seed the highlighter with the persisted theme's code palette so a
        // file opened before the first theme switch already highlights in the
        // active theme's colors (not the Base16 default).
        crate::highlight::set_syntax_palette(app.theme.syntax());
        // Pre-warm the workspace's evident language servers (Cargo.toml →
        // rust-analyzer, and so on), VS Code's `workspaceContains`
        // activation: the cold indexing overlaps with the user browsing
        // the tree instead of starting only at the first file open (#27).
        // The send is one channel post; the spawns run on the LSP worker.
        if let Some(lsp) = app.lsp.as_ref() {
            lsp.prewarm_workspace();
        }
        Ok(app)
    }

    /// Detect inline-image support via env vars only — no stdin queries, no
    /// raw-mode contention. Queries the terminal cell pixel size via
    /// crossterm's `window_size` (TIOCGWINSZ ioctl, no stdin involvement).
    /// SSH PTYs often report only rows/columns and leave pixel dimensions
    /// as zero, so fall back to a sane 10×20 cell estimate; OSC-1337 still
    /// scales the image to the requested cell rectangle.
    /// The active theme's background as a fully-opaque image pixel. Used to
    /// fill the OSC-1337 icon/hero canvases so the baked PNGs sit on the same
    /// color as the surrounding (session-bg) panes, with no visible seam.
    fn theme_bg_pixel(&self) -> image::Rgba<u8> {
        let (r, g, b) = self.theme.editor_bg_rgb();
        image::Rgba([r, g, b, 0xff])
    }

    /// True when the host terminal can render inline images via either
    /// protocol. Gates the bake/emit path; the iTerm2-only `SetColors` /
    /// `Color::Reset` tricks stay behind `detect_iterm2_inline_support`.
    fn inline_images_enabled(&self) -> bool {
        self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::None
    }

    /// Whether evicting stale inline images requires wiping the whole screen.
    /// iTerm2 OSC-1337 and sixel graphics live in the normal cell buffer, so
    /// only a `\x1b[2J` removes their cached cells. Kitty graphics live on
    /// their own layer and are deleted by [`Self::evict_inline_images_on_clear`]
    /// without touching a single text cell - wiping the screen there blanks
    /// the whole app for an SSH round trip on every latch (the "croft blinks
    /// while I type" bug), so the Kitty path must never `terminal.clear()`.
    pub fn image_eviction_needs_screen_wipe(&self) -> bool {
        self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::Kitty
    }

    /// Kitty graphics live on a layer that survives the `\x1b[2J` the main
    /// loop fires to evict iTerm2's image cells, so on the Kitty path that
    /// same clear frame must also delete every placement; the visible
    /// overlays re-emit themselves on the following post-draw flush. No-op on
    /// the iTerm2 path, where the clear already evicted the cached cells.
    pub fn evict_inline_images_on_clear(&self) {
        use std::io::Write;
        if self.inline_protocol == crate::iterm2_inline::InlineImageProtocol::Kitty {
            let mut out = stdout();
            let _ = out.write_all(crate::iterm2_inline::delete_all_kitty_images().as_bytes());
            let _ = out.flush();
        }
    }

    /// One-shot consumer for [`Self::resize_repaint_needed`]: the main loop
    /// answers `true` with an unconditional `terminal.clear()` on every
    /// protocol, Kitty included. Resize is not image eviction: the wipe here
    /// restores text a WINCH (window resize or dtach reattach) invalidated,
    /// and it never fires while the user merely types.
    pub fn consume_resize_repaint(&mut self) -> bool {
        std::mem::take(&mut self.resize_repaint_needed)
    }

    pub fn init_graphics(&mut self) {
        // Env-advertised protocols (iTerm2/Kitty) win; otherwise fall back to a
        // sixel host detected earlier by the DA1 probe. Re-derived here so the
        // theme-switch re-bake keeps the right protocol, and `sixel_supported`
        // carries the probe result across the env re-detect (sixel has none).
        self.inline_protocol = match crate::iterm2_inline::detect_inline_image_protocol() {
            crate::iterm2_inline::InlineImageProtocol::None if self.sixel_supported => {
                crate::iterm2_inline::InlineImageProtocol::Sixel
            }
            other => other,
        };
        if !self.inline_images_enabled() {
            return;
        }
        let Ok(ws) = crossterm::terminal::window_size() else {
            return;
        };
        if ws.columns == 0 || ws.rows == 0 {
            return;
        }
        let (cell_w, cell_h) = if ws.width > 0 && ws.height > 0 {
            (
                (ws.width / ws.columns).max(1) as u32,
                (ws.height / ws.rows).max(1) as u32,
            )
        } else {
            FALLBACK_CELL_PIXEL
        };
        self.cell_pixel = Some((cell_w, cell_h));
        // OSC-1337 hero will own the no-repo illustration cells; the
        // widget skips its ASCII fallback so resize doesn't flash old
        // text through the image.
        self.source_control.inline_hero_image_active = true;
        let canvas_w = cell_w * ACTIVITY_BAR_WIDTH as u32;
        let canvas_h = cell_h * ACTIVITY_ICON_HEIGHT as u32;
        let is_tmux = crate::iterm2_inline::detect_tmux();
        let w_cells = ACTIVITY_BAR_WIDTH;
        let h_cells = ACTIVITY_ICON_HEIGHT;
        let icon_bg = self.theme_bg_pixel();
        // The bar background above is the theme's; so is the ink painted on
        // it. A baked icon can't route its colors through `Theme::ui` the way
        // a styled cell does, so the palette is resolved once here and rides
        // into every compose call (issue #225).
        let icon_ink = crate::iterm2_inline::IconInk::new(
            self.theme.activity_icon_inactive_rgb(),
            self.theme.activity_icon_active_rgb(),
            self.theme.activity_icon_pill_rgb(),
        );
        let protocol = self.inline_protocol;
        // The activity-bar icons are codicon SVGs, rasterised at the exact icon
        // pixel size (no multi-MB raster decode, crisp at any cell size). `id`
        // is the icon's stable per-slot Kitty image/placement id (shared by its
        // active and inactive variants so swapping one for the other replaces
        // the placement in place); ignored on the iTerm2 path.
        let encode = |src_svg: &[u8],
                      state: crate::iterm2_inline::IconState,
                      off_y_bias: i64,
                      id: u32|
         -> Option<String> {
            let baked = crate::iterm2_inline::compose_icon_svg(
                src_svg, canvas_w, canvas_h, state, icon_ink, icon_bg, off_y_bias,
            )?;
            // preserveAspectRatio=0: stretch to exactly fill 4×2 cells.
            // Since the canvas was composed at exactly that pixel size,
            // there's no actual scaling and the codicon's square area
            // remains a true square on screen.
            let raw = crate::iterm2_inline::build_inline_image(
                protocol, &baked, w_cells, h_cells, false, id,
            )?;
            Some(crate::iterm2_inline::maybe_tmux_wrap(
                protocol, is_tmux, raw,
            ))
        };
        // View icons render dead-centered in their cell block; the gear gets a
        // downward bias so it bottom-aligns within its (bottom-inset) block,
        // shaving the canvas's bottom padding off the gap above the status bar.
        // The value need only exceed the no-clip ceiling; `compose_icon_svg`
        // clamps it, so this stays correct at any cell size.
        let gear_off_y_bias = canvas_h as i64;
        use crate::iterm2_inline as ki;
        // Bake all three states per icon up front (selected / hovered / resting)
        // so the render path only ever swaps which pre-encoded sequence it emits
        // — a hover never triggers a re-bake, just a different cached string.
        let bake = |src: &[u8], off_y_bias: i64, id: u32| -> Option<(String, String, String)> {
            Some((
                encode(src, ki::IconState::Active, off_y_bias, id)?,
                encode(src, ki::IconState::Inactive, off_y_bias, id)?,
                encode(src, ki::IconState::Hovered, off_y_bias, id)?,
            ))
        };
        // Customize Layout toolbar icons: baked OPAQUE on the editor bg at the
        // 4×2-cell box so they paint IN FRONT of the container's top line
        // (the line sits behind the icon's solid background). `Inactive` is the
        // muted resting grey; `Hovered` is the bright variant emitted while the
        // pointer rests on the icon. The side-bar / panel ids swap their on/off
        // image in place.
        let layout_canvas_w = cell_w * LAYOUT_ICON_CELLS_W as u32;
        let layout_canvas_h = cell_h * LAYOUT_ICON_CELLS_H as u32;
        let bake_layout = |src_svg: &[u8], state: ki::IconState, id: u32| -> Option<String> {
            let baked = crate::iterm2_inline::compose_icon_svg(
                src_svg,
                layout_canvas_w,
                layout_canvas_h,
                state,
                icon_ink,
                icon_bg,
                0,
            )?;
            let raw = crate::iterm2_inline::build_inline_image(
                protocol,
                &baked,
                LAYOUT_ICON_CELLS_W,
                LAYOUT_ICON_CELLS_H,
                false,
                id,
            )?;
            Some(crate::iterm2_inline::maybe_tmux_wrap(
                protocol, is_tmux, raw,
            ))
        };
        let bake_layout_pair = |src: &[u8], id: u32| -> Option<(String, String)> {
            Some((
                bake_layout(src, ki::IconState::Inactive, id)?,
                bake_layout(src, ki::IconState::Hovered, id)?,
            ))
        };
        let layout_imgs = (|| {
            let (so, soh) =
                bake_layout_pair(ki::LAYOUT_SIDEBAR_ON_SRC_SVG, ki::KITTY_ID_LAYOUT_SIDEBAR)?;
            let (sf, sfh) =
                bake_layout_pair(ki::LAYOUT_SIDEBAR_OFF_SRC_SVG, ki::KITTY_ID_LAYOUT_SIDEBAR)?;
            let (po, poh) =
                bake_layout_pair(ki::LAYOUT_PANEL_ON_SRC_SVG, ki::KITTY_ID_LAYOUT_PANEL)?;
            let (pf, pfh) =
                bake_layout_pair(ki::LAYOUT_PANEL_OFF_SRC_SVG, ki::KITTY_ID_LAYOUT_PANEL)?;
            let (cu, cuh) =
                bake_layout_pair(ki::LAYOUT_CUSTOMIZE_SRC_SVG, ki::KITTY_ID_LAYOUT_CUSTOMIZE)?;
            Some((so, soh, sf, sfh, po, poh, pf, pfh, cu, cuh))
        })();
        if let (
            Some((ea, ei, eh)),
            Some((sa, si, sh)),
            Some((sca, sci, sch)),
            Some((ra, ri, rh)),
            Some((rda, rdi, rdh)),
            Some((exta, exti, exth)),
            Some((tsta, tsti, tsth)),
            Some((gea, gei, geh)),
            Some((lso, lsoh, lsf, lsfh, lpo, lpoh, lpf, lpfh, lcu, lcuh)),
        ) = (
            bake(ki::EXPLORER_SRC_SVG, 0, ki::KITTY_ID_EXPLORER),
            bake(ki::SEARCH_SRC_SVG, 0, ki::KITTY_ID_SEARCH),
            bake(ki::SOURCE_CONTROL_SRC_SVG, 0, ki::KITTY_ID_SOURCE_CONTROL),
            bake(ki::REMOTE_SRC_SVG, 0, ki::KITTY_ID_REMOTE),
            bake(ki::RUN_DEBUG_SRC_SVG, 0, ki::KITTY_ID_RUN_DEBUG_BAR),
            bake(ki::EXTENSIONS_SRC_SVG, 0, ki::KITTY_ID_EXTENSIONS),
            bake(ki::TESTING_SRC_SVG, 0, ki::KITTY_ID_TESTING),
            bake(
                ki::SETTINGS_GEAR_SRC_SVG,
                gear_off_y_bias,
                ki::KITTY_ID_SETTINGS,
            ),
            layout_imgs,
        ) {
            self.overlays.activity.set_images(ActivityBarImages {
                explorer_active: ea,
                explorer_inactive: ei,
                explorer_hovered: eh,
                search_active: sa,
                search_inactive: si,
                search_hovered: sh,
                source_control_active: sca,
                source_control_inactive: sci,
                source_control_hovered: sch,
                remote_active: ra,
                remote_inactive: ri,
                remote_hovered: rh,
                run_debug_active: rda,
                run_debug_inactive: rdi,
                run_debug_hovered: rdh,
                extensions_active: exta,
                extensions_inactive: exti,
                extensions_hovered: exth,
                testing_active: tsta,
                testing_inactive: tsti,
                testing_hovered: tsth,
                settings_active: gea,
                settings_inactive: gei,
                settings_hovered: geh,
                layout_sidebar_on: lso,
                layout_sidebar_on_hover: lsoh,
                layout_sidebar_off: lsf,
                layout_sidebar_off_hover: lsfh,
                layout_panel_on: lpo,
                layout_panel_on_hover: lpoh,
                layout_panel_off: lpf,
                layout_panel_off_hover: lpfh,
                layout_customize: lcu,
                layout_customize_hover: lcuh,
            });
        }
        // The activity-bar count badges ride the same overlay machinery; rebuild
        // them against the freshly-baked icons / new background or cell size. The
        // Explorer badge's per-frame refresh is count-gated, so force a rebuild
        // here by invalidating its cached count first.
        self.refresh_scm_change_badge();
        self.explorer_unsaved_count = usize::MAX;
        self.refresh_explorer_unsaved_badge();
        self.remote_ports_count = usize::MAX;
        self.refresh_remote_ports_badge();
        self.testing_badge_count = usize::MAX;
        self.refresh_testing_badge();
        self.problems_badge_count = usize::MAX;
        self.refresh_problems_badge();
        // Run-and-Debug headline icon: the same debug-alt PNG used in the
        // activity bar, fitted to the panel's icon block (RUN_DEBUG_ICON_CELLS_W
        // cells wide × RUN_DEBUG_ICON_CELLS_H cells tall) and tinted at icon-
        // inactive grey so it reads as the same monochrome family as the rest
        // of the activity-bar icons. Encoded once at init; emitted post-frame
        // by `flush_run_debug_icon_overlay` while the panel is visible.
        let rd_icon_w_cells = crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_W as u32;
        let rd_icon_h_cells = crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_H as u32;
        let rd_icon_w_px = cell_w * rd_icon_w_cells;
        let rd_icon_h_px = cell_h * rd_icon_h_cells;
        if let Ok(baked) = crate::iterm2_inline::compose_icon(
            crate::iterm2_inline::RUN_DEBUG_SRC_PNG,
            rd_icon_w_px,
            rd_icon_h_px,
            false,
            icon_ink,
            icon_bg,
            0,
        ) && let Some(raw) = crate::iterm2_inline::build_inline_image(
            protocol,
            &baked,
            crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_W,
            crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_H,
            false,
            crate::iterm2_inline::KITTY_ID_RUN_DEBUG_PANEL,
        ) {
            self.overlays
                .run_debug
                .set_image(crate::iterm2_inline::maybe_tmux_wrap(
                    protocol, is_tmux, raw,
                ));
        }
        // SSH empty-state illustration baked to a fixed cell box (18 × 8
        // cells). Letterboxed onto the card's dark bg so iTerm2 has no
        // transparent edge to ghost the underlying buffer. Emitted post-
        // draw by `flush_ssh_empty_state_overlay` while the SSH section
        // shows no hosts.
        let ssh_cells_w: u16 = crate::widgets::remote::SSH_EMPTY_STATE_CELLS_W;
        let ssh_cells_h: u16 = crate::widgets::remote::SSH_EMPTY_STATE_CELLS_H;
        let ssh_w_px = cell_w * ssh_cells_w as u32;
        let ssh_h_px = cell_h * ssh_cells_h as u32;
        // Transparent letterbox so the host terminal's session bg shows
        // through the empty padding around the illustration. Any opaque
        // fill here would render as a visible darker rectangle behind the
        // PNG, which is exactly what the user told us to remove.
        let card_bg = ::image::Rgba([0x00, 0x00, 0x00, 0x00]);
        if let Ok(baked) = crate::iterm2_inline::fit_image_auto(
            crate::iterm2_inline::SSH_EMPTY_STATE_PNG,
            ssh_w_px,
            ssh_h_px,
            card_bg,
        ) && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
            protocol,
            &baked,
            ssh_cells_w,
            ssh_cells_h,
            false,
            crate::iterm2_inline::KITTY_ID_SSH,
            crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
        ) {
            self.overlays
                .ssh
                .set_image(crate::iterm2_inline::maybe_tmux_wrap(
                    protocol, is_tmux, raw,
                ));
        }
    }

    /// Emit the OSC-1337 image carrying the run-debug headline icon at the
    /// cell the panel reserved on its most recent render. No-op when the
    /// panel isn't the active sidebar view, when the icon hasn't been
    /// baked (non-iTerm2 host), or when the panel didn't reserve a cell
    /// (too short to fit the icon). Critically, the panel-hidden case
    /// does NOT stamp blanks or any other "wipe" payload here: doing so
    /// after `terminal.clear()` + redraw stomps freshly-painted text in
    /// the next sidebar (this was the bug in the prior space-stamp wipe
    /// attempt). Eviction of iTerm2's cached image cells is handled
    /// exclusively by the `consume_run_debug_image_clear` →
    /// `terminal.clear()` gate in the main loop, the same pipeline the
    /// welcome wordmark and editor preview image use.
    /// Stop showing the Run/Debug empty-state icon: if an OSC-1337 image was
    /// emitted, arm the one-shot `terminal.clear()` latch so the cached image
    /// cells are evicted (text painted over an inline image does not remove
    /// it), then reset the emitted-position tracking so the clear fires exactly
    /// once rather than every frame.
    fn clear_run_debug_icon_if_emitted(&mut self) {
        if self.overlays.run_debug.was_emitted() {
            self.overlays.run_debug.request_clear();
        }
        self.overlays.run_debug.clear_emitted();
    }

    pub fn flush_run_debug_icon_overlay(&mut self) {
        use std::io::Write;
        if self.modal_overlay_open() {
            return;
        }
        let panel_visible = self.show_tree
            && self.sidebar_view == SidebarView::RunDebug
            && self.overlays.run_debug.has_image();
        if !panel_visible {
            self.clear_run_debug_icon_if_emitted();
            return;
        }
        // No icon cell this frame means the panel is showing the paused
        // call-stack tree (debug_active) or is too short for the icon. The
        // empty-state icon is an OSC-1337 image; drawing the tree over it does
        // NOT evict it, so an emitted icon must be cleared with the one-shot
        // `\x1b[2J` latch or it ghosts on top of the call stack.
        let Some((cx, cy)) = self.run_debug.last_icon_cell else {
            self.clear_run_debug_icon_if_emitted();
            return;
        };
        // The icon moved since the last emit (terminal resize OR an internal
        // pane-drag, which never fires Event::Resize and so escapes
        // `on_resize`). A plain re-emit at the new cell stacks a fresh
        // OSC-1337 image on top of the one iTerm2 still caches at the old
        // cell — the doubled/garbled headline-icon ghost. Plain SGR
        // overwrites don't evict those cells, so reuse the proven
        // `terminal.clear()` latch: arm one clear, drop the stale emit
        // position, and skip painting this frame. Next frame the main loop's
        // OR chain fires `\x1b[2J`, full-redraws, and this flush re-emits a
        // single clean icon at the new cell.
        if let Some(prev) = self.overlays.run_debug.last_emitted()
            && prev != (cx, cy)
        {
            self.overlays.run_debug.request_clear();
            self.overlays.run_debug.clear_emitted();
            return;
        }
        let Some(osc) = self.overlays.run_debug.image() else {
            return;
        };
        let mut out = stdout();
        let cursor_on = self.cursor_should_be_visible();
        let _ = write!(out, "\x1b[?25l\x1b[s");
        let _ = write!(out, "\x1b[{};{}H", cy + 1, cx + 1);
        let _ = out.write_all(osc.as_bytes());
        let _ = write!(out, "\x1b[u");
        if cursor_on {
            let _ = write!(out, "\x1b[?25h");
        }
        let _ = out.flush();
        self.overlays.run_debug.mark_emitted_at((cx, cy));
    }

    /// Arm the one-shot `terminal.clear()` latch if the PROBLEMS circle was
    /// emitted, so its cached image cells are evicted when the badge goes away
    /// (text painted over an inline image does not remove it), then reset the
    /// emit position so the clear fires exactly once.
    fn clear_problems_badge_if_emitted(&mut self) {
        if self.overlays.problems_badge.was_emitted() {
            self.overlays.problems_badge.request_clear();
        }
        self.overlays.problems_badge.clear_emitted();
    }

    /// Emit the PROBLEMS-tab orange circle as an OSC-1337/Kitty inline image at
    /// the cell `paint_panel_tabs` recorded this frame, re-emitted every frame
    /// (like the activity-bar badges) so heavy SGR traffic can't evict it.
    /// Clears when the panel strip is hidden, the count is zero, or a modal owns
    /// the screen; arms a one-shot clear when the anchor moves so no ghost stacks.
    pub fn flush_problems_badge_overlay(&mut self) {
        use std::io::Write;
        if self.modal_overlay_open() {
            return;
        }
        let Some((cx, cy)) = self.problems_badge_cell.filter(|_| self.show_terminal) else {
            self.clear_problems_badge_if_emitted();
            return;
        };
        if !self.overlays.problems_badge.has_image() {
            self.clear_problems_badge_if_emitted();
            return;
        }
        if let Some(prev) = self.overlays.problems_badge.last_emitted()
            && prev != (cx, cy)
        {
            self.overlays.problems_badge.request_clear();
            self.overlays.problems_badge.clear_emitted();
            return;
        }
        let Some(osc) = self.overlays.problems_badge.image() else {
            return;
        };
        let mut out = stdout();
        let cursor_on = self.cursor_should_be_visible();
        let _ = write!(out, "\x1b[?25l\x1b[s");
        let _ = write!(out, "\x1b[{};{}H", cy + 1, cx + 1);
        let _ = out.write_all(osc.as_bytes());
        let _ = write!(out, "\x1b[u");
        if cursor_on {
            let _ = write!(out, "\x1b[?25h");
        }
        let _ = out.flush();
        self.overlays.problems_badge.mark_emitted_at((cx, cy));
    }

    /// Re-bake (when needed) and re-emit the OSC-1337 inline image for
    /// the no-repo source-control hero. Pure no-op when the sidebar isn't
    /// on Source Control, the workspace IS a git repo, or the host
    /// terminal can't render inline images. Called from the post-draw
    /// flush each frame so iTerm2 keeps the image painted even after
    /// surrounding cells redraw.
    pub fn flush_no_repo_hero_overlay(&mut self) {
        use std::io::Write;
        if self.modal_overlay_open() {
            return;
        }
        let panel_visible = self.show_tree
            && self.sidebar_view == SidebarView::SourceControl
            && !self.source_control.status.in_repo;
        if !panel_visible {
            self.overlays.hero.mark_hidden();
            return;
        }
        let hero = self.source_control.last_hero_area;
        if hero.width == 0 || hero.height == 0 {
            return;
        }
        // The hero asset carries its own opaque dark backdrop; on a light
        // theme it would sit as a dark slab on the white panel, so the
        // panel keeps its text-only empty state instead.
        if self.theme.is_light() {
            self.overlays.hero.mark_hidden();
            return;
        }
        let Some((cw, ch)) = self.cell_pixel else {
            return;
        };
        let desired = WelcomeLayout {
            cell_x: hero.x,
            cell_y: hero.y,
            cell_w: hero.width,
            cell_h: hero.height,
        };
        if !self.overlays.hero.layout_matches(&desired) || !self.overlays.hero.has_image() {
            let canvas_w = (hero.width as u32) * cw;
            let canvas_h = (hero.height as u32) * ch;
            let bg = self.theme_bg_pixel();
            let protocol = self.inline_protocol;
            if let Ok(baked) = crate::iterm2_inline::fit_image(
                crate::iterm2_inline::NO_REPO_HERO_PNG,
                canvas_w,
                canvas_h,
                bg,
            ) && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
                protocol,
                &baked,
                hero.width,
                hero.height,
                false,
                crate::iterm2_inline::KITTY_ID_HERO,
                crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
            ) {
                let osc = crate::iterm2_inline::maybe_tmux_wrap(
                    protocol,
                    crate::iterm2_inline::detect_tmux(),
                    raw,
                );
                self.overlays.hero.set(osc, desired);
            }
        }
        let Some(osc) = self.overlays.hero.image() else {
            return;
        };
        let mut out = stdout();
        let cursor_on = self.cursor_should_be_visible();
        let _ = write!(out, "\x1b[?25l\x1b[s");
        let _ = write!(out, "\x1b[{};{}H", hero.y + 1, hero.x + 1);
        let _ = out.write_all(osc.as_bytes());
        let _ = write!(out, "\x1b[u");
        if cursor_on {
            let _ = write!(out, "\x1b[?25h");
        }
        let _ = out.flush();
        self.overlays.hero.mark_emitted();
    }

    /// Emit the OSC-1337 SSH-empty-state illustration at the cell the
    /// remote panel reserved on its most recent render. When the panel
    /// is no longer the active view (or has hosts, or the shortcuts
    /// modal is open), this arms a one-shot terminal.clear() via
    /// `consume_ssh_empty_state_image_clear()` so iTerm2 evicts the
    /// cached image cells — otherwise the illustration ghosts onto
    /// whatever view (Explorer / Search / …) replaces it.
    pub fn flush_ssh_empty_state_overlay(&mut self) {
        use std::io::Write;
        let should_show = self.shortcuts_modal.is_none()
            && self.file_finder.is_none()
            && self.zoxide_jump.is_none()
            && self.command_history_popup.is_none()
            && self.branch_picker.is_none()
            && self.input_prompt.is_none()
            && self.list_picker.is_none()
            && self.show_tree
            && self.sidebar_view == SidebarView::Remote
            && self.remote.targets.is_empty();
        if !should_show {
            self.overlays.ssh.hide_and_request_clear();
            return;
        }
        let Some((cx, cy)) = self.remote.last_image_cell else {
            return;
        };
        let Some(osc) = self.overlays.ssh.image() else {
            return;
        };
        let mut out = stdout();
        let cursor_on = self.cursor_should_be_visible();
        let _ = write!(out, "\x1b[?25l\x1b[s");
        let _ = write!(out, "\x1b[{};{}H", cy + 1, cx + 1);
        let _ = out.write_all(osc.as_bytes());
        let _ = write!(out, "\x1b[u");
        if cursor_on {
            let _ = write!(out, "\x1b[?25h");
        }
        let _ = out.flush();
        self.overlays.ssh.mark_displayed();
    }

    /// One-shot consumer paired with `flush_ssh_empty_state_overlay`. The
    /// main loop ORs the result into its `terminal.clear()` chain so
    /// iTerm2's cached image cells are evicted on view change.
    pub fn consume_ssh_empty_state_image_clear(&mut self) -> bool {
        self.overlays.ssh.consume_clear_latch()
    }

    /// One-shot consumer for the "leaving Run-Debug after the icon was
    /// emitted" flag. The main loop folds the result into the same OR
    /// chain that fires `terminal.clear()` for the welcome wordmark and
    /// editor preview image.
    pub fn consume_run_debug_image_clear(&mut self) -> bool {
        self.overlays.run_debug.consume_clear()
    }

    /// One-shot consumer for the "the PROBLEMS circle went away / moved after it
    /// was emitted" flag. Folded into the main loop's `terminal.clear()` OR chain
    /// so iTerm2 evicts the cached badge bitmap.
    pub fn consume_problems_badge_image_clear(&mut self) -> bool {
        self.overlays.problems_badge.consume_clear()
    }

    /// One-shot consumer for the "a resize may have left stale activity-bar
    /// icon bitmaps in iTerm2's image layer" flag, armed by `on_resize`. The
    /// main loop folds the result into the same OR chain that fires
    /// `terminal.clear()` for the welcome wordmark and editor preview image,
    /// evicting the ghost before the icons re-emit on the next draw.
    pub fn consume_activity_image_clear(&mut self) -> bool {
        self.overlays.activity.consume_clear()
    }

    /// Handle a terminal/pane resize. The alt-screen reflow blanks the SGR
    /// cells but iTerm2's OSC-1337 image layer survives, so a plain re-emit
    /// would stack a fresh icon on top of the stale one (the doubled-icon
    /// ghost). Re-mark the icons dirty so they re-emit, and — in images mode,
    /// the only state the stale layer can exist in — arm a one-shot
    /// `terminal.clear()` so iTerm2 drops the cached bitmaps first.
    pub fn on_resize(&mut self) {
        self.overlays.activity.mark_dirty();
        if self.overlays.activity.has_images() {
            self.overlays.activity.request_clear();
        }
        // A WINCH invalidates the physical screen (window resize reflow, or a
        // dtach reattach against a blank terminal) while ratatui's back buffer
        // still claims every cell is painted; force the next frame to wipe and
        // re-emit everything on every protocol.
        self.resize_repaint_needed = true;
    }

    /// One-shot consumer for the "leaving Source Control after the no-repo
    /// hero PNG was emitted" flag. Same shape as
    /// `consume_run_debug_image_clear` - the main loop folds the result
    /// into its `terminal.clear()` chain so iTerm2's cached image cells
    /// are evicted on view change.
    pub fn consume_no_repo_hero_image_clear(&mut self) -> bool {
        self.overlays.hero.consume_clear_latch()
    }

    /// The rect of the sidebar OSC-1337 illustration currently on screen (the
    /// Source Control no-repo hero or the Remote SSH empty-state), or `None`
    /// when neither is showing. Those images composite above ratatui's text
    /// layer, so a tooltip overlapping one must be re-painted last.
    fn active_sidebar_image_rect(&self) -> Option<Rect> {
        if !self.show_tree {
            return None;
        }
        let rect = match self.sidebar_view {
            SidebarView::SourceControl if !self.source_control.status.in_repo => {
                self.source_control.last_hero_area
            }
            SidebarView::Remote if self.remote.targets.is_empty() => self.remote.last_image_area,
            _ => return None,
        };
        (rect.width > 0 && rect.height > 0).then_some(rect)
    }

    /// Re-paint the chrome tooltip directly to the terminal AFTER the inline
    /// images have been flushed, so its box sits in the foreground over any
    /// sidebar illustration it overlaps. The hero / SSH image is emitted
    /// post-draw and would otherwise composite over the tooltip's text; since
    /// the last writer wins each cell, re-emitting the box here puts it on top
    /// while the illustration itself stays fully painted everywhere else.
    /// No-op unless a tooltip is showing and actually lands on an illustration.
    pub fn flush_tooltip_over_image(&mut self) {
        use std::io::Write;
        // Only the cell-buffer protocols (iTerm2 OSC-1337, Sixel) need this: a
        // later text write wins those cells. The Kitty path instead places the
        // illustration at a deep-negative z so text already draws on top, and
        // re-blitting would be wasted stdout traffic.
        match self.inline_protocol {
            crate::iterm2_inline::InlineImageProtocol::ITerm2
            | crate::iterm2_inline::InlineImageProtocol::Sixel => {}
            _ => return,
        }
        let Some(area) = self.ui_tooltip_area else {
            return;
        };
        let Some(img) = self.active_sidebar_image_rect() else {
            return;
        };
        if !rects_intersect(area, img) {
            return;
        }
        let Some(popup) = self.ui_tooltip.as_ref() else {
            return;
        };
        // Render the popup into a standalone buffer at its on-screen rect, then
        // blit each cell as an absolutely-positioned SGR write. The box is fully
        // opaque (its block fills the bg), so it cleanly occludes the slice of
        // the illustration it covers, exactly like a floating tooltip.
        let mut buf = ratatui::buffer::Buffer::empty(area);
        ratatui::widgets::Widget::render(popup, area, &mut buf);
        let mut out = stdout();
        let cursor_on = self.cursor_should_be_visible();
        let _ = write!(out, "\x1b[?25l\x1b[s");
        for y in area.top()..area.bottom() {
            let _ = write!(out, "\x1b[{};{}H", y + 1, area.left() + 1);
            for x in area.left()..area.right() {
                let cell = &buf[(x, y)];
                let _ = out.write_all(sgr_for_cell(cell).as_bytes());
                let _ = out.write_all(cell.symbol().as_bytes());
            }
            let _ = write!(out, "\x1b[0m");
        }
        let _ = write!(out, "\x1b[u");
        if cursor_on {
            let _ = write!(out, "\x1b[?25h");
        }
        let _ = out.flush();
    }

    /// Returns the post-frame OSC-1337 escapes to write under the activity
    /// bar, paired with the absolute terminal cell where each one starts
    /// (just past the active-pill column). Empty when image rendering is
    /// disabled or the activity bar hasn't been laid out yet.
    pub fn pending_activity_image_overlays(&self) -> Vec<((u16, u16), &str)> {
        let Some(images) = self.overlays.activity.images() else {
            return Vec::new();
        };
        let exp_block = self.sidebar_areas.explorer_icon;
        let sea_block = self.sidebar_areas.search_icon;
        let scm_block = self.sidebar_areas.source_control_icon;
        let rem_block = self.sidebar_areas.remote_icon;
        let rdb_block = self.sidebar_areas.run_debug_icon;
        let ext_block = self.sidebar_areas.extensions_icon;
        let tst_block = self.sidebar_areas.testing_icon;
        // The activity bar is all-or-nothing: emit its icons only when every
        // block is laid out (a partial bar would look broken). When it's hidden
        // (Customize Layout / Zen) the blocks are zero-width and skipped, but
        // the layout toolbar icons below still emit independently.
        let activity_ready = exp_block.width > 0
            && sea_block.width > 0
            && scm_block.width > 0
            && rem_block.width > 0
            && rdb_block.width > 0
            && ext_block.width > 0
            && tst_block.width > 0;
        // Three-way per icon: the selected view shows the active (pilled)
        // variant; otherwise the pointer-hovered icon brightens (no pill); the
        // rest stay muted. Selected always wins over hovered.
        let hov = self.hovered_activity_icon;
        let exp_state = if self.sidebar_view == SidebarView::Explorer {
            &images.explorer_active
        } else if hov == Some(ActivityIcon::Explorer) {
            &images.explorer_hovered
        } else {
            &images.explorer_inactive
        };
        let sea_state = if self.sidebar_view == SidebarView::Search {
            &images.search_active
        } else if hov == Some(ActivityIcon::Search) {
            &images.search_hovered
        } else {
            &images.search_inactive
        };
        let scm_state = if self.sidebar_view == SidebarView::SourceControl {
            &images.source_control_active
        } else if hov == Some(ActivityIcon::SourceControl) {
            &images.source_control_hovered
        } else {
            &images.source_control_inactive
        };
        let rem_state = if self.sidebar_view == SidebarView::Remote {
            &images.remote_active
        } else if hov == Some(ActivityIcon::Remote) {
            &images.remote_hovered
        } else {
            &images.remote_inactive
        };
        let rdb_state = if self.sidebar_view == SidebarView::RunDebug {
            &images.run_debug_active
        } else if hov == Some(ActivityIcon::RunDebug) {
            &images.run_debug_hovered
        } else {
            &images.run_debug_inactive
        };
        let ext_state = if self.sidebar_view == SidebarView::Extensions {
            &images.extensions_active
        } else if hov == Some(ActivityIcon::Extensions) {
            &images.extensions_hovered
        } else {
            &images.extensions_inactive
        };
        let tst_state = if self.sidebar_view == SidebarView::Testing {
            &images.testing_active
        } else if hov == Some(ActivityIcon::Testing) {
            &images.testing_hovered
        } else {
            &images.testing_inactive
        };
        // The gear is bottom-anchored and may be absent on a short bar
        // (empty block). It reads "active" while its menu/picker is open.
        let set_block = self.sidebar_areas.settings_icon;
        let set_state = if self.settings_menu_active() {
            &images.settings_active
        } else if hov == Some(ActivityIcon::Settings) {
            &images.settings_hovered
        } else {
            &images.settings_inactive
        };
        // The shortcuts modal and file finder are centered over the editor
        // column, not the far-left activity bar, so the icons stay visible
        // beside them. Suppress an icon only when its block actually
        // intersects an open panel (possible only when the terminal is
        // narrow enough that the centered panel reaches column 0); otherwise
        // a terminal.clear() armed by the modal wipes iTerm2's cached image
        // cells and they never repaint while the panel is up.
        let occluders = [
            self.shortcuts_modal.as_ref().map(|m| m.last_rect),
            self.file_finder.as_ref().map(|f| f.last_rect),
            self.command_palette.as_ref().map(|p| p.last_rect),
            self.go_to_symbol.as_ref().map(|p| p.last_rect),
            self.workspace_symbols.as_ref().map(|p| p.last_rect),
            self.process_picker.as_ref().map(|p| p.last_rect),
        ];
        let visible = |block: Rect| {
            occluders
                .iter()
                .flatten()
                .all(|panel| !block.intersects(*panel))
        };
        let mut blocks: Vec<(Rect, &str)> = Vec::new();
        if activity_ready {
            blocks.extend_from_slice(&[
                (exp_block, exp_state.as_str()),
                (sea_block, sea_state.as_str()),
                (scm_block, scm_state.as_str()),
                (rem_block, rem_state.as_str()),
                (rdb_block, rdb_state.as_str()),
                (ext_block, ext_state.as_str()),
                (tst_block, tst_state.as_str()),
            ]);
            if set_block.width > 0 {
                blocks.push((set_block, set_state.as_str()));
            }
            // Change-count badge over the SCM icon's bottom-right corner. Pushed
            // after the SCM icon so the iTerm2 path (last writer wins each cell)
            // paints it on top; the Kitty path baked it at z=1 for the same
            // effect. Dropping it from the list when the count hits zero shifts
            // the emit positions, which arms the overlay's move-detection clear.
            if let Some(badge) = self.scm_change_badge.as_deref() {
                let bw = crate::iterm2_inline::count_badge_cells_w(self.scm_change_badge_count);
                let bx = scm_block.x + scm_block.width.saturating_sub(bw);
                let by = scm_block.y + scm_block.height.saturating_sub(1);
                blocks.push((
                    Rect {
                        x: bx,
                        y: by,
                        width: bw,
                        height: 1,
                    },
                    badge,
                ));
            }
            // Same badge over the Explorer icon for the unsaved-file count.
            if let Some(badge) = self.explorer_unsaved_badge.as_deref() {
                let bw = crate::iterm2_inline::count_badge_cells_w(self.explorer_unsaved_count);
                let bx = exp_block.x + exp_block.width.saturating_sub(bw);
                let by = exp_block.y + exp_block.height.saturating_sub(1);
                blocks.push((
                    Rect {
                        x: bx,
                        y: by,
                        width: bw,
                        height: 1,
                    },
                    badge,
                ));
            }
            // And over the Remote icon for the forwarded-ports count.
            if let Some(badge) = self.remote_ports_badge.as_deref() {
                let bw = crate::iterm2_inline::count_badge_cells_w(self.remote_ports_count);
                let bx = rem_block.x + rem_block.width.saturating_sub(bw);
                let by = rem_block.y + rem_block.height.saturating_sub(1);
                blocks.push((
                    Rect {
                        x: bx,
                        y: by,
                        width: bw,
                        height: 1,
                    },
                    badge,
                ));
            }
            // And the failing-test count over the Testing (beaker) icon.
            if let Some(badge) = self.testing_badge.as_deref() {
                let bw = crate::iterm2_inline::count_badge_cells_w(self.testing_badge_count);
                let bx = tst_block.x + tst_block.width.saturating_sub(bw);
                let by = tst_block.y + tst_block.height.saturating_sub(1);
                blocks.push((
                    Rect {
                        x: bx,
                        y: by,
                        width: bw,
                        height: 1,
                    },
                    badge,
                ));
            }
        }
        // Customize Layout toolbar icons (top-right of the editor / welcome).
        // Their image swaps with the side-bar / panel visibility, exactly like
        // an activity icon swaps active/inactive. Independent of the activity
        // bar, so they still emit when it's hidden.
        let li = self.layout_icon_areas;
        let hovered = |r: Rect| {
            self.pointer_cell
                .is_some_and(|(px, py)| rect_contains(r, px, py))
        };
        let side_img = match (self.show_tree, hovered(li.toggle_side_bar)) {
            (true, false) => &images.layout_sidebar_on,
            (true, true) => &images.layout_sidebar_on_hover,
            (false, false) => &images.layout_sidebar_off,
            (false, true) => &images.layout_sidebar_off_hover,
        };
        let panel_img = match (self.show_terminal, hovered(li.toggle_panel)) {
            (true, false) => &images.layout_panel_on,
            (true, true) => &images.layout_panel_on_hover,
            (false, false) => &images.layout_panel_off,
            (false, true) => &images.layout_panel_off_hover,
        };
        let cust_img = if hovered(li.customize) {
            &images.layout_customize_hover
        } else {
            &images.layout_customize
        };
        blocks.push((li.toggle_side_bar, side_img.as_str()));
        blocks.push((li.toggle_panel, panel_img.as_str()));
        blocks.push((li.customize, cust_img.as_str()));
        blocks
            .into_iter()
            // A zero-width block means the icon is hidden (the activity bar is
            // off in Customize Layout / Zen, or the toolbar isn't laid out):
            // emit nothing so the image can't ghost.
            .filter(|(block, _)| block.width > 0 && visible(*block))
            .map(|(block, state)| ((block.x, block.y), state))
            .collect()
    }

    /// True while the activity-bar gear's menu or theme picker is open, so the
    /// gear renders in its pressed/active state. Derived from the live context
    /// menu's actions rather than a separate flag that could drift out of sync
    /// with the many places the menu is dismissed.
    fn settings_menu_active(&self) -> bool {
        self.context_menu.as_ref().is_some_and(|menu| {
            menu.items.iter().any(|entry| {
                matches!(
                    entry.action(),
                    Some(MenuAction::OpenThemePicker | MenuAction::SetTheme(_))
                )
            })
        })
    }

    /// Post-draw flush of the activity-bar icons. Re-emits the pre-encoded
    /// OSC-1337 image bytes each frame (ratatui doesn't track image cells, so
    /// neighbouring SGR traffic can evict them from iTerm2's cache) — but
    /// first applies the same emit-time move-detection as the run-debug
    /// headline icon: if the icon cells shifted since the last emit (a
    /// terminal resize, or any future layout change that recenters the bar),
    /// a plain re-emit stacks a fresh image on top of the one iTerm2 still
    /// caches at the old cell, the doubled-icon ghost. On a move it arms one
    /// `terminal.clear()` (the proven `\x1b[2J` eviction the main loop folds
    /// into its OR chain), forgets the emit positions, and skips painting
    /// this frame; the next frame clears, full-redraws, and re-emits a single
    /// clean set at the new cells.
    pub fn flush_activity_image_overlays(&mut self) {
        use std::io::Write;
        // The keepalive re-emit fights iTerm2's image-cache eviction; the sixel
        // cell buffer doesn't evict, so its icons re-emit only when dirty.
        let allow_keepalive =
            self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::Sixel;
        if !self.overlays.activity.should_refresh(allow_keepalive) {
            return;
        }
        let overlays = self.pending_activity_image_overlays();
        if overlays.is_empty() {
            return;
        }
        let positions: Vec<(u16, u16)> = overlays.iter().map(|(cell, _)| *cell).collect();
        if self.overlays.activity.positions_moved(&positions) {
            self.overlays.activity.request_clear();
            self.overlays.activity.forget_positions();
            return;
        }
        let mut out = stdout();
        let cursor_on = self.cursor_should_be_visible();
        let _ = write!(out, "\x1b[?25l\x1b[s");
        for ((x, y), seq) in &overlays {
            // Same screen bound as the image writers (#513): a raw
            // absolute-CUP write that ratatui cannot repair, so the origin
            // is checked before it is used.
            //
            // 1x1 is NARROWER than some payloads here, and knowingly so.
            // `pending_activity_image_overlays` discards each block's
            // `Rect` and returns only its origin, and a count badge is 2-3
            // cells wide (`count_badge_cells_w`), so a badge whose left
            // edge is on screen and right edge is not would pass this.
            // Not reachable today -- the badges anchor to the left-hand
            // activity bar -- and making it exact means returning the
            // `Rect` from that function, which is a wider change than this
            // guard. Recorded rather than left to be rediscovered.
            if !self.overlay_fits_on_screen(*x, *y, 1, 1) {
                continue;
            }
            let _ = write!(out, "\x1b[{};{}H", y + 1, x + 1); // 1-based
            let _ = out.write_all(seq.as_bytes());
        }
        let _ = write!(out, "\x1b[u");
        if cursor_on {
            let _ = write!(out, "\x1b[?25h");
        }
        let _ = out.flush();
        self.overlays.activity.mark_emitted();
        self.overlays.activity.store_positions(positions);
    }

    /// Whether a post-draw overlay at this cell rect may be emitted (#513).
    ///
    /// The flush block below writes with absolute CUP straight to stdout,
    /// after ratatui's diff. Two properties make a wrong origin dangerous
    /// rather than merely wrong: it is a raw write, not a buffer index, so
    /// an out-of-range origin cannot panic the way `Buffer` would; and
    /// ratatui has no record of the cells it touched, so nothing repairs
    /// them on the next frame. The corruption persists instead of clearing
    /// on repaint, which is what #510 looked like from the outside.
    ///
    /// So the payload is checked against the screen at EMIT time rather
    /// than trusting whichever cached rect produced the layout. Every
    /// writer in the block goes through it, which is the part #512's shape
    /// could not give: that fixed the terminal carrier by clearing its
    /// stored rect, but each other writer keeps its own rect with its own
    /// lifecycle, so every future site a frame can decline to paint is one
    /// more place to remember the clear.
    ///
    /// What this does NOT do, stated plainly because the bound is easy to
    /// oversell: it removes OFF-SCREEN writes only. It is a screen bound,
    /// not the owning widget's rect, so an overlay anchored on a stale rect
    /// that still lands somewhere on screen passes it untouched -- and that
    /// is the case #510 actually exhibited, a terminal image painted over a
    /// sibling pane, the sidebar and the status bar, all of them mid-screen
    /// (#512 records the landing sites). So this does not subsume #512 and
    /// does not close #513's class; it removes the unbounded half, where a
    /// wild origin can write anywhere in the terminal.
    ///
    /// The bound is the screen because the emitter does not know which
    /// widget a payload belongs to. Making it exact needs each payload to
    /// carry its owning rect, which is the wider change #513 describes.
    fn overlay_fits_on_screen(&self, cell_x: u16, cell_y: u16, cell_w: u16, cell_h: u16) -> bool {
        let area = self.last_frame_area;
        if area.width == 0 || area.height == 0 {
            // No frame has been drawn yet, so there is no screen to land on.
            return false;
        }
        // A zero-sized payload has nothing to place; treat it as unemittable
        // rather than trivially in-bounds, so a cleared rect cannot slip a
        // bare cursor park through.
        if cell_w == 0 || cell_h == 0 {
            return false;
        }
        cell_x.saturating_add(cell_w) <= area.width && cell_y.saturating_add(cell_h) <= area.height
    }

    /// Reset the blink phase so the caret is solidly visible for the next
    /// 530ms. Call after any edit, cursor movement, or focus change so the
    /// user always sees where the cursor just landed before it starts to
    /// blink off.
    fn poke_cursor(&mut self) {
        self.cursor_blink.poke();
    }

    /// Mirrors the predicate used in `App::render` to decide whether to call
    /// `frame.set_cursor_position`. Used by the post-draw overlay writer so
    /// it can re-Show the caret after the OSC-1337 image emit only when the
    /// editor would have shown it this frame.
    fn cursor_should_be_visible(&self) -> bool {
        if self.context_menu.is_some() || self.prompt.is_some() || !self.cursor_visible_phase() {
            return false;
        }
        let editor_caret = if self.editor.diff.is_some() {
            self.editor.diff_caret_screen_pos()
        } else {
            self.editor.cursor_screen_pos()
        };
        if self.focus == Pane::Editor && editor_caret.is_some() {
            return true;
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::SourceControl
            && self.source_control.cursor_screen_pos().is_some()
        {
            return true;
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Search
            && self.search.cursor_screen_pos().is_some()
        {
            return true;
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Extensions
            && self.extensions.cursor_screen_pos().is_some()
        {
            return true;
        }
        false
    }

    /// True iff the caret is currently in its visible half of the blink
    /// cycle. VS Code uses a 530ms half-period; we match. We blink in
    /// software (by toggling whether `frame.set_cursor_position` is called
    /// each frame) instead of relying on the host terminal's own blink
    /// support, which iTerm2 / Terminal.app may have disabled in user
    /// preferences.
    fn cursor_visible_phase(&self) -> bool {
        self.cursor_blink.visible_phase()
    }

    /// Re-query git status, but no more than once every ~400ms to avoid
    /// spawning a `git` process on every keystroke.  Called after the file
    /// watcher reports any changes.
    fn refresh_git_status_debounced(&mut self) {
        let want_changes = self.sidebar_view == SidebarView::SourceControl;
        self.git.request_status_debounced(want_changes);
        for (_, w) in &mut self.git_extra {
            w.request_status_debounced(want_changes);
        }
    }

    fn sync_open_file_poll_mtime(&mut self) {
        let paths = self.open_tab_paths();
        self.fs_watch.sync_open_file_mtime(&paths);
        self.drop_symbol_tab_if_file_changed();
    }

    /// Close a symbol tab once the editor is showing a different file (#369).
    ///
    /// The range is BYTE offsets into ONE buffer, so it cannot survive the
    /// move: `follow_symbol_tab_edit` would apply the new file's edits
    /// against the old file's offsets and walk the range somewhere
    /// meaningless rather than reporting `Gone`.
    ///
    /// Keyed on the ACTIVE path after the change, not on a path passed in.
    /// `open_at` looked like the chokepoint and is not - search hits, a
    /// quick-open pick with no line hint, file-tree clicks, reopen-closed-tab
    /// and plain `editor.select` all reach another file without it, and
    /// `select` carries no path a guard could inspect. Every one of those
    /// paths does reach `sync_open_file_poll_mtime`.
    ///
    /// A plain comparison is enough, and a canonicalising fallback was tried
    /// and removed. `go_to_definition` does arrive with the server's
    /// realpath-resolved URI while the tab stored whatever the user opened -
    /// but `open_preview` resolves through `find_tab_matching`, which
    /// canonicalises, so it selects the ALREADY-OPEN tab and `editor.path`
    /// keeps its original spelling. The two sides therefore cannot diverge
    /// FOR THE SAME FILE - they diverge freely when the file really changes,
    /// which is the point - because the tab's path is a copy of
    /// `editor.path` and `find_tab_matching` canonicalises before selecting.
    /// The field itself is not canonical. A canonicalising branch was
    /// therefore unreachable: three attempts to
    /// write a test that entered it all failed, and a mutation deleting it
    /// survived, which is what proved it dead rather than merely untested.
    fn drop_symbol_tab_if_file_changed(&mut self) {
        let Some((_, tab_path, _)) = self.symbol_tab.as_ref() else {
            return;
        };
        let Some(active) = self.editor.path.as_deref() else {
            // No file open at all: nothing for the range to describe.
            self.symbol_tab = None;
            return;
        };
        if tab_path.as_path() != active {
            self.symbol_tab = None;
        }
    }

    /// Every file backing an open tab, across all editor groups. The poll
    /// stats these, so a background tab in a dir that carries no watch still
    /// sees an external write.
    fn open_tab_paths(&self) -> Vec<PathBuf> {
        std::iter::once(&self.editor)
            .chain(self.editor_layout.inactive_groups())
            .flat_map(|g| g.editors.iter())
            .filter_map(|e| e.path.clone())
            .collect()
    }

    /// Sweep EVERY open tab for external on-disk changes, not just the
    /// focused one — in every editor GROUP, not just the focused one either.
    /// The poll stats each open path once and re-baselines its stamp, so a
    /// change reported to a sweep that could not reach the tab is burned: no
    /// later tick reports it again and that pane keeps stale text forever.
    /// Clean tabs reload silently; dirty tabs are flagged as conflicts (the
    /// buffer and the disk are both preserved); tabs whose reload FAILED
    /// keep their last good view and say so in the status line (#37).
    /// Returns true if any tab reloaded, failed, or entered conflict, so
    /// the caller redraws.
    fn reload_open_file_after_external_change(&mut self) -> bool {
        let guest = self.is_collab_guest();
        let root = self.tree.root.clone();
        let skip = |p: &Path| guest && collab_file_key(&root, p).is_some();
        let mut report = self.editor.reload_externally_changed_tabs(&skip);
        for group in self.editor_layout.inactive_groups_mut() {
            let extra = group.reload_externally_changed_tabs(&skip);
            report.reloaded.extend(extra.reloaded);
            report.conflicts.extend(extra.conflicts);
            report.failed.extend(extra.failed);
        }
        if report.is_empty() {
            return false;
        }
        self.refresh_git_status_debounced();
        match (
            report.reloaded.len(),
            report.conflicts.len(),
            report.failed.len(),
        ) {
            // A dirty-buffer collision outranks everything: it needs a
            // decision, so it gets the modal.
            (_, c, _) if c > 0 => {
                self.prompt_disk_conflict(report.conflicts.clone());
            }
            // A failed reload used to be silently discarded (#37): the tab
            // keeps its last good view, and the status must say so instead
            // of letting the user read stale content as current.
            (0, 0, 1) => {
                let p = report.failed[0].display();
                self.status = format!("Reload failed for {p}; keeping the last good view");
            }
            (r, 0, f) if f > 0 => {
                self.status = if r == 0 {
                    format!("Reload failed for {f} files changed on disk")
                } else {
                    format!("Reloaded {r} files, reload failed for {f} (kept their last good view)")
                };
            }
            (1, 0, 0) => {
                let p = report.reloaded[0].display();
                self.status = format!("Reloaded {p} (external change)");
            }
            (n, ..) => {
                self.status = format!("Reloaded {n} files changed on disk");
            }
        }
        // Keep the watcher's active-file baseline aligned with the reload so
        // a just-applied change doesn't re-trigger on the next poll.
        self.sync_open_file_poll_mtime();
        true
    }

    /// A dirty buffer collided with an external write. Surface it unmissably
    /// via the confirm popup (Enter reloads and discards local edits, Esc
    /// keeps them). Falls back to the status line only when another prompt
    /// already owns the modal slot, so we never stomp an in-progress input.
    fn prompt_disk_conflict(&mut self, paths: Vec<PathBuf>) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        let (title, placeholder) = match paths.as_slice() {
            [one] => (
                format!(
                    "{} changed on disk and you have unsaved edits.",
                    one.display()
                ),
                "Enter to reload (discard your edits) · Esc to keep editing",
            ),
            many => (
                format!(
                    "{} open files changed on disk with unsaved edits.",
                    many.len()
                ),
                "Enter to reload all (discard your edits) · Esc to keep editing",
            ),
        };
        if self.input_prompt.is_some() {
            self.status = title;
            return;
        }
        self.open_input_prompt(
            InputPrompt::new(InputPurpose::ReloadConflict { paths }, title, placeholder)
                .with_value("reload"),
        );
    }

    fn poll_filesystem_changes(&mut self) -> bool {
        // Runs every frame; the poll itself fires at most every 50ms and backs
        // off from there, so don't build the path list until it would be used.
        if !self.fs_watch.poll_due() {
            return false;
        }
        let open_paths = self.open_tab_paths();
        let poll = self.fs_watch.poll(&mut self.tree, &open_paths);
        // Any directory change can also be a write to a file open in some
        // tab (background or active), so sweep all tabs whenever the poll
        // saw activity, not only when the active file's own stat moved.
        if poll.open_file_changed || poll.dirs_changed {
            self.reload_open_file_after_external_change();
        }
        if poll.dirs_changed {
            self.refresh_git_status_debounced();
            if poll.finder_relevant {
                self.kick_file_finder_index_rebuild();
            }
        }
        // Stamp-gated, so an idle poll costs a stat per open diff view; on
        // hosts without a native watcher this is how a diff follows the
        // file (#471).
        let diffs_changed =
            self.refresh_open_diff_views(false, &[], &std::collections::BTreeSet::new());
        poll.open_file_changed || poll.dirs_changed || diffs_changed
    }

    /// Drain any pending filesystem events from the watcher and refresh the
    /// tree directories whose contents may have changed. Also reloads the
    /// editor's open file when an external write (vim, git pull, etc.)
    /// changes it on disk.
    /// Drain pending filesystem events. Returns `true` iff anything was
    /// processed (so the main loop knows it owes a redraw).
    /// Install background-initialised resources (fs watcher, git status) if
    /// their threads have finished. Returns true if any were installed this
    /// tick (so the caller redraws). Cheap no-op once both are installed.
    pub fn try_install_pending_init(&mut self) -> bool {
        let mut changed = self.fs_watch.try_install_watcher();
        for w in &mut self.fs_watch_extra {
            if w.try_install_watcher() {
                changed = true;
            }
        }
        if self.drain_git_responses() {
            changed = true;
        }
        // Land the background-built Cmd+P file index the moment the
        // walker thread finishes, so the very next Cmd+P opens
        // against a hot index instead of triggering the synchronous
        // fallback walk.
        self.poll_file_finder_index();
        changed
    }

    /// Drain everything the git worker has shipped back since the last
    /// tick and apply each response to the matching cache (`git_status`
    /// for the status-bar badge, `source_control.entries` for the SC
    /// panel rows). Returns true iff anything was applied so the main
    /// loop knows to redraw. Cheap when the rx is empty: a single
    /// non-blocking try_recv. Called from `try_install_pending_init`,
    /// which already runs every tick.
    pub fn drain_git_responses(&mut self) -> bool {
        // The SCM surfaces follow the repository of the root owning the
        // focused file (#149): on a switch, seed the panel from that
        // worker's cached status and re-request its change list — the
        // non-active workers' lists are discarded at their drains below.
        let follow = self.active_workspace_root();
        if follow != self.scm_follow_root {
            // The user moved focus across folders: the panel resumes
            // following, releasing any overview pin (#161).
            self.scm_follow_root = follow.clone();
            self.scm_pin = None;
        }
        // A pin naming a folder that has since left the workspace would
        // re-seed a dead root forever (#162 review): drop it here so the
        // guard holds whichever path removed the folder.
        if self
            .scm_pin
            .as_ref()
            .is_some_and(|p| !self.roots.iter().any(|r| r == p))
        {
            self.scm_pin = None;
        }
        let active = self.scm_pin.clone().unwrap_or_else(|| follow.clone());
        if active != self.active_scm_root {
            self.seed_active_scm(active);
        }
        if follow != self.active_test_root {
            self.rebind_test_root(follow);
        }
        // Ship any refresh the debounce window coalesced once the gap clears,
        // so the trailing edge of an edit burst lands without another FS event.
        let mut changed = false;
        // Roots whose HEAD oid moved in this drain: the open Source Control
        // diffs for THESE re-read their HEAD blob (#471); the rest are
        // stamp-gated like any filesystem tick.
        let mut heads_moved: Vec<PathBuf> = Vec::new();
        let mut status_arrived = false;
        let primary_root = self.roots.primary().to_path_buf();
        let mut worker_roots: Vec<PathBuf> = vec![primary_root];
        worker_roots.extend(self.git_extra.iter().map(|(r, _)| r.clone()));
        for ws_root in worker_roots {
            let is_active = ws_root == self.active_scm_root;
            // Split the borrows: the panel is only handed to the active
            // repo's worker.
            let panel = &mut self.source_control;
            let w = match self.git_extra.iter_mut().find(|(r, _)| *r == ws_root) {
                Some((_, w)) => w,
                None => &mut self.git,
            };
            w.flush_pending();
            let this_changed = w.drain_into(is_active.then_some(panel));
            // A completed refresh whose status came back identical is still
            // news to an open staged / branch / previous-commit diff (#471):
            // those read the index or a ref, which porcelain status does
            // not fully describe.
            if w.take_status_arrival() {
                status_arrived = true;
            }
            if !this_changed {
                continue;
            }
            changed = true;
            let status = w.status().clone();
            if is_active && status.in_repo && self.default_branch_label.is_none() {
                self.default_branch_label = crate::git::default_branch(&self.active_scm_root).ok();
            }
            // HEAD moved in THIS repo (commit, checkout, pull): the cached
            // gutter baselines for ITS files are stale, as is blame; the
            // COMMITS graph refetches only for the active repo.
            let oid = status.head_oid.clone();
            if self.git_head_oids.get(&ws_root) != Some(&oid) {
                self.git_head_oids.insert(ws_root.clone(), oid);
                // The diff tag stores `scm_root()`, the git TOPLEVEL, which
                // is not the workspace root for a subdirectory workspace or
                // for a root reached through a symlink (git canonicalises
                // `--show-toplevel`). Record what the tag will compare with.
                heads_moved.push(status.repo_root.clone().unwrap_or_else(|| ws_root.clone()));
                if is_active {
                    self.refresh_commit_graph();
                }
                for group in std::iter::once(&mut self.editor)
                    .chain(self.editor_layout.inactive_groups_mut())
                {
                    for ed in &mut group.editors {
                        let owned = ed
                            .path
                            .as_deref()
                            .and_then(|p| self.roots.owning_root(p))
                            .is_some_and(|r| r == ws_root);
                        if owned {
                            ed.git_baseline_for = None;
                        }
                    }
                }
                self.blame_fetched = None;
            }
        }
        if changed {
            self.refresh_scm_change_badge();
            // The overview rows track the same drains that feed the badge
            // (#162 review: sync_focus_flags runs on focus TRANSITIONS,
            // not per tick, so background-repo updates lagged).
            self.refresh_scm_repositories();
            // The Explorer dims git-ignored rows across EVERY root: each
            // worker's set is cwd-scoped to its root already, so the union
            // is exact. Single-root keeps the Arc clone (no set copy).
            if self.git_extra.is_empty() {
                self.tree.ignored = self.git.status().ignored.clone();
            } else {
                let mut union: std::collections::HashSet<PathBuf> =
                    self.git.status().ignored.as_ref().clone();
                for (_, w) in &self.git_extra {
                    union.extend(w.status().ignored.iter().cloned());
                }
                self.tree.ignored = std::sync::Arc::new(union);
            }
        }
        // A completed status refresh means HEAD or the index may have moved:
        // a Source Control diff re-reads its HEAD blob when its root's HEAD
        // oid changed, a staged / branch / previous-commit view re-runs its
        // `git diff` on every arrival (#471). This is the debounced cadence,
        // so a burst of writes costs one re-run, and a rebuilt view owes a
        // redraw even when the status itself was unchanged.
        let diffs_refreshed = (changed || status_arrived)
            && self.refresh_open_diff_views(true, &heads_moved, &std::collections::BTreeSet::new());
        changed || diffs_refreshed
    }

    /// Point the SCM surfaces at `active`'s repository: seed the panel
    /// from its worker's cached status, drop the outgoing repo's change
    /// list (rendering another repository's entries under this branch
    /// header would be wrong; the fresh list lands one worker roundtrip
    /// later), re-request it past the debounce, and refetch the COMMITS
    /// graph. Shared by the focus-follow switch and the remove-folder
    /// fallback (#150 review: assigning the field directly left the
    /// removed repo's panel on screen, since the switch-detect saw no
    /// difference).
    fn seed_active_scm(&mut self, active: PathBuf) {
        self.active_scm_root = active.clone();
        self.default_branch_label = None;
        // A lane diff belongs to the root it was asked for. Carried into
        // another repo the range names a branch that does not exist there,
        // and `branch_history_range` answers an unresolvable range with an
        // EMPTY vec rather than an error - so the panel would show a repo
        // with commits as having none, with nothing on screen saying why.
        self.graph_revspec = None;
        let w = self.git_worker_for_root_mut(&active);
        w.bypass_debounce();
        w.request_status_and_changes();
        let status = self.git_worker_for_root(&active).status().clone();
        self.source_control.set_status(status, Vec::new());
        self.refresh_scm_repositories();
        self.refresh_commit_graph();
    }

    /// Rebuild the cached source-control change-count badge after the change
    /// set, theme, or cell size shifts, and mark the activity overlay dirty so
    /// the next post-draw flush re-emits. On the glyph-fallback path (no inline
    /// images) it only tracks the count for the dirty check; that path draws a
    /// text badge directly in `render_activity_bar`.
    fn refresh_scm_change_badge(&mut self) {
        // Across EVERY folder's repository (#161): work pending in a
        // background folder must never be invisible. Single-folder, the
        // sum is exactly the active repo's porcelain count.
        let count: usize = std::iter::once(&self.git)
            .chain(self.git_extra.iter().map(|(_, w)| w))
            .map(|w| w.status().changed_count)
            .sum();
        if !self.overlays.activity.has_images() {
            self.scm_change_badge = None;
            if count != self.scm_change_badge_count {
                self.scm_change_badge_count = count;
                self.overlays.activity.mark_dirty();
            }
            return;
        }
        if count == 0 {
            if self.scm_change_badge.is_some() {
                self.scm_change_badge = None;
                self.overlays.activity.mark_dirty();
            }
            self.scm_change_badge_count = 0;
            return;
        }
        self.scm_change_badge = self.build_count_badge_image(
            count,
            crate::iterm2_inline::KITTY_ID_SCM_BADGE,
            self.theme.accent_rgb(),
        );
        self.scm_change_badge_count = count;
        self.overlays.activity.mark_dirty();
    }

    /// Build the inline-image for an activity-bar count badge (accent pill +
    /// count) at the given Kitty image id. `None` when image rendering is off or
    /// the cell size isn't known yet. Shared by the SCM, Explorer, and Remote
    /// badges so the compose/encode/tmux-wrap chain lives in one place.
    fn build_count_badge_image(
        &self,
        count: usize,
        kitty_id: u32,
        color: (u8, u8, u8),
    ) -> Option<String> {
        let (cw, ch) = self.cell_pixel?;
        let png =
            crate::iterm2_inline::compose_count_badge(count, cw, ch, color, self.theme_bg_pixel())?;
        let raw = crate::iterm2_inline::build_inline_image_z(
            self.inline_protocol,
            &png,
            crate::iterm2_inline::count_badge_cells_w(count),
            1,
            false,
            kitty_id,
            1,
        )?;
        Some(crate::iterm2_inline::maybe_tmux_wrap(
            self.inline_protocol,
            crate::iterm2_inline::detect_tmux(),
            raw,
        ))
    }

    /// Count of open editors with unsaved edits, across the active group and any
    /// split groups, deduped by path (a file open in two splits is one unsaved
    /// file; each dirty path-less buffer counts once). Drives the Explorer
    /// activity badge, mirroring VS Code.
    fn unsaved_count(&self) -> usize {
        let mut paths: std::collections::HashSet<&std::path::Path> =
            std::collections::HashSet::new();
        let mut pathless = 0usize;
        let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
        for ed in groups.flat_map(|g| g.editors.iter()).filter(|e| e.dirty) {
            match ed.path.as_deref() {
                Some(p) => {
                    paths.insert(p);
                }
                None => pathless += 1,
            }
        }
        paths.len() + pathless
    }

    /// Rebuild the cached Explorer unsaved-file badge when the count, theme, or
    /// cell size shifts, and mark the activity overlay dirty so the next flush
    /// re-emits. Cheap to call every frame: it recomputes the count and bails
    /// unless it changed. The glyph-fallback path draws a text badge in
    /// `render_activity_bar` instead.
    pub fn refresh_explorer_unsaved_badge(&mut self) {
        let count = self.unsaved_count();
        if !self.overlays.activity.has_images() {
            self.explorer_unsaved_badge = None;
            if count != self.explorer_unsaved_count {
                self.explorer_unsaved_count = count;
                self.overlays.activity.mark_dirty();
            }
            return;
        }
        if count == self.explorer_unsaved_count {
            return;
        }
        if count == 0 {
            self.explorer_unsaved_badge = None;
            self.explorer_unsaved_count = 0;
            self.overlays.activity.mark_dirty();
            return;
        }
        self.explorer_unsaved_badge = self.build_count_badge_image(
            count,
            crate::iterm2_inline::KITTY_ID_EXPLORER_BADGE,
            self.theme.accent_rgb(),
        );
        self.explorer_unsaved_count = count;
        self.overlays.activity.mark_dirty();
    }

    /// Rebuild the cached Remote forwarded-ports badge when the count, theme, or
    /// cell size shifts. Count-gated like the Explorer badge so it's a cheap
    /// per-frame no-op; the glyph-fallback path draws a text badge instead.
    pub fn refresh_remote_ports_badge(&mut self) {
        let count = self.ports.forwarded_count();
        if !self.overlays.activity.has_images() {
            self.remote_ports_badge = None;
            if count != self.remote_ports_count {
                self.remote_ports_count = count;
                self.overlays.activity.mark_dirty();
            }
            return;
        }
        if count == self.remote_ports_count {
            return;
        }
        if count == 0 {
            self.remote_ports_badge = None;
            self.remote_ports_count = 0;
            self.overlays.activity.mark_dirty();
            return;
        }
        self.remote_ports_badge = self.build_count_badge_image(
            count,
            crate::iterm2_inline::KITTY_ID_REMOTE_BADGE,
            self.theme.accent_rgb(),
        );
        self.remote_ports_count = count;
        self.overlays.activity.mark_dirty();
    }

    /// Rebuild the cached Testing failing-count badge (red pill) when the count,
    /// theme, or cell size shifts. Count-gated per-frame no-op; the glyph path
    /// draws a text badge instead.
    pub fn refresh_testing_badge(&mut self) {
        let count = self.testing.failed_count();
        if !self.overlays.activity.has_images() {
            self.testing_badge = None;
            if count != self.testing_badge_count {
                self.testing_badge_count = count;
                self.overlays.activity.mark_dirty();
            }
            return;
        }
        if count == self.testing_badge_count {
            return;
        }
        if count == 0 {
            self.testing_badge = None;
            self.testing_badge_count = 0;
            self.overlays.activity.mark_dirty();
            return;
        }
        self.testing_badge = self.build_count_badge_image(
            count,
            crate::iterm2_inline::KITTY_ID_TESTING_BADGE,
            self.theme.git_deleted_rgb(),
        );
        self.testing_badge_count = count;
        self.overlays.activity.mark_dirty();
    }

    /// Rebuild the cached PROBLEMS-tab circle badge (orange, like the activity
    /// bar badges) when the count, theme, or cell size shifts. The badge is an
    /// inline-image circle emitted post-frame by `flush_problems_badge_overlay`;
    /// glyph-fallback terminals keep the powerline-cap pill in `paint_panel_tabs`.
    /// Count-gated, so a frame with no churn is a cheap no-op.
    pub fn refresh_problems_badge(&mut self) {
        let count = self.problems.total_count();
        if !self.overlays.activity.has_images() {
            self.problems_badge_count = count;
            return;
        }
        if count == self.problems_badge_count {
            return;
        }
        self.problems_badge_count = count;
        if count == 0 {
            self.overlays.problems_badge.clear_image();
            self.overlays.problems_badge.request_clear();
            return;
        }
        if let Some(img) = self.build_count_badge_image(
            count,
            crate::iterm2_inline::KITTY_ID_PROBLEMS_BADGE,
            crate::gradient::GRAD_TR,
        ) {
            self.overlays.problems_badge.set_image(img);
        }
    }

    /// Push the current search query string and toggle state onto the
    /// worker channel and keep the editor's match highlight synced to the
    /// same term so the active file lights up matches as the user types.
    /// Called whenever the search input or one of the toggles changes.
    /// Clears the live result list so streamed `Hits` events accumulate
    /// from zero rather than appending to leftover hits from the prior query.
    fn submit_search_query(&mut self) {
        self.search.complete = false;
        self.search.hits.clear();
        self.search.selected = 0;
        self.search.scroll = 0;
        // Snapshot unsaved editor buffers so the worker searches their live
        // content (and skips the stale disk copy). This is what makes an
        // unsaved edit — e.g. a Rename Symbol — findable before save, matching
        // VS Code / Zed. Sent before the query so the next scan sees it.
        let dirty: Vec<(PathBuf, String)> = self
            .editor
            .iter_tabs()
            .filter(|t| t.dirty)
            .filter_map(|t| t.path.clone().map(|p| (p, t.lines.join("\n"))))
            .collect();
        let _ = self
            .search_query_tx
            .send(SearchRequest::SetDirtyBuffers(dirty));
        // Push the current files-to-include / files-to-exclude globs so the
        // next scan honours them (VS Code's Search filter inputs).
        let _ = self.search_query_tx.send(SearchRequest::SetFilter(
            self.search.include.clone(),
            self.search.exclude.clone(),
        ));
        let _ = self.search_query_tx.send(SearchRequest::Query(
            self.search.query.clone(),
            self.search.opts,
        ));
        let term = if self.search.query.trim().is_empty() {
            None
        } else {
            Some(self.search.query.clone())
        };
        self.editor.set_search_highlight(term, self.search.opts);
    }

    /// Apply any pending search events from the background worker. Drops
    /// stale events whose query no longer matches the input field (the
    /// user has typed past it). `Hits` events append to the live result
    /// list as files yield matches; `Done` is informational. Returns true
    /// iff hits were updated, so the main loop knows to redraw.
    pub fn drain_search_results(&mut self) -> bool {
        use crate::widgets::search::SearchEvent;
        let mut applied = false;
        while let Ok(event) = self.search_results_rx.try_recv() {
            match event {
                SearchEvent::Hits(q, opts, batch) => {
                    if q == self.search.query && opts == self.search.opts {
                        self.search.hits.extend(batch);
                        applied = true;
                    }
                }
                SearchEvent::Done(q, opts) => {
                    if q == self.search.query && opts == self.search.opts {
                        self.search.complete = true;
                        applied = true;
                    }
                }
            }
        }
        applied
    }

    /// Pull the one-shot remote-extension-index refresh if it has finished.
    /// Rebuilds the Extensions panel exactly once, when the verified cache
    /// actually changed, then drops the receiver so later calls are no-ops.
    pub fn drain_ext_index_refresh(&mut self) -> bool {
        let Some(rx) = self.ext_index_refresh.as_ref() else {
            return false;
        };
        match rx.try_recv() {
            Ok(updated) => {
                self.ext_index_refresh = None;
                if updated {
                    self.refresh_extensions();
                }
                // A user-triggered refresh reports its outcome; the silent
                // startup refresh does not (it must not clobber other status).
                if std::mem::take(&mut self.ext_index_manual_refresh) {
                    self.status = String::from(if updated {
                        "Extensions index refreshed"
                    } else {
                        "Extensions index already up to date"
                    });
                }
                updated
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => false,
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.ext_index_refresh = None;
                false
            }
        }
    }

    /// Manually re-pull the signed remote extension index (the panel's ⟳
    /// button). Re-arms the background refresh; the cached entries keep showing
    /// meanwhile, and [`Self::drain_ext_index_refresh`] rebuilds the panel and
    /// reports the outcome when it lands.
    fn refresh_extension_index(&mut self) {
        self.ext_index_manual_refresh = true;
        self.ext_index_refresh = Some(crate::mcp::registry_index::spawn_refresh());
        self.status = String::from("Refreshing extensions index\u{2026}");
    }

    /// Per-tick LSP doc sync. Diffs every text-buffer tab's edit_seq
    /// against `lsp_last_seen` and forwards did_open / did_change /
    /// did_close to the LspManager. Building `lines.join("\n")` only
    /// happens when a tab's edit_seq has actually moved, so the cost
    /// scales with edits, not with frames.
    pub fn sync_lsp(&mut self) {
        if self.lsp.is_none() {
            return;
        }
        let mut current: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
        // `(is_open, path, text, seq, viewport)`. The viewport `(start, end)`
        // lines are captured only for opens, so the first paint can fire a fast
        // `semanticTokens/range` over what is on screen ahead of the
        // whole-document request.
        type DocSync = (bool, PathBuf, String, u64, Option<(u32, u32)>);
        let mut to_send: Vec<DocSync> = Vec::new();
        // Semantic-token batches recovered from the on-disk cache for files
        // being opened this tick. Applied after the tab loop (which borrows the
        // editor immutably) so the correct colours paint on the first frame,
        // before the server finishes its ~1.8s cold analysis. See
        // `crate::lsp::semantic_cache`.
        let mut cache_hits: Vec<(PathBuf, std::sync::Arc<Vec<String>>, Vec<u32>)> = Vec::new();
        for tab in self.editor.iter_tabs() {
            if tab.has_non_text_view() {
                continue;
            }
            let Some(path) = tab.path.as_ref() else {
                continue;
            };
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if crate::lsp::Language::from_extension(ext).is_none() {
                continue;
            }
            current.insert(path.clone());
            let seq = tab.edit_seq;
            let prev = self.lsp_last_seen.get(path).copied();
            match prev {
                None => {
                    // A small look-ahead past the visible rows keeps colour
                    // stable through the first nudge of the scroll wheel
                    // before the full-document reply lands.
                    let start = tab.scroll as u32;
                    let end = (tab.scroll + tab.page_size() + 16).min(tab.lines.len()) as u32;
                    let text = tab.lines.join("\n");
                    // Paint the last-known semantic colours instantly from the
                    // disk cache, so an import-heavy file does not flash grey
                    // then snap to the server's class/namespace colours seconds
                    // later. A hit is identical to what the server will send, so
                    // the live reply is a no-op repaint.
                    if let Some((legend, data)) = crate::lsp::semantic_cache::load(path, &text) {
                        cache_hits.push((path.clone(), legend, data));
                    }
                    to_send.push((true, path.clone(), text, seq, Some((start, end))));
                }
                Some(p) if p != seq => {
                    to_send.push((false, path.clone(), tab.lines.join("\n"), seq, None))
                }
                _ => {}
            }
        }
        let lsp = match self.lsp.as_ref() {
            Some(l) => l,
            None => return,
        };
        for (is_open, path, text, seq, viewport) in to_send {
            let line_count = text.lines().count() as u32 + 1;
            if is_open {
                lsp.open_doc(path.clone(), text);
                // Paint the visible lines first: ty answers a viewport range
                // query in tens of ms even on a cold workspace, so on-screen
                // code colours immediately while the full request fills in the
                // rest. The editor refuses to let this range batch overwrite
                // the full one when it arrives.
                if let Some((start, end)) = viewport {
                    lsp.request_semantic_tokens_range(path.clone(), start, end, seq);
                }
            } else {
                lsp.change_doc(path.clone(), text);
            }
            // Refresh the whole document's semantic tokens whenever it is
            // opened or changed. Gated by the same `seq` diff as did_change
            // above, so this fires once per edit-batch, not per keystroke.
            lsp.request_semantic_tokens(path.clone(), seq);
            // Same cadence for inlay hints; the reply carries `seq` so a
            // stale batch (computed against older text) is dropped on drain.
            if self.inlay_hints_enabled {
                lsp.request_inlay_hints(path.clone(), line_count, seq);
            }
            // Document links ride the same cadence (#254); silent when no
            // server advertises a documentLinkProvider, so Ctrl+click
            // keeps meaning Go to Definition there.
            lsp.request_document_links(path.clone(), seq);
            // Fold spans ride the same cadence (#254); the worker drops
            // the request silently when no server advertises the
            // provider, which is what leaves the editor's indentation /
            // region fallback in charge.
            lsp.request_folding_ranges(path.clone(), seq);
            // Document colors ride the same cadence (#254); the worker is
            // silent when no server advertises a colorProvider, which is
            // what keeps the swatches from ever appearing unadvertised.
            lsp.request_document_colors(path.clone(), seq);
            self.lsp_last_seen.insert(path, seq);
        }
        let closed: Vec<PathBuf> = self
            .lsp_last_seen
            .keys()
            .filter(|p| !current.contains(*p))
            .cloned()
            .collect();
        let mut dropped_any = false;
        for p in closed {
            lsp.close_doc(p.clone());
            self.lsp_last_seen.remove(&p);
            // Drop the closed file's diagnostics so the store doesn't grow
            // unbounded across a long session of opening and closing files.
            dropped_any |= self.lsp_diagnostics.remove(&p).is_some();
        }
        // A closed file's problems must leave the PROBLEMS panel too.
        // Under Open Files scope the panel also depends on WHICH buffers are
        // open, so a tab opening or closing changes the answer even when no
        // diagnostic moved — rebuild when that set shifts (#256).
        let open_now: std::collections::BTreeSet<PathBuf> = self.open_buffer_paths();
        let open_changed = open_now != self.problems_open_set;
        if open_changed {
            self.problems_open_set = open_now;
        }
        let scope_depends_on_open_set =
            self.problems.scope == crate::widgets::problems::ProblemScope::OpenFiles;
        if dropped_any || (open_changed && scope_depends_on_open_set) {
            self.rebuild_problems();
            self.refresh_problems_badge();
        }
        // Paint cached semantic colours onto the visible editor(s) now that the
        // immutable tab borrow above has ended. `is_full = true` so a later
        // server `range` reply can't blank the off-screen colours, and the
        // identical `full` reply repaints to the same pixels (no snap).
        for (path, legend, data) in cache_hits {
            if self.editor.path.as_deref() == Some(path.as_path()) {
                self.editor
                    .apply_semantic_tokens(path.clone(), data.clone(), legend.clone(), true);
            }
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(path.as_path()) {
                    group.apply_semantic_tokens(path.clone(), data.clone(), legend.clone(), true);
                }
            }
        }
    }

    /// The repository toplevel owning the workspace, from the git worker's
    /// last status reply — the only correct base for porcelain-derived
    /// paths and `HEAD:<rel>` pathspecs, which git resolves against the
    /// toplevel however `-C` is set (#139). Identical to the workspace
    /// root whenever that root IS the toplevel; falls back to it outside
    /// a repo (where the ops fail with their own message) and before the
    /// first status reply lands.
    /// The primary workspace root — what `workspace_root` the field meant
    /// before the set model (#143). Single-root semantics throughout.
    pub fn workspace_root(&self) -> &Path {
        self.roots.primary()
    }

    fn scm_root(&self) -> PathBuf {
        let ws = self.active_scm_root.clone();
        self.git_worker_for_root(&ws)
            .status()
            .repo_root
            .clone()
            .unwrap_or(ws)
    }

    /// The workspace root the focus-following surfaces resolve against:
    /// the root owning the focused editor's file, else the primary
    /// (#149 git, #151 testing/tasks/run).
    fn active_workspace_root(&self) -> PathBuf {
        self.editor
            .path
            .as_deref()
            .and_then(|p| self.roots.owning_root(p))
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf()
    }

    /// The git worker for a workspace root: the primary's, or the
    /// matching secondary's (#149).
    fn git_worker_for_root(&self, ws_root: &Path) -> &GitWorker {
        self.git_extra
            .iter()
            .find(|(r, _)| r == ws_root)
            .map(|(_, w)| w)
            .unwrap_or(&self.git)
    }

    fn git_worker_for_root_mut(&mut self, ws_root: &Path) -> &mut GitWorker {
        match self.git_extra.iter().position(|(r, _)| r == ws_root) {
            Some(i) => &mut self.git_extra[i].1,
            None => &mut self.git,
        }
    }

    /// The active repository's worker — what `self.git` meant while
    /// there was one root (#149).
    fn scm_worker(&self) -> &GitWorker {
        self.git_worker_for_root(&self.active_scm_root)
    }

    /// Rebuild the multi-root repositories overview rows (#161) from the
    /// per-folder workers: called from the git drain (fresh statuses),
    /// the focus sync, and the seed (active-highlight moves with a row
    /// click). Empty — section hidden — with one folder.
    fn refresh_scm_repositories(&mut self) {
        self.source_control.repositories = if self.roots.is_multi() {
            let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
            let labels = crate::workspace::root_display_labels(&roots);
            roots
                .iter()
                .zip(labels)
                .filter_map(|(ws, label)| {
                    let status = self.git_worker_for_root(ws).status();
                    if !status.in_repo {
                        return None;
                    }
                    Some(crate::widgets::source_control::RepoRow {
                        label,
                        branch: status.branch.clone(),
                        changes: status.changed_count,
                        active: *ws == self.active_scm_root,
                        workspace_root: ws.clone(),
                    })
                })
                .collect()
        } else {
            Vec::new()
        };
    }

    /// Let the ACTIVE repo's next debounced refresh through immediately —
    /// every Source Control mutation runs against the active repo (#149).
    fn active_git_bypass_debounce(&mut self) {
        let ws = self.active_scm_root.clone();
        self.git_worker_for_root_mut(&ws).bypass_debounce();
    }

    /// Keep each text tab's git-gutter baseline current. The first time a tab
    /// is seen (or after it switches files, or after HEAD moves), shell out
    /// once for the committed version of the file and hand it to the editor;
    /// the per-line diff is then recomputed in-buffer on every edit with no
    /// further subprocess. Cheap no-op once every open tab has a baseline:
    /// just a path compare per tab.
    ///
    /// `read_file_at_head` is a `git show` (~tens of ms) but runs at most once
    /// per (file, HEAD) pair, never on the keystroke path. Baselines are shared
    /// across groups within a sweep: a split usually holds the SAME file in two
    /// panes, and a HEAD move invalidates every tab in every group at once, so
    /// without the cache one tick would shell out once per tab per group.
    /// ponytail: synchronous fetch on the tick. Move to the git worker thread
    /// if opening a file in a huge repo ever visibly hitches.
    fn sync_git_gutters(&mut self) {
        // `HEAD:<rel>` pathspecs resolve against the toplevel (#139), and
        // each file resolves against the repo of ITS owning workspace
        // root (#149). Precompute (workspace root → repo toplevel) so the
        // editor loop below borrows nothing else off self.
        let repo_bases: Vec<(PathBuf, PathBuf)> = self
            .roots
            .iter()
            .map(Path::to_path_buf)
            .collect::<Vec<_>>()
            .into_iter()
            .map(|ws| {
                let repo = self
                    .git_worker_for_root(&ws)
                    .status()
                    .repo_root
                    .clone()
                    .unwrap_or_else(|| ws.clone());
                (ws, repo)
            })
            .collect();
        let repo_for = |path: &Path| -> Option<PathBuf> {
            repo_bases
                .iter()
                .filter(|(ws, _)| path.starts_with(ws))
                .max_by_key(|(ws, _)| ws.components().count())
                .map(|(_, repo)| repo.clone())
        };
        let mut fetched: std::collections::HashMap<PathBuf, Option<Vec<String>>> =
            std::collections::HashMap::new();
        let groups =
            std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
        for ed in groups.flat_map(|g| g.editors.iter_mut()) {
            let Some(path) = ed.path.clone() else {
                continue;
            };
            if ed.git_baseline_for.as_deref() == Some(path.as_path()) {
                continue;
            }
            // Untracked files / non-repo dirs yield Err here, so the gutter
            // simply shows nothing; the baseline-for marker still updates so we
            // don't re-shell every tick.
            let head = fetched
                .entry(path.clone())
                .or_insert_with(|| {
                    let root = repo_for(&path)?;
                    path.strip_prefix(&root)
                        .ok()
                        .and_then(|rel| rel.to_str())
                        .and_then(|rel| crate::git::read_file_at_head(&root, rel).ok())
                        .map(|text| text.lines().map(str::to_string).collect())
                })
                .clone();
            ed.set_git_head_lines(path, head);
        }
    }

    /// Fetch per-line git blame for the active editor off-thread, once per
    /// (file, HEAD). Mirrors the TIMELINE fetch: a marker gates the spawn so
    /// it fires exactly once per active-file change, and a HEAD move resets
    /// the marker (see the git-drain path) so blame refreshes after a commit.
    /// Gated on the pref so a subprocess never runs when blame is off.
    fn sync_blame(&mut self) {
        self.editor.blame_enabled = self.inline_blame_enabled;
        self.editor.provenance_overlay = self.provenance_overlay;
        self.editor.auto_close_pairs = self.auto_close_pairs;
        if !self.inline_blame_enabled {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            self.blame_fetched = None;
            return;
        };
        if self.blame_fetched.as_deref() == Some(path.as_path()) {
            return;
        }
        self.blame_fetched = Some(path.clone());
        // Pair `-C` and the pathspec with the OWNING workspace root
        // (#149): a secondary root's file blames within its own repo;
        // the cwd-relative pathspec stays consistent by construction.
        let root = self
            .roots
            .owning_root(&path)
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf();
        let Some(rel) = path
            .strip_prefix(&root)
            .ok()
            .and_then(|r| r.to_str())
            .map(String::from)
        else {
            // Outside the repo: no blame, but the marker is set so we don't
            // respawn every tick.
            self.editor.set_blame(path, None);
            return;
        };
        let tx = self.blame_tx.clone();
        std::thread::spawn(move || {
            let blame = crate::git::blame(&root, &rel);
            let _ = tx.send((path, blame));
        });
    }

    /// Install any blame reply whose file is still the active editor. An
    /// empty result (untracked file, git unavailable) clears the annotation.
    /// Returns true when a reply landed so the frame redraws with it.
    fn drain_blame(&mut self) -> bool {
        let mut changed = false;
        while let Ok((path, blame)) = self.blame_rx.try_recv() {
            if self.editor.path.as_deref() == Some(path.as_path()) {
                let data = if blame.is_empty() { None } else { Some(blame) };
                self.editor.set_blame(path, data);
                changed = true;
            }
        }
        changed
    }

    /// Drain LSP completion responses. Drops responses with stale request
    /// ids so a slow earlier reply cannot clobber a fresher popup. Returns
    /// true when the popup state changed and the next frame should redraw.
    pub fn drain_lsp_completion(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut changed = false;
        while let Some(result) = lsp.drain_completion() {
            if Some(result.request_id) != self.completion_request_id {
                continue;
            }
            let Some((cx, cy)) = self.editor.cursor_screen_pos() else {
                continue;
            };
            let prefix = self.editor.word_before_cursor();
            let server_count = result.items.len();
            // Merge user snippets whose prefix matches the typed word into the
            // suggestion list (VS Code shows snippets in the suggest widget);
            // the popup's own prefix filter narrows them further.
            let mut items = result.items;
            let lang = self.editor.scope_id();
            for snip in self.snippets.matching(&prefix, lang) {
                items.push(snippet_completion_item(snip));
            }
            if items.is_empty() {
                if self.completion_popup.is_some() {
                    self.completion_popup = None;
                    changed = true;
                }
                continue;
            }
            let popup = crate::widgets::completion_popup::CompletionPopup::new(
                items,
                prefix.clone(),
                (cx, cy),
                result.path,
                result.request_id,
            );
            let filtered = popup.visible_indices().len();
            crate::lsp::log_file::log(&format!(
                "popup filter: prefix={prefix:?} server={server_count} visible={filtered}"
            ));
            if popup.visible_is_empty() {
                self.completion_popup = None;
                self.status =
                    format!("No completions match '{prefix}' ({server_count} from server)");
            } else {
                self.completion_popup = Some(popup);
            }
            changed = true;
        }
        changed
    }

    /// Tab in the editor: advance a live snippet, else expand a user snippet
    /// whose prefix sits before the caret, else fall back to indentation.
    fn handle_editor_tab(&mut self) {
        if self.editor.snippet_active() {
            self.editor.snippet_next();
            return;
        }
        if self.try_expand_snippet() {
            return;
        }
        if self.editor.selection_is_multiline() {
            self.editor.indent_lines();
        } else {
            self.editor.indent_at_cursor();
        }
    }

    /// Expand the user snippet whose prefix exactly matches the word before the
    /// caret (in the buffer's language). Returns false when nothing matches, so
    /// Tab can fall through to indenting.
    fn try_expand_snippet(&mut self) -> bool {
        if self.snippets.is_empty() || self.editor.selection.is_some() {
            return false;
        }
        let word = self.editor.word_before_cursor();
        if word.is_empty() {
            return false;
        }
        let lang = self.editor.scope_id();
        let Some(body) = self.snippets.exact(&word, lang).map(|s| s.body.clone()) else {
            return false;
        };
        self.completion_popup = None;
        self.completion_request_id = None;
        self.editor.expand_snippet(&body, word.chars().count());
        true
    }

    pub fn trigger_completion(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_completion(path, line, character);
        self.completion_request_id = Some(id);
    }

    /// Ask the server for parameter hints at the caret (typing `(` or `,`).
    pub fn trigger_signature_help(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_signature_help(path, line, character);
        self.signature_help_request_id = Some(id);
        self.signature_help_anchor = Some((
            self.editor.cursor_row,
            self.editor.cursor_col,
            self.editor.edit_seq,
        ));
    }

    /// Dismiss the parameter-hints popup (typing `)`, Esc, or moving away).
    fn dismiss_signature_help(&mut self) {
        self.signature_help_popup = None;
        self.signature_help_request_id = None;
        self.signature_help_anchor = None;
    }

    /// While the parameter-hints popup is open, re-query when the caret moves
    /// or the buffer changes (typing an argument, backspacing, arrowing, a
    /// click). The empty-response path closes the popup once the caret is no
    /// longer inside a call; a non-empty reply keeps it open with the active
    /// parameter following the caret. Cheap: only runs while a popup is up.
    fn refresh_signature_help_if_moved(&mut self) {
        if self.signature_help_popup.is_none() {
            return;
        }
        let now = (
            self.editor.cursor_row,
            self.editor.cursor_col,
            self.editor.edit_seq,
        );
        if self.signature_help_anchor == Some(now) {
            return;
        }
        // The caret left the editor entirely (focus moved to tree/terminal):
        // drop the hint rather than re-query against a stale position.
        if self.focus != Pane::Editor {
            self.dismiss_signature_help();
            return;
        }
        self.trigger_signature_help();
    }

    /// Drain LSP signatureHelp responses, dropping stale ids. An empty reply
    /// closes any open popup; otherwise the popup is re-anchored to the caret.
    pub fn drain_lsp_signature_help(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut changed = false;
        while let Some(result) = lsp.drain_signature_help() {
            if Some(result.request_id) != self.signature_help_request_id {
                continue;
            }
            if result.signatures.is_empty() {
                if self.signature_help_popup.is_some() {
                    self.signature_help_popup = None;
                    changed = true;
                }
                continue;
            }
            let Some((cx, cy)) = self.editor.cursor_screen_pos() else {
                continue;
            };
            self.signature_help_popup = Some(
                crate::widgets::signature_help_popup::SignatureHelpPopup::new(
                    result.signatures,
                    result.active_signature,
                    (cx, cy),
                    result.path,
                    result.request_id,
                ),
            );
            changed = true;
        }
        changed
    }

    /// Map a pointer cell to the activity-bar icon under it, if any. Uses the
    /// same per-icon rectangles the click handler hit-tests, so hover and
    /// click target exactly the same cells.
    fn activity_icon_at(&self, col: u16, row: u16) -> Option<ActivityIcon> {
        let a = &self.sidebar_areas;
        if rect_contains(a.explorer_icon, col, row) {
            Some(ActivityIcon::Explorer)
        } else if rect_contains(a.search_icon, col, row) {
            Some(ActivityIcon::Search)
        } else if rect_contains(a.source_control_icon, col, row) {
            Some(ActivityIcon::SourceControl)
        } else if rect_contains(a.remote_icon, col, row) {
            Some(ActivityIcon::Remote)
        } else if rect_contains(a.run_debug_icon, col, row) {
            Some(ActivityIcon::RunDebug)
        } else if rect_contains(a.extensions_icon, col, row) {
            Some(ActivityIcon::Extensions)
        } else if rect_contains(a.testing_icon, col, row) {
            Some(ActivityIcon::Testing)
        } else if rect_contains(a.settings_icon, col, row) {
            Some(ActivityIcon::Settings)
        } else {
            None
        }
    }

    /// The hover-tooltip label for whatever chrome control sits under the
    /// pointer, or `None` over inert space. The single dispatch point for
    /// button hints: each surface contributes one branch that reuses that
    /// surface's own hit-test, so adding a new tooltipped control is a
    /// one-line change here plus a label in the widget.
    fn ui_tooltip_at(&self, col: u16, row: u16) -> Option<&'static str> {
        // Layout-control icons at the top-right of the editor strip / welcome.
        let icons = self.layout_icon_areas;
        if rect_contains(icons.toggle_side_bar, col, row) {
            return Some("Toggle Primary Side Bar");
        }
        if rect_contains(icons.toggle_panel, col, row) {
            return Some("Toggle Panel");
        }
        if rect_contains(icons.customize, col, row) {
            return Some("Customize Layout");
        }
        // Activity bar: always visible, so it is checked regardless of which
        // sidebar view is open.
        if let Some(icon) = self.activity_icon_at(col, row) {
            return Some(match icon {
                ActivityIcon::Explorer => "Explorer",
                ActivityIcon::Search => "Search",
                ActivityIcon::SourceControl => "Source Control",
                ActivityIcon::Remote => "Remote",
                ActivityIcon::RunDebug => "Run and Debug",
                ActivityIcon::Extensions => "Extensions",
                ActivityIcon::Testing => "Testing",
                ActivityIcon::Settings => "Manage",
            });
        }
        // Sidebar header actions, dispatched by the view that owns them so a
        // panel's stored geometry is never consulted once another view has
        // replaced it on screen.
        match self.sidebar_view {
            SidebarView::Search => {
                if let Some(label) = self.search.tooltip_at(col, row) {
                    return Some(label);
                }
            }
            SidebarView::Explorer => {
                let t = &self.tree;
                if rect_contains(t.header_new_file_btn, col, row) {
                    return Some("New File");
                }
                if rect_contains(t.header_new_folder_btn, col, row) {
                    return Some("New Folder");
                }
                if rect_contains(t.header_refresh_btn, col, row) {
                    return Some("Refresh Explorer");
                }
                if rect_contains(t.header_collapse_btn, col, row) {
                    return Some("Collapse Folders in Explorer");
                }
                if rect_contains(t.header_views_btn, col, row) {
                    return Some("Views and More Actions");
                }
            }
            SidebarView::Remote => {
                let r = &self.remote;
                if rect_contains(r.header_add_btn, col, row) {
                    return Some("Open SSH Configuration File");
                }
                if rect_contains(r.header_refresh_btn, col, row) {
                    return Some("Refresh");
                }
            }
            SidebarView::SourceControl => {
                if rect_contains(self.source_control.header_refresh_btn, col, row) {
                    return Some("Refresh");
                }
            }
            SidebarView::RunDebug => {}
            SidebarView::Extensions => {
                if let Some(label) = self.extensions_tooltip_at(col, row) {
                    return Some(label);
                }
            }
            SidebarView::Testing => {}
        }
        None
    }

    /// Resolve the hover tooltip for whatever the pointer is over in the
    /// Extensions panel: the toggle switch (state-aware enable/disable), the
    /// `+Add` affordance on AVAILABLE rows, or a row body (which conveys the
    /// extension's class and how to remove it). Catalog-aware so an installed
    /// catalog entry advertises Delete-to-uninstall while a hand-dropped user
    /// manifest is correctly described as disable-only.
    fn extensions_tooltip_at(&self, col: u16, row: u16) -> Option<&'static str> {
        // A tooltip fires ONLY over an actual control, never over the row's
        // name/blurb — so hovering the body shows nothing, and each control
        // describes just itself. The trash button takes precedence over the
        // switch since it sits left of it (and is checked first regardless).
        if self.extensions.click_refresh(col, row) {
            return Some("Refresh the extension index");
        }
        if self.extensions.click_clear(col, row) {
            return Some("Clear the filter");
        }
        if self.extensions.click_uninstall(col, row) {
            return Some("Uninstall this extension (returns to Available)");
        }
        if !self.extensions.click_action(col, row) {
            return None;
        }
        let idx = self.extensions.row_at(row)?;
        let item = self.extensions.item_at(idx)?;
        Some(if item.available {
            "Add to your installed extensions"
        } else if item.enabled {
            "Enabled \u{2014} click to disable"
        } else {
            "Disabled \u{2014} click to enable"
        })
    }

    /// Fire the chrome button-hint tooltip once its dwell crosses
    /// `HOVER_DELAY`. Returns `true` when a tooltip was created so the frame
    /// loop redraws. Suppressed while a context menu is open so the two never
    /// overlap.
    fn poll_ui_tooltip(&mut self) -> bool {
        if !self.ui_hover.due(std::time::Instant::now(), HOVER_DELAY) {
            return false;
        }
        self.ui_hover.mark_fired();
        if self.context_menu.is_some() {
            return false;
        }
        let Some(label) = self.ui_tooltip_label else {
            return false;
        };
        let Some((col, row)) = self.ui_hover.cell() else {
            return false;
        };
        self.ui_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new_compact(
            label.to_string(),
            (col, row),
        ));
        true
    }

    fn on_mouse_moved(&mut self, col: u16, row: u16, in_editor: bool) {
        // Activity-bar hover: brighten the icon under the pointer. Re-emit the
        // swapped pre-baked image only when the hovered icon actually changes,
        // so a pointer drifting within one icon (or anywhere else) costs
        // nothing. Computed before the tab/editor early-returns below so the
        // hover clears the moment the pointer leaves the bar.
        let new_hover = self.activity_icon_at(col, row);
        if self.hovered_activity_icon != new_hover {
            self.hovered_activity_icon = new_hover;
            self.overlays.activity.mark_dirty();
        }
        // Layout toolbar hover: same affordance, re-emit the brighter image
        // variant only when the hovered icon changes.
        let li = self.layout_icon_areas;
        let new_layout_hover = if rect_contains(li.toggle_side_bar, col, row) {
            Some(0)
        } else if rect_contains(li.toggle_panel, col, row) {
            Some(1)
        } else if rect_contains(li.customize, col, row) {
            Some(2)
        } else {
            None
        };
        if self.hovered_layout_icon != new_layout_hover {
            self.hovered_layout_icon = new_layout_hover;
            self.overlays.activity.mark_dirty();
        }
        // Chrome button hints: dwell over a labelled control (activity-bar
        // icons, search-panel actions/toggles) to surface its name. Keyed on
        // the label so the dwell only restarts when the pointer crosses to a
        // different control, and is left running while it drifts within one.
        // Computed before the tab/editor early-returns so it tracks the
        // pointer everywhere, including over the sidebar.
        match self.ui_tooltip_at(col, row) {
            // Same label AND still on the same row: keep the dwell running so the
            // tooltip persists while the pointer drifts within one control. The
            // row check matters because adjacent controls can share a label (e.g.
            // every enabled extension toggle reads "Enabled — click to disable");
            // without it the anchor would freeze on the first such control and
            // the box would appear detached from the one actually under the
            // pointer.
            Some(label)
                if self.ui_tooltip_label == Some(label)
                    && self.ui_hover.cell().map(|(_, r)| r) == Some(row) => {}
            Some(label) => {
                self.ui_hover.on_move(std::time::Instant::now(), col, row);
                self.ui_tooltip_label = Some(label);
                self.ui_tooltip = None;
            }
            None => {
                self.ui_hover.clear();
                self.ui_tooltip = None;
                self.ui_tooltip_label = None;
            }
        }
        // Editor tab strip: dwell over a tab to surface its full path. The
        // dwell only restarts when the pointer crosses into a *different*
        // tab, so the tooltip keeps showing while the pointer drifts a few
        // cells within the same tab (matches the LSP "same word" rule).
        if let Some(idx) = self.editor.tab_at(col, row) {
            self.hover.clear();
            self.hover_popup = None;
            self.hover_word = None;
            self.hover_diagnostic = None;
            self.hover_request_id = None;
            if self.tab_hover_idx != Some(idx) {
                self.tab_hover.on_move(std::time::Instant::now(), col, row);
                self.tab_hover_idx = Some(idx);
                self.tab_tooltip = None;
            }
            return;
        }
        self.tab_hover.clear();
        self.tab_tooltip = None;
        self.tab_hover_idx = None;
        if !in_editor {
            self.hover.clear();
            // A terminal-annotation note survives pointer drift while the
            // pointer stays on its own span (the editor's same-region rule);
            // leaving the span dismisses it. Matching the popup's text to
            // the span's note keeps a stale editor hover from hiding here.
            let over_own_note = self
                .hover_popup
                .as_ref()
                .zip(self.terminal().annotation_at(col, row))
                .is_some_and(|(popup, (_, note))| popup.lines.join("\n") == note);
            if !over_own_note {
                self.hover_popup = None;
            }
            self.hover_word = None;
            self.hover_diagnostic = None;
            self.hover_request_id = None;
            return;
        }
        self.hover.on_move(std::time::Instant::now(), col, row);
        if self.hover_popup.is_some() {
            let current = self
                .editor
                .buffer_pos_at(col, row)
                .and_then(|(line, c)| self.editor.hover_region_at(line, c));
            if current != self.hover_word {
                self.hover_popup = None;
                self.hover_word = None;
                self.hover_diagnostic = None;
                self.hover_request_id = None;
            }
        }
    }

    fn poll_hover(&mut self) {
        if !self.hover.due(std::time::Instant::now(), HOVER_DELAY) {
            return;
        }
        self.hover.mark_fired();
        if self.completion_popup.is_some() {
            return;
        }
        if self.editor.has_non_text_view() {
            return;
        }
        let Some((col, row)) = self.hover.cell() else {
            return;
        };
        self.hover_at_cell(col, row);
    }

    /// Resolve a hover at screen cell `(col, row)`: capture any diagnostic
    /// under the point synchronously and, for a real identifier, fire the
    /// async `textDocument/hover`. Split out of `poll_hover` so the dwell
    /// timer doesn't have to be driven to test the resolution logic.
    fn hover_at_cell(&mut self, col: u16, row: u16) {
        let Some((line, c)) = self.editor.buffer_pos_at(col, row) else {
            return;
        };
        // The region (word, or else a diagnostic span over punctuation) the
        // popup belongs to. Nothing of interest under the point → no hover.
        let Some(region) = self.editor.hover_region_at(line, c) else {
            return;
        };
        self.hover_anchor = Some((col, row));
        self.hover_word = Some(region);
        // Debug hover-to-evaluate: while paused, hovering a variable shows its
        // current value (from the loaded locals/globals) instead of the LSP
        // type hover. Takes priority because the live value is what the user
        // wants mid-debug.
        if let Some(text) = self.debug_hover_value(line, c) {
            self.hover_request_id = None;
            self.hover_diagnostic = None;
            self.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
                text,
                (col, row),
            ));
            return;
        }
        // Server diagnostics are already in the editor, so capture the
        // message synchronously; the squiggle's message must show even if the
        // server has no type info (or no LSP is attached at all).
        self.hover_diagnostic = format_diagnostics(&self.editor.diagnostics_at(line, c));
        // Only a real word is worth a `textDocument/hover` round-trip; over
        // punctuation there is no symbol to describe, so show the diagnostic
        // alone right away.
        let word = self.editor.word_at(line, c).is_some();
        // Converted before the match: `self.lsp.as_mut()` borrows self for the
        // whole scrutinee, so the editor is unreachable inside the arm.
        let (uline, uchar) = self.editor.pos_to_utf16(line, c);
        match (word, self.editor.path.clone(), self.lsp.as_mut()) {
            (true, Some(path), Some(lsp)) => {
                let id = lsp.request_hover(path, uline, uchar);
                self.hover_request_id = Some(id);
            }
            _ => {
                self.hover_request_id = None;
                self.hover_popup = compose_hover(self.hover_diagnostic.as_deref(), None)
                    .map(|text| crate::widgets::hover_popup::HoverPopup::new(text, (col, row)));
            }
        }
    }

    /// Fire the tab-strip tooltip once its dwell crosses `HOVER_DELAY`.
    /// Returns `true` when a tooltip was created so the frame loop knows
    /// to redraw. Suppressed while a tab context menu is open so the
    /// right-click menu never collides with the tooltip.
    fn poll_tab_hover(&mut self) -> bool {
        if !self.tab_hover.due(std::time::Instant::now(), HOVER_DELAY) {
            return false;
        }
        self.tab_hover.mark_fired();
        if self.context_menu.is_some() {
            return false;
        }
        let Some(idx) = self.tab_hover_idx else {
            return false;
        };
        let Some((col, row)) = self.tab_hover.cell() else {
            return false;
        };
        let Some(path) = self.editor.tab_full_path(idx) else {
            return false;
        };
        self.tab_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new(
            path,
            (col, row),
        ));
        true
    }

    pub fn drain_lsp_hover(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut changed = false;
        while let Some(result) = lsp.drain_hover() {
            if Some(result.request_id) != self.hover_request_id {
                continue;
            }
            let current = self
                .hover
                .cell()
                .and_then(|(c, r)| self.editor.buffer_pos_at(c, r))
                .and_then(|(line, ch)| self.editor.hover_region_at(line, ch));
            if current != self.hover_word {
                continue;
            }
            // Diagnostic on top, type info below (VS Code PR #166560). Either
            // side may be empty; an all-empty compose hides the popup.
            let anchor = self.hover_anchor.unwrap_or((0, 0));
            self.hover_popup =
                compose_hover(self.hover_diagnostic.as_deref(), result.text.as_deref())
                    .map(|text| crate::widgets::hover_popup::HoverPopup::new(text, anchor));
            changed = true;
        }
        changed
    }

    /// Drain semantic-token batches and hand each to whichever editor group
    /// currently shows that file. Returns true when an overlay changed and
    /// the next frame should redraw.
    pub fn drain_lsp_semantic_tokens(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        // Collect first so the immutable borrow of `lsp` ends before the
        // editors are mutated below.
        let mut updates = Vec::new();
        while let Some(u) = lsp.drain_semantic_tokens() {
            updates.push(u);
        }
        let mut changed = false;
        for u in updates {
            // Drop a batch measured against text the buffer has moved past —
            // an external reload swaps the whole document while a request is
            // still in its retry backoff. Decoding it over the new lines
            // paints the old file's colours at the wrong offsets, and the
            // `is_full` cache store below would persist that under the NEW
            // content's key, replaying it on every future open.
            if !semantic_reply_is_current(
                self.semantic_generation_seen.get(&u.path).copied(),
                u.generation,
            ) {
                continue;
            }
            let mut applied_anywhere = false;
            if self.editor.path.as_deref() == Some(u.path.as_path())
                && self.editor.edit_seq == u.seq
            {
                self.editor.apply_semantic_tokens(
                    u.path.clone(),
                    u.data.clone(),
                    u.legend.clone(),
                    u.is_full,
                );
                changed = true;
                applied_anywhere = true;
            }
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(u.path.as_path()) && group.edit_seq == u.seq {
                    group.apply_semantic_tokens(
                        u.path.clone(),
                        u.data.clone(),
                        u.legend.clone(),
                        u.is_full,
                    );
                    changed = true;
                    applied_anywhere = true;
                }
            }
            // Persist whole-document batches so the next open of this exact
            // content paints these colours instantly instead of waiting out the
            // server's cold analysis. Only when a visible editor holds the file
            // unchanged, so the cache key matches the bytes the next open reads.
            if applied_anywhere {
                self.semantic_generation_seen
                    .insert(u.path.clone(), u.generation);
            }
            if u.is_full && applied_anywhere {
                let mut clean_text = (self.editor.path.as_deref() == Some(u.path.as_path()))
                    .then(|| self.editor.clean_cache_text())
                    .flatten();
                if clean_text.is_none() {
                    clean_text = self
                        .editor_layout
                        .inactive_groups_mut()
                        .into_iter()
                        .find(|g| g.path.as_deref() == Some(u.path.as_path()))
                        .and_then(|g| g.clean_cache_text());
                }
                if let Some(text) = clean_text {
                    crate::lsp::semantic_cache::store(&u.path, &text, &u.legend, &u.data);
                }
            }
        }
        changed
    }

    /// Route drained inlay-hint batches to whichever visible editor holds the
    /// file. A reply whose `seq` no longer matches the buffer's last-synced
    /// edit seq is dropped: its anchors were computed against older text, and
    /// the request fired for the current seq is still in flight.
    pub fn drain_lsp_inlay_hints(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut updates = Vec::new();
        while let Some(u) = lsp.drain_inlay_hints() {
            updates.push(u);
        }
        let mut changed = false;
        for u in updates {
            if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
                continue;
            }
            if self.editor.path.as_deref() == Some(u.path.as_path()) {
                self.editor
                    .apply_inlay_hints(u.path.clone(), u.hints.clone());
                changed = true;
            }
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(u.path.as_path()) {
                    group.apply_inlay_hints(u.path.clone(), u.hints.clone());
                    changed = true;
                }
            }
        }
        changed
    }

    /// Drain document-link batches (#254) into every editor showing the
    /// file — the inlay fan-out, seq gate included. Links change no
    /// pixels, so this never asks for a redraw.
    pub fn drain_lsp_document_links(&mut self) {
        let Some(lsp) = self.lsp.as_ref() else {
            return;
        };
        let mut updates = Vec::new();
        while let Some(u) = lsp.drain_document_links() {
            updates.push(u);
        }
        for u in updates {
            if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
                continue;
            }
            if self.editor.path.as_deref() == Some(u.path.as_path()) {
                self.editor
                    .apply_document_links(u.path.clone(), u.links.clone());
            }
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(u.path.as_path()) {
                    group.apply_document_links(u.path.clone(), u.links.clone());
                }
            }
        }
    }

    /// Follow a server-resolved document link (#254): `file://` targets
    /// open in the editor, web links go to the system opener — or, on a
    /// relay-capable session, to the user's own browser through the relay.
    ///
    /// Web links only past the `file://` branch, matching
    /// `open_detected_url`: the target comes from a language server and the
    /// text it decorates says nothing about where it points, so a
    /// custom-scheme URI would hand `open`/`xdg-open` an arbitrary target
    /// (app launch, protocol handler) off one disguised Ctrl+click. The
    /// refusal surfaces the real destination in the status line.
    fn open_document_link(&mut self, target: &str) {
        // One normalisation for every branch below, so the string that is
        // checked is the string that is forwarded: surrounding whitespace is
        // dropped, a control character (which the relay's own validator
        // rejects, and which has no business in a URI) refuses outright, and
        // the scheme match is case-insensitive like `file_ref`'s.
        let target = target.trim();
        if target.chars().any(char::is_control) {
            self.status = format!("Refused to open malformed link: {target:?}");
            return;
        }
        let lower = target.to_ascii_lowercase();
        if lower.starts_with("file://") {
            if let Ok(url) = lsp_types::Url::parse(target)
                && let Ok(p) = url.to_file_path()
            {
                // Record where the user was so Back returns to it, exactly
                // like go-to-definition and terminal file links.
                let from = self.editor.path.clone().map(|path| NavLoc {
                    path,
                    row: self.editor.cursor_row,
                    col: self.editor.cursor_col,
                });
                match self.editor.open_pinned(&p) {
                    Ok(()) => {
                        if let Some(loc) = from {
                            self.nav.record(loc);
                        }
                        self.focus_pane(Pane::Editor);
                        self.status = format!("Opened {}", self.status_path(&p));
                    }
                    Err(e) => self.status = format!("Open failed: {e}"),
                }
                return;
            }
            self.status = String::from("Malformed file link");
            return;
        }
        // Deliberately NOT delegated to `open_detected_url`, despite the
        // duplicated guard below: that path first probes `diff://` and
        // `editor_file_uri`, which resolves `vscode://file/<path>` (and the
        // Cursor/Windsurf/Zed schemes) into a file open. A terminal link is
        // text the user's own program printed; a document link's target is
        // chosen by the language server, so letting it name an editor URI
        // would hand a server the ability to open arbitrary paths from a
        // click on unrelated-looking text.
        let scheme_ok = lower.starts_with("http://") || lower.starts_with("https://");
        if !scheme_ok {
            self.status = format!("Refused to open non-web link: {target}");
            return;
        }
        // Web link on a remote session: the relay can put it in front of the
        // user's own browser, exactly like a terminal link.
        if self.drop_relay_active() || is_remote_session() {
            self.open_detected_url(target);
            return;
        }
        self.status = match open_url(target) {
            Ok(()) => format!("Opened {target}"),
            Err(e) => format!("Open link failed: {e}"),
        };
    }

    /// Drain the LSP fold-span replies (#254) into every editor showing
    /// the file. Seq-gated like inlay hints; an EMPTY reply is dropped so
    /// a server that answers before indexing (or lacks real spans) never
    /// erases the indentation/region fallback — the outline's guard.
    pub fn drain_lsp_folding_ranges(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut updates = Vec::new();
        while let Some(u) = lsp.drain_folding_ranges() {
            updates.push(u);
        }
        let mut changed = false;
        for u in updates {
            if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
                continue;
            }
            if u.ranges.is_empty() {
                continue;
            }
            if self.editor.path.as_deref() == Some(u.path.as_path()) {
                self.editor.set_lsp_folds(u.ranges.clone());
                changed = true;
            }
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(u.path.as_path()) {
                    group.set_lsp_folds(u.ranges.clone());
                    changed = true;
                }
            }
        }
        changed
    }

    /// Drain document-color batches (#254) into every editor showing the
    /// file — the inlay-hints fan-out, seq gate included. An empty batch
    /// clears the swatches (a stylesheet that lost its last color).
    pub fn drain_lsp_document_colors(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut updates = Vec::new();
        while let Some(u) = lsp.drain_document_colors() {
            updates.push(u);
        }
        let mut changed = false;
        for u in updates {
            if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
                continue;
            }
            if self.editor.path.as_deref() == Some(u.path.as_path()) {
                self.editor
                    .apply_document_colors(u.path.clone(), u.colors.clone());
                changed = true;
            }
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(u.path.as_path()) {
                    group.apply_document_colors(u.path.clone(), u.colors.clone());
                    changed = true;
                }
            }
        }
        changed
    }

    /// "Change Color Presentation" (#254): ask for the alternative
    /// spellings of the color value at the cursor and defer the picker on
    /// the reply.
    fn change_color_presentation(&mut self) {
        if !self.editor_is_text() {
            return;
        }
        let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
        let Some(item) = self.editor.color_at(row, col).cloned() else {
            self.status = String::from("No color value at the cursor");
            return;
        };
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let seq = self.editor.edit_seq;
        let Some(lsp) = self.lsp.as_mut() else {
            self.status = String::from("No language server for this file");
            return;
        };
        let id = lsp.request_color_presentations(
            path.clone(),
            item.raw,
            (item.line, item.character),
            (item.end_line, item.end_character),
        );
        self.color_presentations_request = Some((id, path, seq));
        self.status = String::from("Fetching color presentations…");
    }

    /// Open the presentation picker when the reply lands (#254); gated on
    /// id + path + edit_seq like every deferred caret request.
    pub fn drain_lsp_color_presentations(&mut self) -> bool {
        let mut results = Vec::new();
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(r) = lsp.drain_color_presentations() {
                results.push(r);
            }
        }
        let mut changed = false;
        for result in results {
            let Some((id, path, seq)) = self.color_presentations_request.clone() else {
                continue;
            };
            if result.request_id != id {
                continue;
            }
            self.color_presentations_request = None;
            if self.editor.path.as_deref() != Some(path.as_path()) || self.editor.edit_seq != seq {
                continue;
            }
            changed = true;
            if result.presentations.is_empty() {
                self.status = String::from("No color presentations offered here");
                continue;
            }
            let rows: Vec<crate::widgets::list_picker::ListRow> = result
                .presentations
                .iter()
                .enumerate()
                .map(|(i, (label, _))| crate::widgets::list_picker::ListRow {
                    id: i.to_string(),
                    label: label.clone(),
                })
                .collect();
            self.pending_color_presentations = result.presentations;
            self.pending_color_context = Some((path.clone(), seq));
            self.open_list_picker(
                crate::widgets::list_picker::ListPicker::new(
                    crate::widgets::list_picker::ListPurpose::ColorPresentation,
                    "Change Color Presentation",
                    rows,
                ),
                "No color presentations offered here",
            );
        }
        changed
    }

    /// Flatten the per-server diagnostics stored for `path` into one list for
    /// the editor. Servers are layered, not merged across (each owns its own
    /// findings), so this is a simple concatenation of every server's set.
    fn merged_diagnostics(&self, path: &Path) -> Vec<crate::lsp::manager::Diagnostic> {
        self.lsp_diagnostics
            .get(path)
            .map(|by_server| by_server.values().flatten().cloned().collect())
            .unwrap_or_default()
    }

    /// The producer id for the whole-project check (#256).
    ///
    /// `build_diag_files_by_pane` keys a producer's contribution so its next
    /// run replaces its previous one. Pane uids are allocated from 1 upward
    /// by an `AtomicU64`, so `u64::MAX` cannot collide with a real pane. The
    /// sweep needs its OWN id rather than borrowing one: sharing would make a
    /// pane's next command wipe the sweep's rows, and the sweep wipe the
    /// pane's.
    const PROJECT_CHECK_ID: u64 = u64::MAX;

    /// The first line with something to say, escapes stripped (#256).
    ///
    /// A checker's failure output is not a tidy single line: npx opens with
    /// a blank line and an ANSI-coloured banner, so both a leading-blank
    /// skip and the stripping are needed for the message to carry a reason
    /// rather than an escape sequence.
    fn first_meaningful_line(text: &str) -> Option<String> {
        text.lines()
            .map(|l| crate::remote_connect::strip_ansi(l.as_bytes()))
            .map(|l| l.trim().to_string())
            .find(|l| !l.is_empty())
    }

    /// Take a finished project check off the channel and report it (#256).
    ///
    /// Three outcomes, deliberately distinguished. A spawn failure names the
    /// error. A run that produced no rows AND exited non-zero is an
    /// INVOCATION failure, not a clean project: `tsc` prints global errors
    /// like `error TS5023: Unknown compiler option` with no `file(line,col)`
    /// prefix, so no matcher claims them and the row count is zero - exactly
    /// what a clean project looks like. Reporting "no problems" there tells
    /// the user their code is fine when the checker never checked it.
    /// Otherwise the count is this producer's own, not the panel's.
    fn drain_project_check(&mut self) -> bool {
        let Ok((cwd, done)) = self.project_check_rx.try_recv() else {
            return false;
        };
        self.project_check_running = false;
        match done {
            Err(e) => {
                // true, not false: the status changed, so the frame must be
                // redrawn or the message waits for an unrelated repaint.
                self.status = format!("Could not run the project checker: {e}");
                true
            }
            Ok(out) => {
                let text = String::from_utf8_lossy(&out.stdout).into_owned();
                self.ingest_project_check(Some(&cwd), &text);
                self.rebuild_problems();
                let n = self.project_check_count();
                if n == 0 && !out.status.success() {
                    // The first NON-BLANK line, from either stream. Which
                    // stream carries the reason is not predictable: npx
                    // reports a missing compiler on STDOUT (with an empty
                    // stderr and a leading blank line), while tsc's own
                    // global errors also go to stdout and a missing binary
                    // goes to stderr. Taking `.next()` showed the blank line
                    // and reported a failure with no reason at all.
                    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
                    let why = Self::first_meaningful_line(&stderr)
                        .or_else(|| Self::first_meaningful_line(&text))
                        .unwrap_or_else(|| String::from("no output"));
                    self.status = format!("The project checker failed: {why}");
                } else {
                    self.status = match n {
                        0 => String::from("Whole-project check: no problems"),
                        1 => String::from("Whole-project check: 1 problem"),
                        n => format!("Whole-project check: {n} problems"),
                    };
                }
                true
            }
        }
    }

    /// Queue a finished check on the REAL channel WITHOUT draining (#256).
    ///
    /// Test-only. The sibling helper drains immediately, which is right for
    /// testing the reporting logic but wrong for the same-tick race: the
    /// hint is applied by `sync_explorer_panels`, so the test must let that
    /// function do the draining.
    #[cfg(all(test, unix))]
    pub(crate) fn queue_project_check_result_for_test(
        &mut self,
        cwd: &Path,
        stdout: &str,
        stderr: &str,
        success: bool,
    ) {
        use std::os::unix::process::ExitStatusExt;
        let out = std::process::Output {
            status: std::process::ExitStatus::from_raw(if success { 0 } else { 256 }),
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        };
        self.project_check_running = true;
        let _ = self.project_check_tx.send((cwd.to_path_buf(), Ok(out)));
    }

    /// Whether the session's one-shot size hint has been spent (#256).
    /// Test-only reader; the field is private.
    #[cfg(all(test, unix))]
    pub(crate) fn project_check_hinted_for_test(&self) -> bool {
        self.project_check_hinted
    }

    /// Queue a size hint on the REAL channel (#256). Test-only.
    ///
    /// Does not drain: the point is to have it in flight when the result
    /// arrives, which is the race that erased it.
    #[cfg(all(test, unix))]
    pub(crate) fn send_project_hint_for_test(&mut self) {
        let _ = self.project_hint_tx.send(());
    }

    /// Push a finished check through the REAL channel and drain it (#256).
    ///
    /// Test-only, and deliberately not a shortcut: it sends down
    /// `project_check_tx` and calls `drain_project_check`, so the reporting
    /// logic under test is the shipped one. A helper that set the status
    /// itself would pass while the drain was broken.
    /// Unix-only: `ExitStatusExt::from_raw` has a different meaning on
    /// Windows, and an ungated spawning helper breaks that target's test
    /// build without failing anything here or in CI.
    #[cfg(all(test, unix))]
    pub(crate) fn finish_project_check_for_test(
        &mut self,
        cwd: &Path,
        stdout: &str,
        stderr: &str,
        success: bool,
    ) {
        use std::os::unix::process::ExitStatusExt;
        let out = std::process::Output {
            status: std::process::ExitStatus::from_raw(if success { 0 } else { 256 }),
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        };
        self.project_check_running = true;
        let _ = self.project_check_tx.send((cwd.to_path_buf(), Ok(out)));
        self.drain_project_check();
    }

    /// Scan a whole-project checker's output into PROBLEMS (#256).
    ///
    /// Routed through `apply_build_scan` rather than a parallel path, so the
    /// sweep inherits the matcher table (tsc's two output shapes are already
    /// handled), the relative-path resolution, and the replace-wholesale
    /// semantics a re-run needs. `cwd` is where the checker ran, which is
    /// what its relative paths are against; `None` means the workspace root.
    pub(crate) fn ingest_project_check(&mut self, cwd: Option<&Path>, output: &str) -> bool {
        let root = self.workspace_root().to_path_buf();
        let cwd = cwd.unwrap_or(&root).to_path_buf();
        // Count what THIS scan produced, before it is merged into a store
        // shared with every other producer.
        self.project_check_rows = self.matchers.scan_batch(output, "tsc").len();
        self.apply_build_scan(Self::PROJECT_CHECK_ID, Some(&cwd), "tsc", output)
    }

    /// How many files put a root out of the sweep's automatic reach (#256).
    ///
    /// VS Code's own workspace-diagnostics guidance draws the line around
    /// the size where a project-wide compile stops being a background cost
    /// and starts being the foreground one. The exact number matters less
    /// than having one: the setting overrides it either way.
    const PROJECT_CHECK_AUTO_MAX_FILES: usize = 100_000;

    /// Whether `root` holds more than `limit` files worth counting (#256).
    ///
    /// Stops at `limit + 1` rather than completing the walk. Counting a
    /// giant tree to decide not to walk a giant tree would cost exactly what
    /// the cap exists to avoid, and the question is a threshold one - the
    /// total is never used.
    ///
    /// Ignored and vendored directories do not count: `node_modules` alone
    /// puts most JS projects over any sensible cap, and disabling the sweep
    /// for JS projects would disable it for the projects it is FOR.
    pub(crate) fn workspace_exceeds(root: &Path, limit: usize) -> bool {
        let mut seen = 0usize;
        for entry in ignore::WalkBuilder::new(root)
            .git_ignore(true)
            .require_git(false)
            .hidden(false)
            .filter_entry(|e| {
                e.depth() == 0
                    || !e.file_type().is_some_and(|t| t.is_dir())
                    || !crate::widgets::file_finder::is_noise_dir(e.file_name())
            })
            .build()
        {
            let Ok(entry) = entry else { continue };
            if entry.file_type().is_some_and(|t| t.is_file()) {
                seen += 1;
                if seen > limit {
                    return true;
                }
            }
        }
        false
    }

    /// Whether the sweep may run WITHOUT the user asking, for `mode` (#256).
    ///
    /// `on` and `off` are answers, not hints: a cap that only ever declined
    /// would make `on` useless on the monorepos that most want it, and a cap
    /// that could not be turned off would surprise someone who knows their
    /// tree. `auto` asks the size question. Anything else reads as `auto`
    /// rather than as `on`, so a typo cannot start a compile on a 100k-file
    /// root - the failure the cap exists to prevent.
    pub(crate) fn project_check_auto_enabled(root: &Path, mode: &str, limit: usize) -> bool {
        match Self::project_scope_mode(mode) {
            "on" => true,
            "off" => false,
            _ => !Self::workspace_exceeds(root, limit),
        }
    }

    /// Normalise a `problems_project_scope` value (#256).
    ///
    /// Mirrors `ProblemScope::from_config`: a hand-edited config saying
    /// `"Off"` or `" off "` means off, and reading it as `auto` would give
    /// the user a size-dependent maybe when they asked for never. Anything
    /// unrecognised still becomes `auto`, so a typo cannot turn the sweep
    /// ON. Returns a `&'static str` so the cycle and the predicate agree by
    /// construction rather than by both remembering to normalise.
    pub(crate) fn project_scope_mode(raw: &str) -> &'static str {
        match raw.trim().to_ascii_lowercase().as_str() {
            "on" | "always" => "on",
            "off" | "never" => "off",
            _ => "auto",
        }
    }

    /// The whole-project check command for this workspace (#256).
    ///
    /// `tsc --noEmit` when a `tsconfig.json` sits at the root, which is the
    /// path VS Code users already take: vtsls exposes project-wide checking
    /// poorly over LSP, so the pragmatic route is the compiler itself. `None`
    /// when nothing is recognised - the command then says so rather than
    /// running a guess.
    ///
    /// The PROJECT's compiler first, `npx --no-install` second. Bare `npx
    /// tsc` on a project without TypeScript installed does not fail: it
    /// fetches `tsc` from the registry, which is an unrelated Unix
    /// terminal-control tool, and runs THAT against the user's source. The
    /// `--no-install` flag turns a missing compiler into an error, which is
    /// the honest outcome.
    fn project_check_command(root: &Path) -> Option<(std::ffi::OsString, Vec<&'static str>)> {
        if !root.join("tsconfig.json").is_file() {
            return None;
        }
        let local = root.join("node_modules").join(".bin").join("tsc");
        if local.is_file() {
            return Some((local.into_os_string(), vec!["--noEmit"]));
        }
        Some((
            std::ffi::OsString::from("npx"),
            vec!["--no-install", "tsc", "--noEmit"],
        ))
    }

    /// How many rows the last project check contributed (#256).
    ///
    /// NOT `problems.total_count()`: that is the panel's projection, which
    /// mixes in every language server's diagnostics and every pane's build
    /// output, and which the Open Files scope filters down - so under that
    /// scope a sweep whose findings are all in unopened files would report
    /// "no problems", defeating the feature. Count this producer's own
    /// contribution instead.
    ///
    /// Recorded at install time rather than summed from the store: a file's
    /// entry in `build_diagnostics` holds EVERY producer's items for that
    /// file, so summing it double-counts a file the sweep and a pane both
    /// report. Filtering on the item's `source` would not help either: a
    /// pane running tsc produces the same source string as this sweep.
    /// (The rows do carry an owner since #532, so an owner-filtered count
    /// would work - but this field is already exact and cheaper.)
    fn project_check_count(&self) -> usize {
        self.project_check_rows
    }

    /// Scan one finished command's output through the build matchers and
    /// install the results (#119). The pane's PREVIOUS contribution is
    /// replaced wholesale — a rebuild that fixed everything clears its old
    /// entries because the fresh scan is empty. Relative tool paths resolve
    /// against the command's cwd (falling back to the workspace root);
    /// resolution is lexical, no filesystem probe, so a path the tool
    /// printed oddly still gets a row even if navigation later misses.
    pub(crate) fn apply_build_scan(
        &mut self,
        pane: u64,
        cwd: Option<&Path>,
        cmd: &str,
        output: &str,
    ) -> bool {
        // A watch matcher already published this pane's batch mid-run: the
        // watcher's exit must not overwrite the last cycle with a rescan of
        // its whole history. One skip only — the pane's next command scans.
        if self.watch_published_panes.remove(&pane) {
            return false;
        }
        // A task-declared problemMatcher is exclusive for its pane
        // (VS Code's model); otherwise user matchers claiming the command
        // run alongside the built-in table.
        let diags = match self.task_matcher_by_pane.get(&pane) {
            Some(m) => m.scan_batch(output),
            None => self.matchers.scan_batch(output, cmd),
        };
        self.install_build_diags(pane, cwd, diags)
    }

    /// Install `diags` as pane `pane`'s PROBLEMS contribution (#119/#252).
    fn install_build_diags(
        &mut self,
        pane: u64,
        cwd: Option<&Path>,
        diags: Vec<crate::build_matchers::BuildDiag>,
    ) -> bool {
        let had_old = self
            .build_diag_files_by_pane
            .get(&pane)
            .is_some_and(|v| !v.is_empty());
        if diags.is_empty() && !had_old {
            return false;
        }
        if let Some(files) = self.build_diag_files_by_pane.remove(&pane) {
            for f in files {
                // Filter, never remove: another producer may hold rows on
                // this same file, and dropping the entry took them too
                // (#532). The entry goes only once nothing is left in it.
                if let Some(rows) = self.build_diagnostics.get_mut(&f) {
                    rows.retain(|(owner, _)| *owner != pane);
                    if rows.is_empty() {
                        self.build_diagnostics.remove(&f);
                    }
                }
            }
        }
        let base = cwd.unwrap_or(self.workspace_root()).to_path_buf();
        let mut touched = Vec::new();
        for d in diags {
            let path = {
                let p = Path::new(&d.file);
                if p.is_absolute() {
                    p.to_path_buf()
                } else {
                    base.join(p)
                }
            };
            let entry = self.build_diagnostics.entry(path.clone()).or_default();
            // Unconditionally: recording only when the entry was empty meant
            // the SECOND producer to reach a file never listed it, so its
            // next run had nothing to clear (#532). `touched` is this
            // producer's own file list, not a set of first-touchers.
            if !touched.contains(&path) {
                touched.push(path);
            }
            entry.push((
                pane,
                crate::widgets::problems::ProblemItem {
                    line: d.line,
                    col: d.col,
                    // Build tools report characters (rustc counts code
                    // points), not the UTF-16 units an LSP position carries.
                    col_utf16: false,
                    severity: d.severity,
                    message: d.message,
                    source: d.source.to_string(),
                },
            ));
        }
        self.build_diag_files_by_pane.insert(pane, touched);
        self.rebuild_problems();
        true
    }

    /// Re-read matchers.json (user + workspace) after a save, surfacing
    /// compile warnings once in OUTPUT · Matchers (#252).
    fn reload_matchers(&mut self) {
        // Same isolation guard as App::new: the developer's real
        // matchers.json must never steer app tests — a test that saves a
        // path equal to the real matchers_path() would otherwise reload
        // the runner's actual config here.
        let set = if cfg!(test) {
            crate::problem_matchers::MatcherSet::default()
        } else {
            crate::problem_matchers::MatcherSet::load(
                &crate::problem_matchers::matchers_path(),
                Some(&crate::problem_matchers::workspace_matchers_path(
                    self.workspace_root(),
                )),
            )
        };
        for w in &set.warnings {
            crate::output::push("Matchers", crate::output::OutputLevel::Warn, w);
        }
        let warned = set.warnings.len();
        self.watch_set = std::sync::Arc::new(set.watch_set());
        self.matchers = std::sync::Arc::new(set);
        self.status = if warned == 0 {
            format!(
                "Problem matchers reloaded ({} active)",
                self.matchers.matchers.len()
            )
        } else {
            format!(
                "Problem matchers reloaded ({} active, {warned} warning{} — see OUTPUT · Matchers)",
                self.matchers.matchers.len(),
                if warned == 1 { "" } else { "s" }
            )
        };
    }

    fn clear_build_diagnostics(&mut self) {
        let n: usize = self.build_diagnostics.values().map(Vec::len).sum();
        self.build_diagnostics.clear();
        self.build_diag_files_by_pane.clear();
        self.rebuild_problems();
        self.status = format!(
            "Cleared {n} build diagnostic{}",
            if n == 1 { "" } else { "s" }
        );
    }

    /// Every open buffer's path, across the active leaf and every inactive
    /// one. `App::editor` is the hoisted active leaf and `inactive_leaf_tabs`
    /// walks the rest, so together they cover each leaf exactly once.
    fn open_buffer_paths(&self) -> std::collections::BTreeSet<PathBuf> {
        self.editor
            .editors
            .iter()
            .chain(
                self.editor_layout
                    .inactive_leaf_tabs()
                    .into_iter()
                    .flat_map(|g| g.editors.iter()),
            )
            .filter_map(|e| e.path.clone())
            .collect()
    }

    /// Rebuild the PROBLEMS panel's grouped projection from the per-file
    /// diagnostics store. Returns whether the projection changed (so the caller
    /// can fold it into its redraw decision). Files are grouped, ordered by
    /// path; each group's diagnostics are ordered by position.
    fn rebuild_problems(&mut self) -> bool {
        use crate::widgets::problems::{ProblemGroup, ProblemItem};
        let mut paths: Vec<&PathBuf> = self
            .lsp_diagnostics
            .keys()
            .chain(self.build_diagnostics.keys())
            .collect();
        paths.sort();
        paths.dedup();
        // Scope (#256): Open Files keeps only paths with a live buffer, so the
        // panel and the status-bar badge (which counts the same list) agree.
        let scoped = self.problems.scope == crate::widgets::problems::ProblemScope::OpenFiles;
        let open = if scoped {
            self.open_buffer_paths()
        } else {
            std::collections::BTreeSet::new()
        };
        let scoped_out = |p: &PathBuf| scoped && !open.contains(p);
        let mut groups = Vec::new();
        for path in paths {
            if scoped_out(path) {
                continue;
            }
            let mut items: Vec<ProblemItem> = Vec::new();
            if let Some(by_server) = self.lsp_diagnostics.get(path) {
                for (server, diags) in by_server {
                    for d in diags {
                        items.push(ProblemItem {
                            line: d.start_line,
                            col: d.start_char,
                            col_utf16: true,
                            severity: d.severity,
                            message: d.message.clone(),
                            source: server.clone(),
                        });
                    }
                }
            }
            if let Some(build) = self.build_diagnostics.get(path) {
                items.extend(build.iter().map(|(_, item)| item.clone()));
            }
            if items.is_empty() {
                continue;
            }
            items.sort_by_key(|i| (i.line, i.col));
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            let rel_dir = path
                .strip_prefix(self.workspace_root())
                .unwrap_or(path)
                .parent()
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or_default();
            groups.push(ProblemGroup {
                path: path.clone(),
                name,
                rel_dir,
                items,
            });
        }
        self.problems.set_groups(groups)
    }

    /// Drain server-pushed diagnostics into the per-file store, then refresh
    /// the underline overlay on whichever editor group shows an affected (or
    /// just-switched-to) file. Returns true when an overlay changed and the
    /// next frame should redraw.
    pub fn drain_lsp_diagnostics(&mut self) -> bool {
        // Collect first so the immutable borrow of `lsp` ends before the store
        // and the editors are mutated below.
        let mut updates = Vec::new();
        if let Some(lsp) = self.lsp.as_ref() {
            while let Some(u) = lsp.drain_diagnostics() {
                updates.push(u);
            }
        }
        let mut touched: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
        for u in updates {
            touched.insert(u.path.clone());
            let by_server = self.lsp_diagnostics.entry(u.path).or_default();
            // An empty batch is the server saying "all clear" for its findings.
            if u.diagnostics.is_empty() {
                by_server.remove(&u.server);
            } else {
                by_server.insert(u.server, u.diagnostics);
            }
        }
        let mut changed = false;
        // The active editor re-decodes when its file was touched this tick OR
        // when it now shows a file whose stored diagnostics it hasn't applied
        // yet (a tab switch: diagnostics are pushed, never re-requested).
        if let Some(path) = self.editor.path.clone() {
            let stale = self.editor.diagnostics_path() != Some(path.as_path());
            if stale || touched.contains(&path) {
                let merged = self.merged_diagnostics(&path);
                self.editor.apply_diagnostics(path, merged);
                changed = true;
            }
        }
        // Same for every inactive group, computed without overlapping borrows.
        let mut split_targets: Vec<PathBuf> = self
            .editor_layout
            .inactive_groups_mut()
            .into_iter()
            .filter_map(|s| {
                let p = s.path.clone()?;
                let stale = s.diagnostics_path() != Some(p.as_path());
                (stale || touched.contains(&p)).then_some(p)
            })
            .collect();
        split_targets.dedup();
        for path in split_targets {
            let merged = self.merged_diagnostics(&path);
            for group in self.editor_layout.inactive_groups_mut() {
                if group.path.as_deref() == Some(path.as_path()) {
                    group.apply_diagnostics(path.clone(), merged.clone());
                    changed = true;
                }
            }
        }
        // The PROBLEMS panel aggregates every file's diagnostics, including
        // files no editor group has open, so rebuild it whenever any server
        // republished this tick (not only when an editor overlay changed).
        if !touched.is_empty() {
            changed |= self.rebuild_problems();
        }
        changed
    }

    /// Drain server work-done progress updates into the per-server map the
    /// status bar reads. Returns true when anything changed so the main loop
    /// repaints the bar. A `Some(message)` upserts the server's status; a
    /// `None` (the server's `End`) clears it.
    pub fn drain_lsp_progress(&mut self) -> bool {
        let mut updates = Vec::new();
        if let Some(lsp) = self.lsp.as_ref() {
            while let Some(u) = lsp.drain_progress() {
                updates.push(u);
            }
        }
        let mut changed = false;
        for u in updates {
            match u.message {
                Some(message) => {
                    self.lsp_progress.insert(u.server, message);
                    changed = true;
                }
                None => {
                    if self.lsp_progress.remove(&u.server).is_some() {
                        changed = true;
                    }
                }
            }
        }
        changed
    }

    /// The active LSP progress line for the status bar, if any server is busy
    /// (e.g. `rust-analyzer: Indexing 112/340 33%`). Joins multiple busy
    /// servers with `  ·  ` so a Rust + Python workspace shows both.
    fn lsp_progress_status(&self) -> Option<String> {
        if self.lsp_progress.is_empty() {
            return None;
        }
        let mut entries: Vec<String> = self
            .lsp_progress
            .iter()
            .map(|(server, msg)| format!("{server}: {msg}"))
            .collect();
        entries.sort();
        Some(entries.join("  ·  "))
    }

    /// Re-pull semantic tokens when a server asked us to via
    /// `workspace/semanticTokens/refresh`. rust-analyzer answers the first
    /// request from partial syntax analysis, then sends refresh once its
    /// cargo/crate-graph analysis resolves the richer type-aware tokens; this
    /// is how that upgraded set reaches the editor without an edit. Only the
    /// visible editor(s) are re-requested (matching VS Code), and only for
    /// files the manager has open. The fresh full batch replaces the partial
    /// one via the editor's `is_full` guard.
    pub fn refresh_semantic_tokens_if_requested(&self) {
        let Some(lsp) = self.lsp.as_ref() else {
            return;
        };
        if !lsp.take_semantic_refresh() {
            return;
        }
        let mut paths: Vec<PathBuf> = Vec::new();
        if let Some(p) = self.editor.path.clone() {
            paths.push(p);
        }
        for group in self.editor_layout.inactive_groups() {
            if let Some(p) = group.path.clone() {
                paths.push(p);
            }
        }
        for p in paths {
            // Re-request at the seq the doc was last synced at, so a reply
            // arriving after an external reload is recognised as stale.
            if let Some(&seq) = self.lsp_last_seen.get(&p) {
                lsp.request_semantic_tokens(p, seq);
            }
        }
    }

    /// Re-request inlay hints when a server asked us to via
    /// `workspace/inlayHint/refresh` (rust-analyzer sends it after a config
    /// reload or when cross-file analysis changes the hints without an edit).
    /// Mirrors [`refresh_semantic_tokens_if_requested`].
    pub fn refresh_inlay_hints_if_requested(&mut self) {
        let Some(lsp) = self.lsp.as_ref() else {
            return;
        };
        if !lsp.take_inlay_refresh() {
            return;
        }
        if self.inlay_hints_enabled {
            self.request_inlay_hints_for_open_editors();
        }
    }

    /// Re-pull whole-project diagnostics when a server asked us to via
    /// `workspace/diagnostic/refresh` (#533).
    ///
    /// Mirrors [`refresh_semantic_tokens_if_requested`], with one difference:
    /// there is nothing to aim it at. A pull covers the whole workspace, not
    /// the visible editors, which is the point - it is what puts problems from
    /// files no editor has open into PROBLEMS. The manager filters to the
    /// servers advertising `workspaceDiagnostics`, so a workspace whose
    /// servers all PUSH never sends a request.
    pub fn refresh_workspace_diagnostics_if_requested(&self) {
        let Some(lsp) = self.lsp.as_ref() else {
            return;
        };
        if !lsp.take_diagnostic_refresh() {
            return;
        }
        lsp.request_workspace_diagnostics();
    }

    /// Fire an inlay-hint request for every visible editor's file at its
    /// current edit seq. Shared by the server-driven refresh and the palette
    /// toggle's re-enable path.
    fn request_inlay_hints_for_open_editors(&mut self) {
        let Some(lsp) = self.lsp.as_ref() else {
            return;
        };
        let mut targets: Vec<(PathBuf, u32)> = Vec::new();
        if let Some(p) = self.editor.path.clone() {
            targets.push((p, self.editor.line_count() as u32 + 1));
        }
        for group in self.editor_layout.inactive_groups() {
            if let Some(p) = group.path.clone() {
                targets.push((p, group.line_count() as u32 + 1));
            }
        }
        for (p, line_count) in targets {
            if let Some(&seq) = self.lsp_last_seen.get(&p) {
                lsp.request_inlay_hints(p, line_count, seq);
            }
        }
    }

    /// Editor: Toggle Inlay Hints — flips the hint display live and persists
    /// the choice. Off clears every editor's hints; on re-requests them for
    /// the visible files.
    fn toggle_inlay_hints(&mut self) {
        self.inlay_hints_enabled = !self.inlay_hints_enabled;
        if self.inlay_hints_enabled {
            self.request_inlay_hints_for_open_editors();
            self.status = String::from("Inlay Hints: on");
        } else {
            self.editor.clear_inlay_hints();
            for group in self.editor_layout.inactive_groups_mut() {
                group.clear_inlay_hints();
            }
            self.status = String::from("Inlay Hints: off");
        }
        if !cfg!(test) {
            let _ = crate::prefs::save_inlay_hints(self.inlay_hints_enabled);
        }
    }

    fn go_to_definition(&mut self, path: PathBuf, line: u32, col: u32) {
        if let Some(from) = self.editor.path.clone() {
            self.nav.record(NavLoc {
                path: from,
                row: self.editor.cursor_row,
                col: self.editor.cursor_col,
            });
        }
        // `col` is the server's UTF-16 column, not a character column.
        match self.open_at_utf16(&path, line, col) {
            Ok(()) => {
                self.status = format!("Jumped to {} line {}", self.status_path(&path), line + 1)
            }
            Err(e) => self.status = format!("Go to definition failed: {e}"),
        }
    }

    /// The breadcrumb segments for the active editor: the workspace-relative
    /// path folders and file name, then the enclosing symbol chain at the
    /// caret. Empty for the welcome screen, preview tabs, and buffers with no
    /// path (so the bar hides). Symbol crumbs carry a jump target; path crumbs
    /// are informational.
    fn build_breadcrumbs(&self) -> Vec<crate::widgets::editor::Crumb> {
        use crate::widgets::editor::Crumb;
        let Some(path) = self.editor.path.as_deref() else {
            return Vec::new();
        };
        if self.editor.has_non_text_view() {
            return Vec::new();
        }
        let mut crumbs = Vec::new();
        // Strip against the OWNING root (#147): a secondary-root file
        // crumbs from its own root (folder-relative, like status_path),
        // never the primary — which yielded the full absolute chain.
        let rel = self
            .roots
            .owning_root(path)
            .and_then(|r| path.strip_prefix(r).ok())
            .unwrap_or(path);
        for comp in rel.components() {
            if let std::path::Component::Normal(os) = comp {
                crumbs.push(Crumb {
                    label: os.to_string_lossy().into_owned(),
                    target: None,
                });
            }
        }
        // Symbol scope chain, only when the outline belongs to this file so a
        // stale outline from the previous tab never leaks into the bar.
        if self.outline.path() == Some(path) {
            let line = self.editor.cursor_row as u32;
            let symbols = self.outline.symbols();
            for i in breadcrumb_symbol_chain(symbols, line) {
                let s = &symbols[i];
                crumbs.push(Crumb {
                    label: s.name.clone(),
                    target: Some((s.line, s.character)),
                });
            }
        }
        crumbs
    }

    /// The scope-header lines to pin as sticky scroll: the enclosing symbols of
    /// the top visible line whose header has scrolled above the viewport,
    /// outermost first, capped. Empty when the feature does not apply (welcome
    /// screen, preview tab, no outline, or nothing scrolled off).
    fn build_sticky_lines(&self) -> Vec<u32> {
        let Some(path) = self.editor.path.as_deref() else {
            return Vec::new();
        };
        if self.editor.has_non_text_view() {
            return Vec::new();
        }
        if self.outline.path() != Some(path) {
            return Vec::new();
        }
        let top = self.editor.scroll as u32;
        let symbols = self.outline.symbols();
        breadcrumb_symbol_chain(symbols, top)
            .into_iter()
            .map(|i| symbols[i].range_start_line)
            .filter(|&l| l < top)
            .take(STICKY_SCROLL_MAX)
            .collect()
    }

    /// Keep the OUTLINE in sync with the active editor: request fresh symbols
    /// when the file or its edit-seq changed (once per change), settle a
    /// loaded-empty outline for files no language server tracks, and advance
    /// follow-cursor. Returns whether the highlight moved (for redraw).
    pub fn sync_outline(&mut self) -> bool {
        let Some(path) = self.editor.path.clone() else {
            // Back on the welcome screen: drop any stale outline.
            if self.outline.path.is_some() {
                self.outline.clear();
            }
            self.outline_synced = None;
            return false;
        };
        // `lsp_last_seen` carries the edit seq the manager last saw for an open
        // doc; absent means no language server tracks this file.
        let seq = self.lsp_last_seen.get(&path).copied();
        let key = (path.clone(), seq);
        if self.outline_synced.as_ref() != Some(&key) {
            self.outline_synced = Some(key);
            // Tree-sitter paints the outline instantly from the buffer's own
            // syntax tree, before any language server replies. The LSP request
            // below refines it with richer kinds/detail when (and if) it lands.
            let syntax = self.compute_syntax_outline(&path);
            let lsp_pending = seq.is_some();
            self.outline
                .set_syntax_symbols(path.clone(), syntax, lsp_pending);
            if lsp_pending && let (Some(lsp), Some(seq)) = (self.lsp.as_ref(), seq) {
                lsp.request_document_symbols(path, seq);
            }
        }
        // Follow-cursor every tick; cheap (O(symbols)) and only repaints when
        // the enclosing symbol actually changes.
        self.outline.follow_caret(self.editor.cursor_row as u32)
    }

    /// Keep the Explorer's non-OUTLINE stacked sub-views current: re-project the
    /// OPEN EDITORS list from the tabs, kick off the TIMELINE / DEPENDENCIES
    /// background fetches when their input (active file / workspace root) changed,
    /// and drain any worker replies. Returns whether anything changed, so the
    /// main loop only repaints when it must. All the heavy work (`git log`,
    /// `cargo metadata`) runs on spawned threads — never on this tick.
    fn sync_explorer_panels(&mut self) -> bool {
        let mut changed = false;

        // --- OPEN EDITORS: a pure projection of the focused group's tabs. ---
        let active = self.editor.active_index();
        // Same disambiguated titles as the tab strip (#167), so the two
        // views never name one file two ways.
        let labels = self.editor.tab_display_labels();
        let items: Vec<OpenEditorItem> = self
            .editor
            .iter_tabs()
            .enumerate()
            .filter_map(|(i, ed)| {
                ed.path.as_ref().map(|p| OpenEditorItem {
                    path: p.clone(),
                    name: labels
                        .get(i)
                        .cloned()
                        .unwrap_or_else(|| p.display().to_string()),
                    dirty: ed.dirty,
                    active: i == active,
                })
            })
            .collect();
        changed |= self.open_editors.set_items(items);

        // --- TIMELINE: git history of the active file, fetched off-thread. ---
        if self.explorer_views.is_visible(ExplorerView::Timeline) {
            match self.editor.path.clone() {
                Some(path) => {
                    if self.timeline_fetched.as_ref() != Some(&path) {
                        self.timeline_fetched = Some(path.clone());
                        self.timeline.begin_loading(path.clone());
                        changed = true;
                        let timeline_root = self
                            .roots
                            .owning_root(&path)
                            .unwrap_or_else(|| self.roots.primary())
                            .to_path_buf();
                        let rel = path
                            .strip_prefix(&timeline_root)
                            .ok()
                            .map(|r| r.to_string_lossy().into_owned());
                        let root = timeline_root;
                        let tx = self.timeline_tx.clone();
                        let history_root = self.history_root.clone();
                        let abs = path.clone();
                        let now = now_millis();
                        std::thread::spawn(move || {
                            // Merge git commits with local snapshots so the
                            // TIMELINE shows both sources, like VS Code. Git
                            // history only exists inside the workspace, but
                            // snapshots are path-keyed and repo-free, so a
                            // file outside the root still lists its versions.
                            let commits = rel
                                .map(|rel| crate::git::file_history(&root, &rel, 50))
                                .unwrap_or_default();
                            let snaps = crate::history::entries_in(&history_root, &abs);
                            let entries = crate::history::merged_timeline(commits, &snaps, now);
                            let _ = tx.send((path, entries));
                        });
                    }
                }
                None => {
                    if self.timeline_fetched.is_some() {
                        self.timeline_fetched = None;
                        self.timeline.clear();
                        changed = true;
                    }
                }
            }
        }
        // A background test-source lookup landed: jump or say it missed. A
        // reply from before an Explorer re-root names the old root; drop it.
        while let Ok((root, name, hit)) = self.test_jump_rx.try_recv() {
            if root != self.workspace_root() {
                continue;
            }
            match hit {
                Some((path, line)) => self.go_to_definition(path, line, 0),
                None => self.status = format!("No source found for test {name}"),
            }
            changed = true;
        }
        // A history snapshot finished writing: refetch the TIMELINE so the
        // new version shows (resetting the marker before the write landed
        // would list the store without it).
        while let Ok(path) = self.history_done_rx.try_recv() {
            if self.editor.path.as_deref() == Some(path.as_path()) {
                self.timeline_fetched = None;
                changed = true;
            }
        }
        // The workspace is too large for the sweep to start on its own.
        // Held rather than written: the result below sets `status`
        // unconditionally and nothing paints between the two, so writing it
        // here DESTROYED the hint whenever the checker finished inside one
        // tick - and it is a one-shot, so it never came back. The
        // fast-failure path (over-cap root, no compiler installed) is
        // exactly where that happened.
        let hinted_now = self.project_hint_rx.try_recv().is_ok();
        if hinted_now {
            // Here, not at the spawn: only a hint that was actually WARRANTED
            // spends the one-shot.
            self.project_check_hinted = true;
        }
        // A whole-project check finished: its rows and its verdict land
        // together, so the status cannot describe a different run's result.
        if self.drain_project_check() {
            changed = true;
        }
        if hinted_now {
            // Appended, so the outcome the user asked for still leads.
            self.status.push_str(
                " - too large for the whole-project check to run on its own; \
                 set it to always in Problems: Whole-Project Check Auto-Run",
            );
            changed = true;
        }
        // Drain any TIMELINE replies; ignore one for a since-closed file.
        while let Ok((path, entries)) = self.timeline_rx.try_recv() {
            if self.editor.path.as_deref() == Some(path.as_path()) {
                self.timeline.set_history(path, entries);
                changed = true;
            }
        }
        // Drain any COMMITS graph replies; ignore one for a since-left root.
        while let Ok((root, revspec, rows)) = self.graph_rx.try_recv() {
            self.graph_fetch_inflight = false;
            if root == self.active_scm_root && revspec == self.graph_revspec {
                self.commit_graph.set_rows(rows);
                changed = true;
            }
            // A trigger arrived while this reply was in flight: what it
            // asked for (new root, newer HEAD) is not what just landed.
            if self.graph_refetch_queued {
                self.graph_refetch_queued = false;
                self.refresh_commit_graph();
            }
        }

        // --- DEPENDENCIES: detect the workspace's package ecosystems from its
        // manifest files (cheap, once per root), set the language-aware header,
        // then resolve the packages off-thread. The section is gated on
        // detection: a root with no recognised manifest detects nothing, so it
        // is hidden and dropped from the ⋯ menu (the rule every reference editor
        // follows). The fetch only fires when the section is actually shown. ---
        let root = self.tree.root.clone();
        if self.deps_fetched.as_ref() != Some(&root) {
            self.deps_fetched = Some(root.clone());
            self.dep_ecosystems = crate::widgets::dependencies::detect_ecosystems(&root);
            self.dependencies
                .set_header(crate::widgets::dependencies::header_label(
                    &self.dep_ecosystems,
                ));
            changed = true;
            if !self.dep_ecosystems.is_empty()
                && self.explorer_views.is_visible(ExplorerView::Dependencies)
            {
                let tx = self.deps_tx.clone();
                std::thread::spawn(move || {
                    let deps = crate::widgets::dependencies::fetch_dependencies(&root);
                    let _ = tx.send(deps);
                });
            }
        }
        while let Ok(deps) = self.deps_rx.try_recv() {
            self.dependencies.set_deps(deps);
            changed = true;
        }

        changed
    }

    /// Activate the editor tab for `path` (clicked in OPEN EDITORS). The path is
    /// already open by definition, so this selects its tab; should it have been
    /// closed between the projection and the click, it re-opens it.
    fn activate_open_editor(&mut self, path: PathBuf) {
        if let Some(idx) = self.editor.find_tab_with_path(&path) {
            self.editor.select(idx);
        } else if self.editor.open(&path).is_err() {
            self.status = format!("Could not open {}", path.display());
            return;
        }
        self.focus_pane(Pane::Editor);
        self.sync_open_file_poll_mtime();
    }

    /// Open the diff a TIMELINE commit introduced for `path` (`git show <hash>
    /// -- <path>`) in a read-only side-by-side editor tab.
    fn open_timeline_diff(&mut self, path: PathBuf, hash: String) {
        // Disarm first: every early exit below must leave "Restore Snapshot"
        // pointing at nothing, never at whatever snapshot was viewed before.
        self.history_restore = None;
        let rel = match path.strip_prefix(&self.tree.root) {
            Ok(r) => r.to_string_lossy().into_owned(),
            Err(_) => path.display().to_string(),
        };
        // A local-history row: diff the snapshot against the working file and
        // remember it so "Restore Snapshot" can write it back.
        if let Some(millis) = crate::history::snapshot_millis(&hash) {
            let Some(snap_file) =
                crate::history::snapshot_file_in(&self.history_root, &path, millis)
            else {
                self.status = String::from("Snapshot no longer available");
                return;
            };
            let Ok(content) = std::fs::read(&snap_file) else {
                self.status = String::from("Could not read snapshot");
                return;
            };
            // Snapshots hold the file's raw bytes; decode like `Editor::open`
            // so a UTF-16 file's history diffs as text, not mojibake.
            let enc = encoding_rs::Encoding::for_bom(&content)
                .map(|(e, _)| e)
                .unwrap_or(encoding_rs::UTF_8);
            let text = enc.decode(&content).0.into_owned();
            let label = std::path::PathBuf::from(format!("{rel} (local snapshot)"));
            if let Err(e) = self
                .editor
                .open_head_diff_with_text(label, &text, &path, false)
            {
                self.status = format!("Could not open snapshot diff: {e}");
                return;
            }
            self.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft { left_text: text });
            self.history_restore = Some((path, millis, content));
            self.focus_pane(Pane::Editor);
            self.status = format!("Showing {rel} at a local snapshot");
            return;
        }
        // A git commit row: no snapshot to restore.
        let timeline_root = self
            .editor
            .path
            .as_deref()
            .and_then(|p| self.roots.owning_root(p))
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf();
        match crate::git::show_commit_file_diff(&timeline_root, &hash, &rel) {
            Ok(raw) => {
                let label = std::path::PathBuf::from(format!("{rel} @ {hash}"));
                if let Err(e) = self.editor.open_git_diff_side_by_side(&label, &raw) {
                    self.status = format!("Could not open diff: {e}");
                    return;
                }
                self.focus_pane(Pane::Editor);
                self.status = format!("Showing {rel} at {hash}");
            }
            Err(e) => {
                self.status = format!("git show failed: {e}");
            }
        }
    }

    /// Restore the local snapshot currently shown in a TIMELINE diff: write its
    /// contents back to the file and reload the buffer. Reachable from the
    /// Command Palette once a snapshot diff is open (which records the target).
    fn restore_history_snapshot(&mut self) {
        let Some((file, millis, content)) = self.history_restore.clone() else {
            self.status = String::from("Open a local snapshot from the TIMELINE first");
            return;
        };
        if let Err(e) = std::fs::write(&file, &content) {
            self.status = format!("Restore failed: {e}");
            return;
        }
        // The snapshot's seats describe exactly the bytes just written (#349),
        // so they come along: onto the buffer, and onto the snapshot this
        // restore records below. No open tab's map can serve instead: a
        // reverted tab has just had its map cleared, and an unreverted one
        // still describes the text the restore replaced. A snapshot with no
        // sidecar restores every line unknown, which is what it knows.
        let seats =
            crate::history::seats_for(&self.history_root, &file, millis).unwrap_or_default();
        // If that file is the active tab (the snapshot diff opened it), reload
        // so the editor shows the restored contents and the disk stamp resyncs.
        // `holds_exactly` re-checks rather than assuming the reload landed the
        // restored bytes: another process can rewrite the file between the
        // write above and the read inside the revert.
        if self.editor.path.as_deref() == Some(file.as_path())
            && self.editor.revert_to_disk().is_ok()
            && self.editor.holds_exactly(&content)
        {
            let mut onto_buffer = seats.clone();
            onto_buffer.truncate(self.editor.lines.len());
            self.editor.provenance = onto_buffer;
        }
        // The restore is itself a new version worth keeping.
        self.record_history_snapshot(&file, seats);
        self.status = format!("Restored {}", self.status_path(&file));
    }

    /// Apply a `documentSymbol` reply to the OUTLINE panel, but only when its
    /// `path` is still the active editor file — a reply for a file the user
    /// navigated away from is dropped. Refreshes follow-cursor on success.
    /// Returns whether the outline changed (for redraw).
    fn apply_outline_symbols(
        &mut self,
        path: std::path::PathBuf,
        seq: u64,
        symbols: Vec<crate::lsp::manager::OutlineSymbol>,
    ) -> bool {
        if self.editor.path.as_ref() != Some(&path) {
            return false;
        }
        // Drop a reply answering an older buffer than the newest request: its
        // ranges are shifted by the edits made since, the caret falls outside
        // them, and the breadcrumb's symbol crumb flickers off and on with
        // every keystroke (visible against a slow remote rust-analyzer while
        // tree-sitter and the late reply take turns owning the outline). Only
        // enforced when a request seq is tracked for this file; an untracked
        // file has no newer request to be stale against.
        if let Some((p, Some(newest))) = self.outline_synced.as_ref()
            && *p == path
            && seq != *newest
        {
            return false;
        }
        // An empty reply (server lacks `documentSymbol`, or answered before it
        // finished indexing) must not blank an outline tree-sitter already
        // filled. Keep the syntactic symbols rather than flashing "No symbols".
        if symbols.is_empty() && !self.outline.is_empty() {
            return false;
        }
        self.outline.set_symbols(path, symbols);
        self.outline.follow_caret(self.editor.cursor_row as u32);
        true
    }

    /// Compute the active editor's outline directly from its syntax tree, so
    /// the OUTLINE panel can paint before a (possibly cold) language server
    /// answers `documentSymbol`. Empty for files whose language has no outline
    /// query; those fall back to the LSP reply.
    fn compute_syntax_outline(
        &self,
        path: &std::path::Path,
    ) -> Vec<crate::lsp::manager::OutlineSymbol> {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        let Some(kind) = crate::highlight::lang_for_extension(ext) else {
            return Vec::new();
        };
        let text = self.editor.lines.join("\n");
        crate::outline_syntax::symbols_for(kind, text.as_bytes())
    }

    /// Drain pending `documentSymbol` replies and offer every one to
    /// `apply_outline_symbols`, which is the sole judge of what applies.
    ///
    /// Deliberately no pre-selection. The drain used to collapse a tick's
    /// replies to whichever ARRIVED last and discard the rest, which lost the
    /// active file's reply whenever a slow one for the file just left landed
    /// after it — the guard then rejected the survivor on path, and
    /// `sync_outline` never re-requests because its `(path, seq)` key has not
    /// changed. Picking the highest seq instead would be just as wrong: `seq`
    /// is a per-`Editor` counter that RESTARTS at zero when a file lands in a
    /// fresh editor group (a split, or close-and-reopen), so the outstanding
    /// request can carry a lower number than a reply still in flight from the
    /// old group. Offering all of them keeps the decision in the one place
    /// that knows which request is outstanding.
    pub fn drain_lsp_document_symbols(&mut self) -> bool {
        let mut replies = Vec::new();
        if let Some(lsp) = self.lsp.as_ref() {
            while let Some(r) = lsp.drain_document_symbols() {
                replies.push((r.path, r.seq, r.symbols));
            }
        }
        let mut applied = false;
        for (path, seq, symbols) in replies {
            applied |= self.apply_outline_symbols(path, seq, symbols);
        }
        applied
    }

    pub fn drain_lsp_definition(&mut self) -> bool {
        let mut target = None;
        let mut peek = None;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            let mut peek_replied = false;
            while let Some(result) = lsp.drain_definition() {
                if Some(result.request_id) == self.peek_definition_request_id {
                    peek_replied = true;
                    peek = result.target;
                    continue;
                }
                if Some(result.request_id) != self.definition_request_id {
                    continue;
                }
                target = result.target;
            }
            if peek_replied && peek.is_none() {
                // The reply arrived empty: without this the "Peeking
                // definition" status hung forever with no popup.
                self.peek_definition_request_id = None;
                self.status = String::from("No definition found");
            }
        }
        let mut changed = false;
        if let Some((path, line, col)) = peek {
            self.peek_definition_request_id = None;
            self.open_peek_popup(path, line, col);
            changed = true;
        }
        if let Some((path, line, col)) = target {
            self.go_to_definition(path, line, col);
            changed = true;
        }
        changed
    }

    /// Build and show the Peek Definition popup: a `path:line` header and a
    /// numbered excerpt of the target region with the definition line marked.
    /// The open buffer supplies the text when the target file is already open
    /// (unsaved edits visible); disk otherwise.
    fn open_peek_popup(&mut self, path: PathBuf, line: u32, col: u32) {
        // Any open buffer wins over disk — the ACTIVE group's tabs plus
        // every inactive split leaf's — so unsaved edits show wherever the
        // target file happens to be open.
        let open_buffer = self
            .editor
            .editors
            .iter()
            .chain(
                self.editor_layout
                    .inactive_leaf_tabs()
                    .into_iter()
                    .flat_map(|tabs| tabs.editors.iter()),
            )
            .find(|e| e.path.as_deref() == Some(path.as_path()))
            .map(|e| e.lines.clone());
        let lines: Vec<String> = match open_buffer {
            Some(lines) => lines,
            None => match std::fs::read_to_string(&path) {
                Ok(text) => text.lines().map(|s| s.to_string()).collect(),
                Err(e) => {
                    self.status = format!("Peek failed: {e}");
                    return;
                }
            },
        };
        let target = line as usize;
        let (start, excerpt) = peek_excerpt(&lines, target, 4, 12);
        let mut body = vec![format!("{}:{}", self.status_path(&path), target + 1)];
        let num_w = (start + excerpt.len()).to_string().len();
        for (i, text) in excerpt.iter().enumerate() {
            let n = start + i;
            let marker = if n == target { '\u{25b6}' } else { ' ' };
            body.push(format!("{marker}{:>num_w$}  {text}", n + 1));
        }
        body.push(String::from("Enter jumps \u{00b7} Esc closes"));
        let anchor = self.editor.cursor_screen_pos().unwrap_or((
            self.editor.last_full_area.x + 1,
            self.editor.last_full_area.y + 1,
        ));
        self.peek_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
            body.join("\n"),
            anchor,
        ));
        self.peek_target = Some((path, line, col));
        self.status = String::new();
    }

    fn close_peek_popup(&mut self) {
        self.peek_popup = None;
        self.peek_target = None;
    }

    pub fn drain_lsp_declaration(&mut self) -> bool {
        let mut target = None;
        let mut unsupported = false;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_declaration() {
                if Some(result.request_id) != self.declaration_request_id {
                    continue;
                }
                target = result.target;
                unsupported = result.unsupported;
            }
        }
        match target {
            // The jump itself is identical to definition: open the target file,
            // move the caret, record nav history.
            Some((path, line, col)) => {
                self.go_to_definition(path, line, col);
                true
            }
            // Be explicit rather than silently no-op: say when the language
            // server has no declaration provider (e.g. TypeScript's vtsls) and
            // when it simply found nothing at this position.
            None if unsupported => {
                self.status =
                    String::from("Go to Declaration: not supported by this file's language server");
                true
            }
            None => false,
        }
    }

    pub fn drain_lsp_type_definition(&mut self) -> bool {
        let mut target = None;
        let mut unsupported = false;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_type_definition() {
                if Some(result.request_id) != self.type_definition_request_id {
                    continue;
                }
                target = result.target;
                unsupported = result.unsupported;
            }
        }
        match target {
            // The jump itself is identical to definition: open the target file,
            // move the caret, record nav history.
            Some((path, line, col)) => {
                self.go_to_definition(path, line, col);
                true
            }
            None if unsupported => {
                self.status = String::from(
                    "Go to Type Definition: not supported by this file's language server",
                );
                true
            }
            None => false,
        }
    }

    pub fn drain_lsp_implementation(&mut self) -> bool {
        let mut targets: Vec<(PathBuf, u32, u32)> = Vec::new();
        let mut unsupported = false;
        let mut responded = false;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_implementation() {
                if Some(result.request_id) != self.implementation_request_id {
                    continue;
                }
                targets = result.targets;
                unsupported = result.unsupported;
                responded = true;
            }
        }
        if !responded {
            return false;
        }
        if unsupported {
            self.status =
                String::from("Go to Implementations: not supported by this file's language server");
            return true;
        }
        match targets.len() {
            0 => self.status = String::from("No implementations found"),
            // One implementor: behave exactly like Go to Definition.
            1 => {
                let (path, line, col) = targets.into_iter().next().expect("len == 1");
                self.go_to_definition(path, line, col);
            }
            // Many implementors: offer a picker rather than silently choosing
            // the first. This 1:many case is the whole point of the feature.
            _ => self.open_location_picker(targets, "implementations"),
        }
        true
    }

    pub fn drain_lsp_references(&mut self) -> bool {
        let mut targets: Vec<(PathBuf, u32, u32)> = Vec::new();
        let mut unsupported = false;
        let mut responded = false;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_references() {
                if Some(result.request_id) != self.references_request_id {
                    continue;
                }
                targets = result.targets;
                unsupported = result.unsupported;
                responded = true;
            }
        }
        if !responded {
            return false;
        }
        if unsupported {
            self.status =
                String::from("Go to References: not supported by this file's language server");
            return true;
        }
        match targets.len() {
            0 => self.status = String::from("No references found"),
            // A symbol used exactly once: jump straight there like Go to
            // Definition rather than pop a one-row picker.
            1 => {
                let (path, line, col) = targets.into_iter().next().expect("len == 1");
                self.go_to_definition(path, line, col);
            }
            // The common case: a symbol used in many places. Offer every use as
            // a picker, exactly like Go to Implementations.
            _ => self.open_location_picker(targets, "references"),
        }
        true
    }

    /// Apply a call-hierarchy reply: a picker of callers/callees labelled
    /// `name — path:line`, jumping on select. Invoking the command again at a
    /// picked site walks the next level of the hierarchy.
    pub fn drain_lsp_call_hierarchy(&mut self) -> bool {
        let mut result = None;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(r) = lsp.drain_call_hierarchy() {
                if Some(r.request_id) == self.call_hierarchy_request_id {
                    result = Some(r);
                }
            }
        }
        let Some(result) = result else {
            return false;
        };
        let noun = if result.incoming {
            "incoming calls"
        } else {
            "outgoing calls"
        };
        if result.unsupported {
            self.status =
                String::from("Call hierarchy: not supported by this file's language server");
            return true;
        }
        if result.sites.is_empty() {
            self.status = format!("No {noun}");
            return true;
        }
        let root = self.tree.root.clone();
        let items: Vec<(String, MenuAction)> = result
            .sites
            .into_iter()
            .map(|s| {
                let label = format!(
                    "{} — {}:{}",
                    s.name,
                    s.path.strip_prefix(&root).unwrap_or(&s.path).display(),
                    s.line + 1
                );
                (
                    label,
                    MenuAction::GoToLocation {
                        path: s.path,
                        line: s.line,
                        col: s.character,
                    },
                )
            })
            .collect();
        self.present_call_hierarchy_menu(items, noun);
        true
    }

    /// Show a call-hierarchy reply as a picker at the caret — unless another
    /// menu is already open: rust-analyzer can answer seconds later, and a
    /// late reply must not replace what the user is looking at (or yank
    /// focus to the editor under them).
    fn present_call_hierarchy_menu(&mut self, items: Vec<(String, MenuAction)>, noun: &str) {
        if self.context_menu.is_some() {
            self.status = String::from("Call hierarchy ready, but another menu is open");
            return;
        }
        self.status = format!("{} {noun}", items.len());
        let origin = self.editor.cursor_screen_pos().unwrap_or((
            self.editor.last_full_area.x + 1,
            self.editor.last_full_area.y + 1,
        ));
        // A late server reply is not the user asking to leave the sidebar.
        // The `context_menu` guard cannot cover this: it is set on the NEXT
        // line, so auto-hide would already have fired.
        self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
        let root = self.tree.root.clone();
        self.context_menu = Some(ContextMenu::flat(origin, items, root));
    }

    /// Request the callers (`incoming`) or callees of the symbol at the
    /// cursor. Cmd+K H / Cmd+K Shift+H and the right-click menu rows.
    fn request_call_hierarchy_at_cursor(&mut self, incoming: bool) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            self.status = String::from("Call hierarchy: no language server for this file");
            return;
        };
        let id = lsp.request_call_hierarchy(path, line, character, incoming);
        self.call_hierarchy_request_id = Some(id);
    }

    /// Whether the current file's language server implements call hierarchy;
    /// drives the right-click menu rows, like the other capability gates.
    fn editor_language_supports_call_hierarchy(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_call_hierarchy(lang))
            .unwrap_or(false)
    }

    /// On-type formatting (#254), run once per frame: when enabled and the
    /// last edit was a keystroke in the server's advertised trigger set,
    /// fire `textDocument/onTypeFormatting` at the caret. The typed record
    /// is consumed here — examined exactly once, on the frame right after
    /// the keystroke — so a later tab switch or settings toggle can never
    /// replay a stale trigger. Never fires unadvertised: the trigger set
    /// comes from the capability the server declared, and `None` (no server
    /// probed, or no provider) means stay inert.
    pub fn tick_on_type_formatting(&mut self) {
        let taken = self.editor.last_typed.take();
        // A keystroke and a tab switch can arrive in the same input burst,
        // draining before this tick runs — the record is then armed on a tab
        // that is no longer active, and nothing else ever clears it. Sweep
        // every editor in every group (the active one is already drained by
        // the `take` above) so a trigger can only ever fire from the tab
        // that was active at its tick.
        let groups =
            std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
        for ed in groups.flat_map(|g| g.editors.iter_mut()) {
            ed.last_typed = None;
        }
        let Some((ch, seq)) = taken else {
            return;
        };
        if !self.format_on_type || !self.editor_is_text() {
            return;
        }
        if seq != self.editor.edit_seq {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lang) = path
            .extension()
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return;
        };
        let triggers = self
            .lsp
            .as_ref()
            .and_then(|lsp| lsp.language_on_type_triggers(lang));
        if !triggers.is_some_and(|t| t.contains(ch)) {
            return;
        }
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let (tab_size, insert_spaces) = self.editor.indent_preference();
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_on_type_formatting(
            path.clone(),
            line,
            character,
            ch,
            tab_size,
            insert_spaces,
        );
        self.on_type_request = Some((id, seq, path));
    }

    /// What to do with one on-type formatting reply. Extracted from the
    /// drain loop so the three-way decision is testable without a live
    /// server: the channel's sender lives inside the LSP worker, so a test
    /// cannot inject a `FormatResult` through it.
    fn on_type_reply_disposition(&self, result: &crate::lsp::manager::FormatResult) -> OnTypeReply {
        let Some((id, seq, ref requested)) = self.on_type_request else {
            return OnTypeReply::NotOurs;
        };
        // A superseded reply must NOT clear the armed request: a newer one
        // is in flight and its own reply still has to apply.
        if result.request_id != id {
            return OnTypeReply::NotOurs;
        }
        // `edit_seq` is per-tab, so the counter comparison only means
        // "buffer unchanged" when the active tab is still the one the
        // request was computed against — require the path to match too.
        // Content-unchanged is also the whole test on purpose: caret-only
        // motion (arrow keys, auto-pair type-over) leaves the counter
        // alone, and that is correct — the server's edits are document
        // edits computed against text that is still byte-identical, so
        // they apply cleanly wherever the caret has wandered.
        if self.editor.edit_seq != seq
            || requested != &result.path
            || self.editor.path.as_deref() != Some(result.path.as_path())
        {
            return OnTypeReply::Stale;
        }
        OnTypeReply::Apply
    }

    /// Apply an on-type formatting reply — quietly, and only while the
    /// buffer has not moved since the request (the edits were computed
    /// against exactly that text; continued typing makes them stale).
    pub fn drain_lsp_on_type_format(&mut self) -> bool {
        let mut results = Vec::new();
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(r) = lsp.drain_on_type_formatting() {
                results.push(r);
            }
        }
        let mut changed = false;
        for result in results {
            match self.on_type_reply_disposition(&result) {
                OnTypeReply::NotOurs => continue,
                OnTypeReply::Stale => {
                    self.on_type_request = None;
                    continue;
                }
                OnTypeReply::Apply => self.on_type_request = None,
            }
            if let Some(edits) = result.edits.filter(|e| !e.is_empty())
                && self
                    .editor
                    .apply_rename_to_open_tab(&result.path, &edits)
                    .is_some()
            {
                self.editor.clamp_cursor();
                changed = true;
            }
        }
        changed
    }

    /// Linked editing (#254): replay the last keystroke across the
    /// sibling tag ranges, keep the set alive only while the caret
    /// stays inside one, and (debounced on caret idle) ask the server
    /// for the set at a new caret position. Never fires a request for a
    /// language the LSP layer isn't tracking; a server without the
    /// provider simply never answers, and the feature stays inert.
    pub fn tick_linked_editing(&mut self) -> bool {
        const LINKED_IDLE: std::time::Duration = std::time::Duration::from_millis(250);
        let mirrored = self.editor.mirror_linked_edit();
        let eligible = self.editor_is_text() && self.lsp.is_some();
        let Some(path) = self.editor.path.clone().filter(|_| eligible) else {
            self.linked_observed = None;
            self.linked_request = None;
            self.editor.clear_linked_ranges();
            return mirrored;
        };
        let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
        // While the caret stays inside the live set, keep it — the whole
        // point is typing inside a range. (The mirror above re-synced
        // positions for this frame's keystroke.)
        if self.editor.has_linked_ranges() {
            if self.editor.linked_ranges_contain(row, col) {
                return mirrored;
            }
            self.editor.clear_linked_ranges();
        }
        let cur = (path, row, col, self.editor.edit_seq);
        if self.linked_observed.as_ref() != Some(&cur) {
            self.linked_observed = Some(cur);
            self.linked_observed_at = std::time::Instant::now();
            self.linked_request = None;
            return mirrored;
        }
        let already = self
            .linked_request
            .as_ref()
            .is_some_and(|(_, p, s)| (p, s) == (&cur.0, &cur.3));
        if already || self.linked_observed_at.elapsed() < LINKED_IDLE {
            return mirrored;
        }
        let (uline, uchar) = self.editor.cursor_position_utf16();
        let Some(lsp) = self.lsp.as_mut() else {
            return mirrored;
        };
        let id = lsp.request_linked_editing(cur.0.clone(), uline, uchar);
        self.linked_request = Some((id, cur.0, cur.3));
        mirrored
    }

    /// Install a linkedEditingRange reply, gated on the in-flight id,
    /// the path, and the edit seq the spans were computed against.
    pub fn drain_lsp_linked_editing(&mut self) -> bool {
        let mut results = Vec::new();
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(r) = lsp.drain_linked_editing() {
                results.push(r);
            }
        }
        let mut changed = false;
        for result in results {
            let Some((id, path, seq)) = self.linked_request.as_ref() else {
                continue;
            };
            if result.request_id != *id
                || self.editor.path.as_deref() != Some(path.as_path())
                || self.editor.edit_seq != *seq
            {
                continue;
            }
            self.linked_request = None;
            self.editor.set_linked_ranges(&result.ranges);
            changed = true;
        }
        changed
    }

    /// Expand Selection (#254): grow every cursor to the next
    /// semantically meaningful range. Cached chain steps apply
    /// instantly; otherwise the LSP `selectionRange` chains are fetched
    /// (one request, all cursors), with tree-sitter node ancestry as the
    /// serverless fallback — so the gesture works with no LSP at all.
    fn expand_selection(&mut self) {
        if !self.editor_is_text() {
            return;
        }
        self.editor.validate_expand_stacks();
        if self.editor.expand_selection_from_stack() {
            return;
        }
        let lang_known = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
            .is_some();
        if lang_known
            && self.lsp.is_some()
            && let Some(path) = self.editor.path.clone()
        {
            let seq = self.editor.edit_seq;
            let positions = self.editor.cursor_positions_utf16();
            // Reuse the pending request only when it was fired for these
            // exact cursors; a caret move re-fires for the new spot.
            if let Some(pending) = self.selection_range_request.as_mut()
                && pending.path == path
                && pending.seq == seq
                && pending.positions == positions
            {
                pending.presses += 1;
                return;
            }
            if let Some(lsp) = self.lsp.as_mut() {
                let id = lsp.request_selection_ranges(path.clone(), positions.clone());
                self.selection_range_request = Some(PendingSelectionRanges {
                    id,
                    path,
                    seq,
                    presses: 1,
                    positions,
                });
            }
            return;
        }
        if !self.editor.expand_selection_syntax() {
            self.status = String::from("No larger range to select");
        }
    }

    /// Shrink Selection: retrace the expand stack one step. Purely
    /// local — the stack already remembers the exact ranges.
    fn shrink_selection(&mut self) {
        if !self.editor_is_text() {
            return;
        }
        self.editor.shrink_selection_step();
    }

    /// Drain `selectionRange` replies (#254): triple-gated like
    /// occurrences (id + path + edit_seq), then either install the
    /// server's chains or resolve the queued presses via tree-sitter
    /// when the request came back unsupported/empty.
    fn drain_lsp_selection_ranges(&mut self) -> bool {
        let Some(lsp) = self.lsp.as_ref() else {
            return false;
        };
        let mut results = Vec::new();
        while let Some(r) = lsp.drain_selection_ranges() {
            results.push(r);
        }
        let mut changed = false;
        for r in results {
            let Some(pending) = self.selection_range_request.as_ref() else {
                continue;
            };
            // Gate on id + path + edit_seq AND the cursors the request
            // was fired for: a click between request and reply leaves
            // `edit_seq` unchanged, but the chains describe the OLD
            // caret and must not apply at the new one.
            if r.request_id != pending.id
                || self.editor.path.as_deref() != Some(pending.path.as_path())
                || self.editor.edit_seq != pending.seq
                || self.editor.cursor_positions_utf16() != pending.positions
            {
                if r.request_id == pending.id {
                    self.selection_range_request = None;
                }
                continue;
            }
            let presses = pending.presses;
            self.selection_range_request = None;
            if r.unsupported || r.chains.is_empty() {
                for _ in 0..presses {
                    if !self.editor.expand_selection_syntax() {
                        break;
                    }
                }
                changed = true;
                continue;
            }
            self.editor.install_selection_chains(r.chains);
            for _ in 0..presses {
                if !self.editor.expand_selection_from_stack() {
                    break;
                }
            }
            changed = true;
        }
        changed
    }

    /// Idle-caret occurrences trigger, run once per frame: when the caret has
    /// rested on one buffer position for `OCCURRENCES_IDLE`, fire ONE
    /// `documentHighlight` request for it; the moment it moves (or the buffer
    /// edits), drop the painted set. Mirrors VS Code's word highlight, which
    /// follows the cursor with a small debounce rather than every keystroke.
    pub fn tick_occurrences(&mut self) -> bool {
        const OCCURRENCES_IDLE: std::time::Duration = std::time::Duration::from_millis(250);
        let eligible = self.editor.diff.is_none()
            && self.editor.sheet.is_none()
            && self.editor.image.is_none()
            && self.lsp.is_some();
        let Some(path) = self.editor.path.clone().filter(|_| eligible) else {
            self.occ_observed = None;
            self.occurrences_request = None;
            return self.editor.clear_occurrences();
        };
        let cur = (
            path,
            self.editor.cursor_row,
            self.editor.cursor_col,
            self.editor.edit_seq,
        );
        if self.occ_observed.as_ref() != Some(&cur) {
            self.occ_observed = Some(cur);
            self.occ_observed_at = std::time::Instant::now();
            // The old symbol's tints are stale the moment the caret leaves it
            // (an edit already cleared them via mark_buffer_changed), and an
            // in-flight reply for the old spot must never paint late.
            self.occurrences_request = None;
            return self.editor.clear_occurrences();
        }
        let already_requested = self
            .occurrences_request
            .as_ref()
            .is_some_and(|(_, p, r, c, s)| (p, r, c, s) == (&cur.0, &cur.1, &cur.2, &cur.3));
        if already_requested || self.occ_observed_at.elapsed() < OCCURRENCES_IDLE {
            return false;
        }
        let (uline, uchar) = self.editor.pos_to_utf16(cur.1, cur.2);
        let Some(lsp) = self.lsp.as_mut() else {
            return false;
        };
        let id = lsp.request_document_highlights(cur.0.clone(), uline, uchar);
        self.occurrences_request = Some((id, cur.0, cur.1, cur.2, cur.3));
        false
    }

    /// Apply a documentHighlight reply to the editor, dropping it unless it
    /// answers the in-flight request AND the editor still shows that file at
    /// that edit seq (the columns were computed against that text).
    pub fn drain_lsp_document_highlights(&mut self) -> bool {
        let mut results = Vec::new();
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(r) = lsp.drain_document_highlights() {
                results.push(r);
            }
        }
        let mut changed = false;
        for result in results {
            let Some((id, path, _row, _col, seq)) = self.occurrences_request.as_ref() else {
                continue;
            };
            if result.request_id != *id
                || self.editor.path.as_deref() != Some(path.as_path())
                || self.editor.edit_seq != *seq
            {
                continue;
            }
            self.editor.apply_occurrences(result.items);
            changed = true;
        }
        changed
    }

    /// Build a multi-location picker as a `ContextMenu` anchored at the editor
    /// cursor: one row per target, labelled `relative/path:line`, each carrying a
    /// `GoToLocation` that jumps on select. Reuses the context menu's existing
    /// keyboard (arrows + Enter) and mouse handling. Shared by Go to
    /// Implementations and Go to References; `noun` is the status-line plural
    /// ("implementations" / "references").
    fn open_location_picker(&mut self, targets: Vec<(PathBuf, u32, u32)>, noun: &str) {
        // Same guard as present_call_hierarchy_menu: the LSP can answer
        // seconds later, and the reply must not replace a menu the user
        // opened while waiting (or yank focus to the editor).
        if self.context_menu.is_some() {
            self.status = String::from("Locations ready, but another menu is open");
            return;
        }
        let root = self.tree.root.clone();
        let items: Vec<(String, MenuAction)> = targets
            .into_iter()
            .map(|(path, line, col)| {
                let label = format!(
                    "{}:{}",
                    path.strip_prefix(&root).unwrap_or(&path).display(),
                    line + 1
                );
                (label, MenuAction::GoToLocation { path, line, col })
            })
            .collect();
        self.status = format!("{} {noun}", items.len());
        let origin = self.editor.cursor_screen_pos().unwrap_or((
            self.editor.last_full_area.x + 1,
            self.editor.last_full_area.y + 1,
        ));
        // As in `present_call_hierarchy_menu`: the reply arrives whenever the
        // server is ready, and the `context_menu` guard is armed a line too
        // late to protect the sidebar from this focus move.
        self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
        self.context_menu = Some(ContextMenu::flat(origin, items, root));
    }

    /// Anchor a `ContextMenu` at the activity-bar gear. `menu_rect` clamps it
    /// onto the screen, so a bottom-anchored gear pops the menu upward — the
    /// same direction VS Code's "Manage" menu opens.
    fn settings_menu_origin(&self) -> (u16, u16) {
        let gear = self.sidebar_areas.settings_icon;
        (gear.x + gear.width, gear.y)
    }

    /// Open the activity-bar gear's settings menu (VS Code's "Manage" menu).
    /// Currently one entry — Color Theme — which opens the theme picker; more
    /// settings entries slot in here later.
    fn open_settings_menu(&mut self) {
        let origin = self.settings_menu_origin();
        self.context_menu = Some(ContextMenu::flat(
            origin,
            vec![
                (String::from("Color Theme"), MenuAction::OpenThemePicker),
                (
                    String::from("Customize Layout"),
                    MenuAction::OpenCustomizeLayout,
                ),
            ],
            self.workspace_root().to_path_buf(),
        ));
        // The gear renders "active" while its menu is open; re-emit it so the
        // pressed-state PNG replaces the idle one.
        self.overlays.activity.mark_dirty();
    }

    /// Anchor for the Customize Layout popup: just under the Customize Layout
    /// (⛶) title-bar icon when it has been laid out, else the activity-bar gear
    /// (the gear-menu entry path).
    fn customize_layout_origin(&self) -> (u16, u16) {
        let icon = self.layout_icon_areas.customize;
        if icon.width > 0 {
            // Pull left so the wider popup doesn't spill off the right edge;
            // `menu_rect` clamps anything that still would.
            (icon.x.saturating_sub(18), icon.y + 1)
        } else {
            self.settings_menu_origin()
        }
    }

    /// Build the Customize Layout popup rows (VS Code's title-bar layout
    /// controls): visibility checkboxes, then radio groups for Side Bar
    /// Position, Panel Alignment, and Quick Input Position, then Zen Mode.
    /// A leading `✔` marks an enabled toggle / the active radio option.
    fn customize_layout_items(&self) -> Vec<MenuEntry> {
        let check = |on: bool| if on { "\u{2713} " } else { "  " };
        vec![
            MenuEntry::item(
                format!("{}Activity Bar", check(self.activity_bar_visible)),
                MenuAction::ToggleActivityBar,
            ),
            MenuEntry::item(
                format!("{}Primary Side Bar", check(self.show_tree)),
                MenuAction::ToggleSideBar,
            ),
            MenuEntry::item(
                format!(
                    "{}Secondary Side Bar",
                    check(self.secondary_side_bar_visible)
                ),
                MenuAction::ToggleSecondarySideBar,
            ),
            MenuEntry::item(
                format!("{}Panel", check(self.show_terminal)),
                MenuAction::TogglePanel,
            ),
            MenuEntry::item(
                format!("{}Status Bar", check(self.status_bar_visible)),
                MenuAction::ToggleStatusBar,
            ),
            MenuEntry::item(
                format!("{}Minimap", check(self.minimap_visible)),
                MenuAction::ToggleMinimap,
            ),
            MenuEntry::item(
                format!("{}Auto-Hide Side Bar", check(self.sidebar_auto_hide)),
                MenuAction::ToggleAutoHideSideBar,
            ),
            MenuEntry::Separator,
            MenuEntry::header("Primary Side Bar Position"),
            MenuEntry::item(
                format!(
                    "{}Left",
                    check(self.side_bar_position == SideBarPosition::Left)
                ),
                MenuAction::SetSideBarPosition(SideBarPosition::Left),
            ),
            MenuEntry::item(
                format!(
                    "{}Right",
                    check(self.side_bar_position == SideBarPosition::Right)
                ),
                MenuAction::SetSideBarPosition(SideBarPosition::Right),
            ),
            MenuEntry::Separator,
            MenuEntry::header("Panel Alignment"),
            MenuEntry::item(
                format!(
                    "{}Left",
                    check(self.panel_alignment == PanelAlignment::Left)
                ),
                MenuAction::SetPanelAlignment(PanelAlignment::Left),
            ),
            MenuEntry::item(
                format!(
                    "{}Center",
                    check(self.panel_alignment == PanelAlignment::Center)
                ),
                MenuAction::SetPanelAlignment(PanelAlignment::Center),
            ),
            MenuEntry::item(
                format!(
                    "{}Right",
                    check(self.panel_alignment == PanelAlignment::Right)
                ),
                MenuAction::SetPanelAlignment(PanelAlignment::Right),
            ),
            MenuEntry::item(
                format!(
                    "{}Justify",
                    check(self.panel_alignment == PanelAlignment::Justify)
                ),
                MenuAction::SetPanelAlignment(PanelAlignment::Justify),
            ),
            MenuEntry::Separator,
            MenuEntry::header("Quick Input Position"),
            MenuEntry::item(
                format!(
                    "{}Top",
                    check(self.quick_input_position == QuickInputPosition::Top)
                ),
                MenuAction::SetQuickInputPosition(QuickInputPosition::Top),
            ),
            MenuEntry::item(
                format!(
                    "{}Center",
                    check(self.quick_input_position == QuickInputPosition::Center)
                ),
                MenuAction::SetQuickInputPosition(QuickInputPosition::Center),
            ),
            MenuEntry::Separator,
            MenuEntry::item(
                format!("{}Zen Mode", check(self.zen_mode)),
                MenuAction::ToggleZenMode,
            ),
        ]
    }

    /// Reopen the Customize Layout popup with the cursor on the row carrying
    /// `action`. Looking the row up beats hardcoding an index: the indices
    /// were already stale for every row below the first separator (a row
    /// insert shifts them and nothing catches it), so this makes that whole
    /// class of bug unrepresentable.
    fn open_customize_layout_menu_on(&mut self, action: &MenuAction) {
        let idx = self
            .customize_layout_items()
            .iter()
            .position(|e| matches!(e, MenuEntry::Item { action: a, .. } if a == action))
            .unwrap_or(0);
        self.open_customize_layout_menu_at(idx);
    }

    /// Open (or re-open) the Customize Layout popup with the cursor on row
    /// `selected`. Each toggle re-opens it so the popup stays put while the
    /// user flips several controls, exactly like VS Code's dropdown.
    fn open_customize_layout_menu_at(&mut self, selected: usize) {
        let origin = self.customize_layout_origin();
        self.context_menu = Some(ContextMenu {
            origin,
            items: self.customize_layout_items(),
            selected,
            open_submenu: None,
            submenu_selected: 0,
            target_dir: self.workspace_root().to_path_buf(),
        });
        self.overlays.activity.mark_dirty();
    }

    /// Open the Customize Layout popup fresh (cursor on the first row).
    fn open_customize_layout_menu(&mut self) {
        self.open_customize_layout_menu_at(0);
    }

    /// Persist the current Customize Layout chrome to `~/.config/croft`.
    /// Best-effort and skipped under test (hermetic suite, like `apply_theme`).
    fn persist_layout(&self) {
        if cfg!(test) {
            return;
        }
        let _ = crate::prefs::save_layout(crate::prefs::LayoutPrefs {
            activity_bar: self.activity_bar_visible,
            status_bar: self.status_bar_visible,
            side_bar_position: self.side_bar_position,
            secondary_side_bar: self.secondary_side_bar_visible,
            panel_alignment: self.panel_alignment,
            quick_input_position: self.quick_input_position,
        });
    }

    /// Hide the activity bar's inline images when the bar is collapsed so the
    /// OSC-1337 icons don't ghost over the editor; arm a re-emit when shown.
    fn after_chrome_visibility_change(&mut self) {
        self.overlays.activity.mark_dirty();
        if self.overlays.activity.has_images() {
            self.overlays.activity.request_clear();
        }
        // The welcome logo re-bakes against the new editor rect on next render.
        self.overlays.welcome.mark_dirty();
    }

    /// Show or hide the primary side bar. Every route that flips it by hand —
    /// the Cmd+B keybinding, the palette command, the Customize Layout row and
    /// the layout-icon click — goes through here, because each one is a
    /// deliberate sidebar action and so must take the auto-hide pin (#260).
    /// Four hand-rolled copies is exactly how three of them ended up without
    /// it: the pin lived only on the palette route, so the real Cmd+B revealed
    /// the panel and the next click into the editor collapsed it again.
    fn toggle_side_bar(&mut self) {
        let was_visible = self.show_tree;
        self.show_tree = !self.show_tree;
        // A reveal the user asked for outlives the focus move that follows it.
        // Taken only when auto-hide is live: a pin set while the feature is
        // off would sit unconsumed and silently eat the first collapse after
        // they turn it on.
        // Structural suppression (Zen Mode, or a hidden activity bar) means no
        // collapse can fire for as long as it lasts, so a pin taken now is the
        // "sits unconsumed and silently eats a later collapse" case this line
        // already guards against for `!sidebar_auto_hide` — same bug, same
        // answer: refuse to bank it rather than hold it indefinitely.
        self.sidebar_pinned_open =
            self.show_tree && self.sidebar_auto_hide && self.activity_bar_visible && !self.zen_mode;
        // A deliberate toggle supersedes any pending automatic collapse: the
        // dwell was armed against a sidebar state the user has since changed by
        // hand. Leaving it armed lets a later idle tick fire against the NEW
        // state — spending the pin this reveal just banked on a collapse the
        // user never saw, which is #294 reached by a different door.
        self.sidebar_dwell.disarm();
        // Hiding the sidebar while Run-Debug was on screen: arm the same
        // OSC-1337 image-cell evict gate that fires on a sidebar-view change.
        // Without this the bug+play icon ghosts on top of the editor /
        // terminal that fills the space the panel just vacated.
        if was_visible
            && !self.show_tree
            && self.sidebar_view == SidebarView::RunDebug
            && self.overlays.run_debug.was_emitted()
        {
            self.overlays.run_debug.request_clear();
        }
    }

    /// Toggle the secondary side bar (the Outline of the active file), on the
    /// edge opposite the primary side bar. Mirrors ⌥⌘B.
    fn toggle_secondary_side_bar(&mut self) {
        self.secondary_side_bar_visible = !self.secondary_side_bar_visible;
        self.persist_layout();
        self.after_chrome_visibility_change();
        self.status = String::from(if self.secondary_side_bar_visible {
            "Secondary side bar shown"
        } else {
            "Secondary side bar hidden"
        });
    }

    /// Toggle Zen Mode: hide the activity bar, both side bars, the panel, and
    /// the status bar; toggling off restores the pre-Zen snapshot. Mirrors VS
    /// Code's ⌘K Z.
    fn toggle_zen_mode(&mut self) {
        if let Some(prev) = self.pre_zen.take() {
            self.activity_bar_visible = prev.activity_bar;
            self.status_bar_visible = prev.status_bar;
            self.show_tree = prev.side_bar;
            self.secondary_side_bar_visible = prev.secondary_side_bar;
            self.show_terminal = prev.panel;
            self.zen_mode = false;
            self.status = String::from("Zen Mode off");
        } else {
            self.pre_zen = Some(PreZenLayout {
                activity_bar: self.activity_bar_visible,
                status_bar: self.status_bar_visible,
                side_bar: self.show_tree,
                secondary_side_bar: self.secondary_side_bar_visible,
                panel: self.show_terminal,
            });
            self.activity_bar_visible = false;
            self.status_bar_visible = false;
            self.show_tree = false;
            // Zen is structural, not a transient suppression: it can last the
            // session, and a dwell left armed would fire on the frame Zen
            // exits — a collapse the user long since stopped associating with
            // the focus move that armed it.
            //
            // The pin goes too, for the reason `toggle_side_bar` refuses to
            // bank one here: Zen sets both structural conditions, so no
            // collapse can fire while it lasts and a pin held across it is
            // unconsumable — it would silently eat the first real collapse
            // after Zen exits. Main cleared this incidentally, by taking the
            // pin on every focus move; consuming at fire time instead is
            // correct but leaves this boundary to say so explicitly.
            self.sidebar_dwell.disarm();
            self.sidebar_pinned_open = false;
            self.secondary_side_bar_visible = false;
            self.show_terminal = false;
            self.zen_mode = true;
            self.status = String::from("Zen Mode on");
        }
        self.after_chrome_visibility_change();
    }

    /// Replace the gear menu with the Color Theme picker: one row per theme,
    /// a check on the active one. Selecting a row switches + persists it.
    fn open_theme_picker(&mut self) {
        let origin = self.settings_menu_origin();
        let active = self.theme;
        let items: Vec<(String, MenuAction)> = crate::theme::Theme::all()
            .iter()
            .map(|&t| {
                let mark = if t == active { "✔ " } else { "  " };
                (format!("{mark}{}", t.label()), MenuAction::SetTheme(t))
            })
            .collect();
        let selected = crate::theme::Theme::all()
            .iter()
            .position(|&t| t == active)
            .unwrap_or(0);
        self.context_menu = Some(ContextMenu {
            origin,
            items: items.into_iter().map(MenuEntry::from).collect(),
            selected,
            open_submenu: None,
            submenu_selected: 0,
            target_dir: self.workspace_root().to_path_buf(),
        });
        self.overlays.activity.mark_dirty();
    }

    /// Open the Explorer's "Views and More Actions" (⋯) menu: one row per
    /// stacked sub-view, each prefixed with a check when currently shown.
    /// Selecting a row toggles that view (see [`Self::toggle_explorer_view`]).
    /// The ⋯-menu / status label for a sub-view. DEPENDENCIES is language-aware
    /// ("Rust Dependencies", "Python Dependencies", or plain "Dependencies" for
    /// a polyglot root), computed from the detected ecosystems; every other view
    /// uses its static name.
    fn explorer_view_label(&self, view: ExplorerView) -> String {
        match view {
            ExplorerView::Dependencies => {
                crate::widgets::dependencies::menu_label(&self.dep_ecosystems)
            }
            other => other.label().to_string(),
        }
    }

    /// Whether a sub-view may appear in the ⋯ menu and stack in the panel.
    /// DEPENDENCIES is additionally gated on a manifest being detected at the
    /// root, so a plain folder shows no dependency view at all; every other view
    /// is always available.
    fn explorer_view_available(&self, view: ExplorerView) -> bool {
        match view {
            ExplorerView::Dependencies => !self.dep_ecosystems.is_empty(),
            _ => true,
        }
    }

    /// Anchored just below the ⋯ button on the EXPLORER title line; the
    /// menu-rect clamp pulls it left so it never spills off the right edge.
    fn open_explorer_views_menu(&mut self) {
        let btn = self.tree.header_views_btn;
        let origin = if btn.width > 0 {
            (btn.x, btn.y + 1)
        } else {
            (self.tree.last_area.x + 1, self.tree.last_area.y + 1)
        };
        let items: Vec<(String, MenuAction)> = ExplorerView::ALL
            .iter()
            .filter(|&&view| self.explorer_view_available(view))
            .map(|&view| {
                let mark = if self.explorer_views.is_visible(view) {
                    "\u{2713} "
                } else {
                    "  "
                };
                (
                    format!("{mark}{}", self.explorer_view_label(view)),
                    MenuAction::ToggleExplorerView(view),
                )
            })
            .collect();
        self.context_menu = Some(ContextMenu::flat(
            origin,
            items,
            self.workspace_root().to_path_buf(),
        ));
    }

    /// Flip one Explorer sub-view's visibility, persist the new set, and (for a
    /// data-backed view turned on) clear its fetch latch so the next frame
    /// re-populates it. The layout reads `explorer_views` directly, so no other
    /// wiring is needed for the section to appear or vanish.
    fn toggle_explorer_view(&mut self, view: ExplorerView) {
        let now_visible = self.explorer_views.toggle(view);
        let _ = crate::prefs::save_explorer_views(self.explorer_views.as_prefs());
        if now_visible {
            match view {
                ExplorerView::Timeline => self.timeline_fetched = None,
                ExplorerView::Dependencies => self.deps_fetched = None,
                _ => {}
            }
        }
        self.status = format!(
            "{} {}",
            if now_visible { "Showing" } else { "Hiding" },
            self.explorer_view_label(view)
        );
    }

    /// Lay out and paint the Explorer's visible stacked sub-views top-to-bottom
    /// inside `area` (the region above the SYSTEM footer). Folders (the file
    /// tree) is the flexible region that absorbs leftover rows; every other
    /// visible section takes its own collapsible height, clipped so the tree
    /// always keeps a few rows. Sections hidden via the ⋯ menu are skipped, and
    /// their hit-test rects are zeroed so a stale click can't reach them.
    fn render_explorer_sections(&mut self, frame: &mut ratatui::Frame, area: Rect) {
        self.open_editors.last_area = Rect::default();
        self.outline.last_area = Rect::default();
        self.timeline.last_area = Rect::default();
        self.dependencies.last_area = Rect::default();

        let folders_visible = self.explorer_views.is_visible(ExplorerView::Folders);
        if !folders_visible {
            // The tree isn't painted, so zero its geometry too — otherwise a
            // click on a since-hidden row would still resolve against it.
            self.tree.last_inner = Rect::default();
            self.tree.last_area = Rect::default();
        }
        if area.height == 0 || area.width == 0 {
            if folders_visible {
                frame.render_widget(&mut self.tree, area);
            }
            return;
        }

        // Requested rows per visible section, in stacking order. Folders is a
        // placeholder (0) here; it claims the leftover after the others.
        let mut heights: Vec<(ExplorerView, u16)> = Vec::new();
        for &v in &ExplorerView::ALL {
            if !self.explorer_views.is_visible(v) || !self.explorer_view_available(v) {
                continue;
            }
            let h = match v {
                ExplorerView::Folders => 0,
                ExplorerView::OpenEditors => self.open_editors.desired_height(area.height),
                ExplorerView::Outline => self.outline.desired_height(area.height),
                ExplorerView::Timeline => self.timeline.desired_height(area.height),
                ExplorerView::Dependencies => self.dependencies.desired_height(area.height),
            };
            heights.push((v, h));
        }
        if heights.is_empty() {
            return;
        }

        // Reserve a floor for the tree, then hand the fixed (non-Folders)
        // sections rows in order, clipping each to what's left.
        let total = area.height;
        let tree_floor = if folders_visible { 3u16.min(total) } else { 0 };
        let mut budget = total.saturating_sub(tree_floor);
        let mut fixed_sum = 0u16;
        for (v, h) in heights.iter_mut() {
            if *v == ExplorerView::Folders {
                continue;
            }
            let assigned = (*h).min(budget);
            *h = assigned;
            budget -= assigned;
            fixed_sum += assigned;
        }
        if folders_visible {
            if let Some(slot) = heights
                .iter_mut()
                .find(|(v, _)| *v == ExplorerView::Folders)
            {
                slot.1 = total.saturating_sub(fixed_sum);
            }
        } else {
            // No tree to absorb slack: grow the first section to fill the gap.
            let used: u16 = heights.iter().map(|(_, h)| *h).sum();
            if used < total
                && let Some(first) = heights.first_mut()
            {
                first.1 += total - used;
            }
        }

        let mut y = area.y;
        for (v, h) in heights {
            if h == 0 {
                continue;
            }
            let rect = Rect {
                x: area.x,
                y,
                width: area.width,
                height: h,
            };
            y = y.saturating_add(h);
            match v {
                ExplorerView::Folders => frame.render_widget(&mut self.tree, rect),
                ExplorerView::OpenEditors => frame.render_widget(&mut self.open_editors, rect),
                ExplorerView::Outline => frame.render_widget(&mut self.outline, rect),
                ExplorerView::Timeline => frame.render_widget(&mut self.timeline, rect),
                ExplorerView::Dependencies => frame.render_widget(&mut self.dependencies, rect),
            }
        }
    }

    /// Switch the IDE color theme: persist it, repaint the iTerm2 session
    /// background (so every `Color::Reset` surface follows), re-bake the
    /// OSC-1337 icon PNGs against the new background, and drop the lazily-baked
    /// image overlays + arm a full clear so nothing ghosts the old background.
    fn apply_theme(&mut self, theme: crate::theme::Theme) {
        self.apply_theme_visuals(theme);
        // Persistence is best-effort: a write failure never blocks the
        // in-session switch, which has already taken effect above. Skipped
        // under test so the suite never clobbers the developer's real config.
        // The layered-settings reload path calls `apply_theme_visuals`
        // directly instead — a workspace-set theme must not be written back
        // into the user's own config.
        if !cfg!(test) {
            let _ = crate::prefs::save_theme(theme);
        }
    }

    /// Everything [`Self::apply_theme`] does except persisting the choice.
    fn apply_theme_visuals(&mut self, theme: crate::theme::Theme) {
        self.theme = theme;
        // Push the theme's code palette into the highlighter and re-highlight
        // every open editor (across all split groups): cached spans carry baked
        // colors, so the syntax colors only follow the theme once recomputed.
        crate::highlight::set_syntax_palette(theme.syntax());
        // Assign the theme before re-highlighting: the rebuilds below (the
        // markdown preview in particular) read `ed.theme`, and the per-frame
        // push in render would hand it over one frame too late.
        for ed in &mut self.editor.editors {
            ed.theme = theme;
            ed.rehighlight_for_theme();
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in &mut group.editors {
                ed.theme = theme;
                ed.rehighlight_for_theme();
            }
        }
        // Refresh the per-pane gradient-border flag for the new theme so the
        // focused box switches its highlight style on the very next frame.
        self.sync_focus_flags();
        if !cfg!(test) {
            use std::io::Write;
            let mut out = stdout();
            // Portable dynamic colors first (all hosts), then the iTerm2
            // sRGB override where supported.
            let _ = out.write_all(host_colors_seq(theme).as_bytes());
            if crate::iterm2_inline::detect_iterm2_inline_support() {
                let _ = out.write_all(set_session_bg_srgb_seq(theme.editor_bg_rgb()).as_bytes());
            }
            let _ = out.flush();
        }
        // Re-bake the fixed icon/badge/run-debug PNGs against the new bg.
        self.init_graphics();
        // The welcome wordmark, no-repo hero, SSH empty state, and editor
        // image previews are baked lazily and keyed on layout, not theme —
        // drop them so the next render re-bakes them on the new background.
        self.overlays.welcome.disable();
        self.overlays.hero.disable();
        self.overlays.ssh.disable();
        self.overlays.editor[0].disable();
        self.overlays.editor[1].disable();
        // Evict the stale activity-icon image layer and force a full repaint
        // (the clear latch the main loop folds into `terminal.clear()`), so
        // every cell — SGR and image alike — repaints on the new background.
        self.overlays.activity.mark_dirty();
        self.overlays.activity.request_clear();
        self.status = format!("Color Theme: {}", theme.label());
    }

    /// [`Self::open_at`] for a position that came FROM a language server, whose
    /// column counts UTF-16 code units rather than characters. The file has to
    /// be open before the conversion can happen — the mapping needs the target
    /// line's text — so this opens at column 0 and then re-seats the caret.
    ///
    /// Out-of-range answers are clamped rather than rejected, matching
    /// `open_at`: a server that names a line past the end of a buffer we have
    /// since edited should still land the user on the right file.
    fn open_at_utf16(&mut self, path: &Path, line: u32, character: u32) -> Result<()> {
        self.open_at(path, line as usize, 0)?;
        let row = self.editor.cursor_row;
        let col = self.editor.utf16_col_to_char_pub(row, character);
        let max_col = self
            .editor
            .lines
            .get(row)
            .map(|l| l.chars().count())
            .unwrap_or(0);
        self.editor.cursor_col = col.min(max_col);
        self.editor.ensure_cursor_col_visible();
        Ok(())
    }

    fn open_at(&mut self, path: &Path, row: usize, col: usize) -> Result<()> {
        self.hover_popup = None;
        self.hover_diagnostic = None;
        self.editor.open_preview(path)?;
        self.sync_open_file_poll_mtime();
        let row = row.min(self.editor.lines.len().saturating_sub(1));
        let max_col = self
            .editor
            .lines
            .get(row)
            .map(|l| l.chars().count())
            .unwrap_or(0);
        self.editor.cursor_row = row;
        self.editor.cursor_col = col.min(max_col);
        let page = self.editor.page_size().max(1);
        self.editor.scroll = row.saturating_sub(page / 2);
        self.editor.scroll_col = 0;
        self.editor.ensure_cursor_col_visible();
        self.focus_pane(Pane::Editor);
        self.poke_cursor();
        Ok(())
    }

    /// The active editor's position as a NavLoc, for threading through
    /// back/forward so the walk is reversible. None on file-less surfaces
    /// (welcome screen, image tabs without a path).
    fn current_nav_loc(&self) -> Option<NavLoc> {
        let path = self.editor.path.clone()?;
        Some(NavLoc {
            path,
            row: self.editor.cursor_row,
            col: self.editor.cursor_col,
        })
    }

    fn nav_back(&mut self) {
        let current = self.current_nav_loc();
        let Some(loc) = self.nav.back(current) else {
            self.status = "No previous location".to_string();
            return;
        };
        let line = loc.row;
        match self.open_at(&loc.path, loc.row, loc.col) {
            Ok(()) => {
                self.status = format!("Back to {} line {}", self.status_path(&loc.path), line + 1)
            }
            Err(e) => self.status = format!("Go back failed: {e}"),
        }
    }

    /// VS Code "Go Forward" (Ctrl+Shift+-): return along the trail Go Back
    /// walked, restoring the position each back step left.
    fn nav_forward(&mut self) {
        let current = self.current_nav_loc();
        let Some(loc) = self.nav.forward(current) else {
            self.status = "No forward location".to_string();
            return;
        };
        let line = loc.row;
        match self.open_at(&loc.path, loc.row, loc.col) {
            Ok(()) => {
                self.status = format!(
                    "Forward to {} line {}",
                    self.status_path(&loc.path),
                    line + 1
                )
            }
            Err(e) => self.status = format!("Go forward failed: {e}"),
        }
    }

    /// VS Code "Go to Last Edit Location" (Cmd+K Cmd+Q): jump to the most
    /// recent buffer edit across the open editors, threading the current
    /// position onto the back stack so Ctrl+- returns. The location lives
    /// on each editor (`last_edit_pos`), so an edit in a background split
    /// counts too; a buffer closed since its edit takes its location with
    /// it, like the rest of its view state.
    fn goto_last_edit_location(&mut self) {
        let mut best: Option<(std::time::Instant, NavLoc)> = None;
        let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
        for group in groups {
            for ed in &group.editors {
                let (Some(at), Some((row, col)), Some(path)) =
                    (ed.last_edit_at, ed.last_edit_pos, ed.path.clone())
                else {
                    continue;
                };
                if best.as_ref().is_none_or(|(b, _)| at > *b) {
                    best = Some((at, NavLoc { path, row, col }));
                }
            }
        }
        let Some((_, loc)) = best else {
            self.status = String::from("No edits this session");
            return;
        };
        if let Some(cur) = self.current_nav_loc() {
            self.nav.record(cur);
        }
        let line = loc.row;
        match self.open_at(&loc.path, loc.row, loc.col) {
            Ok(()) => {
                self.status = format!(
                    "Last edit: {} line {}",
                    self.status_path(&loc.path),
                    line + 1
                )
            }
            Err(e) => self.status = format!("Go to last edit failed: {e}"),
        }
    }

    fn trigger_definition_at(&mut self, col: u16, row: u16) {
        if self.editor.has_non_text_view() {
            return;
        }
        let Some((line, c)) = self.editor.buffer_pos_at(col, row) else {
            return;
        };
        self.editor.cursor_row = line;
        self.editor.cursor_col = c;
        // A server-resolved document link outranks Go to Definition at
        // this spot (#254): URLs in comments have no definition at all,
        // and an import specifier's link and definition land in the same
        // file anyway — VS Code follows the link too.
        if let Some(target) = self.editor.document_link_at(line, c).map(str::to_string) {
            self.open_document_link(&target);
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let (uline, uchar) = self.editor.pos_to_utf16(line, c);
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_definition(path, uline, uchar);
        self.definition_request_id = Some(id);
    }

    /// Alt+F12 / palette "Peek Definition": the definition request whose
    /// response opens an excerpt popup instead of jumping (#115).
    fn peek_definition_at_cursor(&mut self) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            self.status = String::from("No language server for this file");
            return;
        };
        let id = lsp.request_definition(path, line, character);
        self.peek_definition_request_id = Some(id);
        self.status = String::from("Peeking definition");
    }

    /// Request the LSP definition of the symbol at the current cursor (buffer)
    /// position. Used by the editor right-click "Go to Definition" item, where
    /// the cursor has already been moved to the click point.
    fn request_definition_at_cursor(&mut self) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_definition(path, line, character);
        self.definition_request_id = Some(id);
    }

    /// Request the LSP declaration of the symbol at the current cursor (buffer)
    /// position. Used by the editor right-click "Go to Declaration" item and the
    /// `⇧F12` keybinding. Declaration and definition coincide for languages with
    /// no separate declaration site (e.g. Python); they diverge for C/C++ (header
    /// prototype) and TypeScript (`.d.ts`).
    fn request_declaration_at_cursor(&mut self) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_declaration(path, line, character);
        self.declaration_request_id = Some(id);
    }

    /// Request the LSP type definition of the symbol at the current cursor
    /// (buffer) position. Used by the editor right-click "Go to Type Definition"
    /// item and the `⌃F12` keybinding. Jumps to where the *type* of the
    /// expression is defined, as opposed to the symbol itself (definition).
    fn request_type_definition_at_cursor(&mut self) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_type_definition(path, line, character);
        self.type_definition_request_id = Some(id);
    }

    /// Request the LSP implementations of the abstraction at the current cursor
    /// (buffer) position. Used by the editor right-click "Go to Implementations"
    /// item and the `⌘F12` keybinding. Meaningful on traits / interfaces /
    /// abstract methods; the server may return many, and croft jumps to the first.
    fn request_implementation_at_cursor(&mut self) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_implementation(path, line, character);
        self.implementation_request_id = Some(id);
    }

    /// Request the LSP references of the symbol at the current cursor (buffer)
    /// position. Used by the editor right-click "Go to References" item and the
    /// `⇧F12` keybinding. The server almost always returns many uses, which
    /// `drain_lsp_references` then offers as a picker.
    fn request_references_at_cursor(&mut self) {
        let (line, character) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_references(path, line, character);
        self.references_request_id = Some(id);
    }

    /// Whether the current editor file's language server implements
    /// `textDocument/declaration`. Drives whether the right-click menu shows the
    /// "Go to Declaration" row. Unknown (server not yet spawned) or no server is
    /// treated as unsupported, so the row only appears once support is confirmed.
    fn editor_language_supports_declaration(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_declaration(lang))
            .unwrap_or(false)
    }

    /// Whether the current editor file's language server implements
    /// `textDocument/typeDefinition`. Drives whether the right-click menu shows
    /// the "Go to Type Definition" row. Unknown (server not yet spawned) or no
    /// server is treated as unsupported, so the row only appears once support is
    /// confirmed.
    fn editor_language_supports_type_definition(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_type_definition(lang))
            .unwrap_or(false)
    }

    /// Whether the current editor file's language server implements
    /// `textDocument/implementation`. Drives whether the right-click menu shows
    /// the "Go to Implementations" row. Unknown (server not yet spawned) or no
    /// server is treated as unsupported, so the row only appears once support is
    /// confirmed.
    fn editor_language_supports_implementation(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_implementation(lang))
            .unwrap_or(false)
    }

    /// Whether the current editor file's language server implements
    /// `textDocument/references`. Drives whether the right-click menu shows the
    /// "Go to References" row. Unknown (server not yet spawned) or no server is
    /// treated as unsupported, so the row only appears once support is confirmed.
    fn editor_language_supports_references(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_references(lang))
            .unwrap_or(false)
    }

    fn editor_language_supports_code_action(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_code_action(lang))
            .unwrap_or(false)
    }

    /// VS Code "Change All Occurrences" (Cmd/Ctrl+F2): select every textual
    /// match of the word under the cursor in the current file as multi-cursor
    /// carets so the next keystrokes edit them all at once.
    fn start_change_all_occurrences(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let n = self.editor.select_all_occurrences_of_word_at_cursor();
        if n == 0 {
            self.status = String::from("No symbol under cursor");
        } else {
            self.status = format!("Selected {n} occurrences (type to replace, Esc to cancel)");
        }
    }

    /// VS Code "Add Selection to Next Find Match" (`Cmd+D`): select the word
    /// under the cursor, then grow the multi-cursor one occurrence per press.
    fn start_select_next_occurrence(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let n = self.editor.select_next_occurrence();
        if n == 0 {
            self.status = String::from("No symbol under cursor");
        } else if n > 1 {
            self.status = format!("Selected {n} occurrences (type to replace, Esc to cancel)");
        }
    }

    /// VS Code "Delete Line" (`Cmd+Shift+K`): delete the cursor's line, or
    /// every line a selection touches, yanking the removed text to the
    /// clipboard. Replaces the old `Cmd+d d` convenience, whose leader now
    /// belongs to Add Selection to Next Match.
    fn delete_current_line(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let yanked = self.editor.delete_caret_lines();
        if !yanked.is_empty() {
            copy_to_clipboard(&yanked);
        }
        let n = yanked.lines().count();
        self.status = format!("Deleted {n} {}", if n == 1 { "line" } else { "lines" });
    }

    /// VS Code "Rename Symbol" (F2): prompt for a new name pre-filled with the
    /// identifier under the cursor; committing fires an LSP `rename` request.
    fn start_rename_symbol(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return;
        };
        if self.lsp.is_none() {
            self.status = String::from("No language server for this file");
            return;
        }
        // Prepare-rename first (#254): the server validates the position
        // and hands back the exact range + placeholder, so the prompt
        // pre-fills the real symbol and an invalid position fails fast
        // with the server's own message. The worker always answers;
        // an `unsupported` verdict falls back to the word-under-cursor
        // prompt below (today's behavior, kept for servers without the
        // capability).
        let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
        let (line, character) = self.editor.pos_to_utf16(row, col);
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_prepare_rename(path.clone(), line, character);
        // Overwriting also disarms any previous in-flight prepare: its caret
        // is abandoned, and a late verdict for it must not reopen a prompt
        // carrying the old (row, col) into the rename request.
        self.prepare_rename_request = Some((id, path, row, col, self.editor.edit_seq));
        self.status = String::from("Preparing rename…");
    }

    /// The pre-#254 rename prompt: pre-fill with the word under the
    /// cursor. The fallback when no server advertises `prepareProvider`
    /// (or it answers "default behavior").
    fn open_rename_prompt_fallback(&mut self, path: PathBuf, row: usize, col: usize) {
        let Some((start, end)) = self.editor.word_at(row, col) else {
            self.status = String::from("No symbol under cursor");
            return;
        };
        let word: String = self.editor.lines[row]
            .chars()
            .skip(start)
            .take(end - start)
            .collect();
        self.prompt = Some(Prompt {
            label: format!("Rename Symbol '{word}'"),
            buffer: word,
            kind: PromptKind::RenameSymbol { path, row, col },
            target_dir: PathBuf::new(),
            error: None,
        });
    }

    /// Resolve a prepare-rename verdict (#254) into the prompt, an
    /// error, or the fallback. Gated on id + path + edit_seq like every
    /// deferred caret request.
    pub fn drain_lsp_prepare_rename(&mut self) -> bool {
        let mut results = Vec::new();
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(r) = lsp.drain_prepare_rename() {
                results.push(r);
            }
        }
        let mut changed = false;
        for result in results {
            changed |= self.apply_prepare_rename_verdict(result);
        }
        changed
    }

    /// Resolve one prepare-rename verdict into the prompt, a status, or the
    /// word-under-cursor fallback. Split out of the drain loop so the four
    /// verdict shapes are testable: the reply channel's sender lives inside
    /// the LSP worker, so a test cannot inject a `PrepareRenameResult`
    /// through it. Returns whether the screen needs a repaint.
    fn apply_prepare_rename_verdict(
        &mut self,
        result: crate::lsp::manager::PrepareRenameResult,
    ) -> bool {
        let Some((id, path, row, col, seq)) = self.prepare_rename_request.clone() else {
            return false;
        };
        if result.request_id != id {
            return false;
        }
        self.prepare_rename_request = None;
        if self.editor.path.as_deref() != Some(path.as_path()) || self.editor.edit_seq != seq {
            // The caret moved on (an edit, or a tab switch — which also
            // bumps edit_seq). Say so: bailing silently would strand
            // "Preparing rename…" on screen with no way to tell the
            // rename died.
            self.status = String::from("Rename cancelled");
            return true;
        }
        if result.unsupported {
            self.open_rename_prompt_fallback(path, row, col);
            return true;
        }
        if let Some(msg) = result.error {
            self.status = format!("Rename rejected: {msg}");
            return true;
        }
        let Some(((sl, sc, el, ec), placeholder)) = result.target else {
            self.status = String::from("Nothing renameable at the cursor");
            return true;
        };
        // Placeholder wins; otherwise the validated range's text.
        let word = placeholder.unwrap_or_else(|| {
            let (sr, er) = (sl as usize, el as usize);
            let scol = self.editor.utf16_col_to_char_pub(sr, sc);
            let ecol = self.editor.utf16_col_to_char_pub(er, ec);
            if sr == er {
                self.editor
                    .lines
                    .get(sr)
                    .map(|l| {
                        l.chars()
                            .skip(scol)
                            .take(ecol.saturating_sub(scol))
                            .collect()
                    })
                    .unwrap_or_default()
            } else {
                String::new()
            }
        });
        if word.is_empty() {
            self.open_rename_prompt_fallback(path, row, col);
            return true;
        }
        self.prompt = Some(Prompt {
            label: format!("Rename Symbol '{word}'"),
            buffer: word,
            kind: PromptKind::RenameSymbol { path, row, col },
            target_dir: PathBuf::new(),
            error: None,
        });
        true
    }

    pub fn drain_lsp_rename(&mut self) -> bool {
        let mut arrived = false;
        let mut edits: Option<Vec<(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)>> = None;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_rename() {
                if Some(result.request_id) != self.rename_request_id {
                    continue;
                }
                arrived = true;
                edits = result.edits;
            }
        }
        if !arrived {
            return false;
        }
        self.rename_request_id = None;
        match edits {
            Some(files) => match self.apply_rename_edits(&files) {
                Ok((file_count, occ)) => {
                    self.status =
                        format!("Renamed {occ} occurrence(s) across {file_count} file(s)");
                }
                Err(e) => self.status = format!("Rename failed: {e}"),
            },
            None => self.status = String::from("Rename produced no changes"),
        }
        true
    }

    /// Apply an LSP rename `WorkspaceEdit` (already normalised to per-file
    /// char-indexed spans). Open tabs are edited in-memory as one undo step
    /// and left dirty; closed files are rewritten on disk (the fs watcher
    /// refreshes the tree). Returns (files touched, occurrences replaced).
    fn apply_rename_edits(
        &mut self,
        files: &[(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)],
    ) -> Result<(usize, usize)> {
        let mut file_count = 0;
        let mut occ_count = 0;
        for (path, edits) in files {
            if edits.is_empty() {
                continue;
            }
            if let Some(n) = self.editor.apply_rename_to_open_tab(path, edits) {
                occ_count += n;
            } else if self.is_collab_guest() && collab_file_key(&self.tree.root, path).is_some() {
                // Closed-file rename edits are raw disk writes; a collab
                // guest never writes shared files (open tabs above are fine:
                // those edits flow to the owner as ops).
                continue;
            } else {
                let content = std::fs::read_to_string(path)?;
                let mut lines: Vec<String> = content.split('\n').map(str::to_string).collect();
                occ_count += crate::widgets::editor::apply_span_edits_to_lines(&mut lines, edits);
                std::fs::write(path, lines.join("\n"))?;
            }
            file_count += 1;
        }
        Ok((file_count, occ_count))
    }

    /// VS Code "Format Document" (Cmd+Opt+Shift+F): ask the language server to
    /// reformat the active buffer. No-op on read-only diff / sheet / image
    /// tabs. The reply is applied in [`drain_lsp_format`].
    fn start_format_document(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            self.status = String::from("No language server for this file");
            return;
        };
        // Mirror the editor's indentation preference; servers that carry their
        // own config (rustfmt, ruff, prettier) ignore these but the fields are
        // required by the LSP request.
        let (tab_size, insert_spaces) = self.editor.indent_preference();
        let id = lsp.request_formatting(path, tab_size, insert_spaces);
        self.format_request_id = Some(id);
        self.format_request_selection = false;
        self.status = String::from("Formatting document");
    }

    /// "Format Selection" (#254): `textDocument/rangeFormatting` over the
    /// primary selection, applied through the same reply path as
    /// whole-document formatting.
    fn format_selection(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        let Some(sel) = self.editor.selection.filter(|s| s.has_area()) else {
            self.status = String::from("Select something to format");
            return;
        };
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return;
        };
        let ((sr, sc), (er, ec)) = sel.normalised();
        let start = self.editor.pos_to_utf16(sr, sc);
        let end = self.editor.pos_to_utf16(er, ec);
        let (tab_size, insert_spaces) = self.editor.indent_preference();
        let Some(lsp) = self.lsp.as_mut() else {
            self.status = String::from("No language server for this file");
            return;
        };
        let id = lsp.request_range_formatting(path, start, end, tab_size, insert_spaces);
        self.format_request_id = Some(id);
        self.format_request_selection = true;
        self.status = String::from("Formatting selection");
    }

    pub fn drain_lsp_format(&mut self) -> bool {
        let mut arrived = false;
        let mut edits: Option<Vec<crate::widgets::editor::TextSpanEdit>> = None;
        let mut unsupported = false;
        let mut path: Option<PathBuf> = None;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_formatting() {
                if Some(result.request_id) != self.format_request_id {
                    continue;
                }
                arrived = true;
                edits = result.edits;
                unsupported = result.unsupported;
                path = Some(result.path);
            }
        }
        if !arrived {
            return false;
        }
        self.format_request_id = None;
        let selection = std::mem::take(&mut self.format_request_selection);
        if unsupported {
            self.status = if selection {
                String::from("No range formatter available for this file")
            } else {
                String::from("No formatter available for this file")
            };
            self.complete_pending_save();
            return true;
        }
        match (edits, path) {
            (Some(edits), Some(path)) if !edits.is_empty() => {
                match self.editor.apply_rename_to_open_tab(&path, &edits) {
                    Some(_) => {
                        self.editor.clamp_cursor();
                        self.status = if selection {
                            String::from("Formatted selection")
                        } else {
                            String::from("Formatted document")
                        };
                    }
                    None => self.status = String::from("Format failed: document not open"),
                }
            }
            _ => {
                self.status = if selection {
                    String::from("Selection already formatted")
                } else {
                    String::from("Document already formatted")
                }
            }
        }
        // A format-on-save write is deferred until now so the disk file gets the
        // formatted text in one go.
        self.complete_pending_save();
        true
    }

    /// VS Code "Quick Fix" (`Cmd+.`): ask the language server for the code
    /// actions available at the cursor (with the diagnostics on that line as
    /// context) and present them in a picker. No-op on read-only preview tabs.
    /// The reply is handled in [`Self::drain_lsp_code_actions`].
    /// The Quick Fix picker for a merge conflict at the cursor: VS Code's
    /// three accept actions, applied locally with no LSP involvement.
    /// F7 / Shift+F7: move the caret to the next / previous conflict header,
    /// wrapping, and say which of how many the caret landed on.
    fn jump_conflict(&mut self, backwards: bool) {
        let blocks = self.editor.conflicts().to_vec();
        let from = self.editor.cursor_row;
        let hit = if backwards {
            crate::merge::prev_conflict(&blocks, from)
        } else {
            crate::merge::next_conflict(&blocks, from)
        };
        let Some((idx, row)) = hit else {
            return;
        };
        self.editor.clear_selection();
        self.editor.cursor_row = row;
        self.editor.cursor_col = 0;
        self.editor.scroll_col = 0;
        self.editor.ensure_cursor_col_visible();
        self.status = format!("Conflict {} of {}", idx + 1, blocks.len());
    }

    fn open_merge_conflict_picker(&mut self) {
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let rows = vec![
            ListRow {
                id: String::from("current"),
                label: String::from("Accept Current Change"),
            },
            ListRow {
                id: String::from("incoming"),
                label: String::from("Accept Incoming Change"),
            },
            ListRow {
                id: String::from("both"),
                label: String::from("Accept Both Changes"),
            },
        ];
        self.open_list_picker(
            ListPicker::new(ListPurpose::MergeConflict, "Resolve Merge Conflict", rows),
            "No merge conflict at the cursor",
        );
    }

    /// Resolve the merge conflict at the cursor, reporting VS Code's
    /// wording in the status line. Backs both the palette's Merge Conflict
    /// commands and the Quick Fix picker rows.
    fn resolve_merge_at_cursor(&mut self, res: crate::merge::Resolution) {
        // Palette commands reach here on any tab; a non-text view (image,
        // sheet, diff) must refuse rather than consult the conflict cache.
        if !self.editor_is_text() {
            self.status = String::from("Merge conflict actions need a text file");
            return;
        }
        let row = self.editor.cursor_row;
        if !self.editor.resolve_conflict_at(row, res) {
            self.status = String::from("No merge conflict at the cursor");
            return;
        }
        let accepted = match res {
            crate::merge::Resolution::Current => "Accepted current change",
            crate::merge::Resolution::Incoming => "Accepted incoming change",
            crate::merge::Resolution::Both => "Accepted both changes",
        };
        self.status = if self.editor.conflicts().is_empty() {
            format!(
                "{accepted} — all conflicts resolved; \"Merge: Complete Merge\" stages the file"
            )
        } else {
            format!("{accepted} — {} left", self.editor.conflicts().len())
        };
    }

    /// VS Code's "Accept All Current / Incoming": resolve every block in the
    /// buffer the same way, back to front so each replacement is one undo
    /// step and earlier block indices stay valid.
    fn resolve_all_merge(&mut self, res: crate::merge::Resolution) {
        if !self.editor_is_text() {
            self.status = String::from("Merge conflict actions need a text file");
            return;
        }
        let total = self.editor.conflicts().len();
        if total == 0 {
            self.status = String::from("No merge conflicts in this file");
            return;
        }
        while let Some(block) = self.editor.conflicts().last().copied() {
            if !self.editor.resolve_conflict_at(block.ours_start, res) {
                break;
            }
        }
        let side = match res {
            crate::merge::Resolution::Current => "current",
            crate::merge::Resolution::Incoming => "incoming",
            crate::merge::Resolution::Both => "both sides",
        };
        self.status = format!(
            "Accepted {side} for {total} conflict{} — \"Merge: Complete Merge\" stages the file",
            if total == 1 { "" } else { "s" }
        );
    }

    /// VS Code's "Complete Merge": once every block is resolved, persist the
    /// buffer and stage the file so it leaves MERGE CONFLICTS and rejoins the
    /// ordinary commit flow. Refuses while conflicts remain.
    fn complete_merge(&mut self) {
        if !self.editor_is_text() {
            self.status = String::from("Merge conflict actions need a text file");
            return;
        }
        // Merge editor (#253): the Result has no markers, so the gate is
        // the tracked regions, not the marker scan below.
        if self.editor.merge.is_some() {
            self.merge_view_sync();
            let unresolved = self
                .editor
                .merge
                .as_ref()
                .map(|mv| mv.unresolved_count())
                .unwrap_or(0);
            if unresolved > 0 {
                self.status = format!(
                    "{unresolved} conflict{} still unresolved — F7 jumps to the next one",
                    if unresolved == 1 { "" } else { "s" }
                );
                return;
            }
        }
        let left = self.editor.conflicts().len();
        if left > 0 {
            self.status = format!(
                "{left} conflict{} still unresolved — F7 jumps to the next one",
                if left == 1 { "" } else { "s" }
            );
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return;
        };
        if self.editor.dirty {
            self.save();
        }
        // Canonicalize before the relative-path strip: a workspace under
        // a symlink (macOS /var → /private/var) otherwise falls back to
        // the absolute path, which reads wrong in the status and would
        // refuse in stricter git contexts.
        let merge_root = self
            .roots
            .owning_root(&path)
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf();
        let canon_root = std::fs::canonicalize(&merge_root).unwrap_or_else(|_| merge_root.clone());
        let canon_path = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
        let rel = canon_path
            .strip_prefix(&canon_root)
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|_| self.status_path(&path));
        match crate::git::stage_path(&canon_root, &rel) {
            Ok(()) => {
                self.refresh_source_control();
                self.status = format!("Merge complete: staged {rel}");
            }
            Err(e) => self.status = format!("Stage failed: {e}"),
        }
    }

    /// Open the three-way merge editor (#253) for `path`. Inputs come
    /// from the git index stages (`:1:` base, `:2:` ours, `:3:` theirs)
    /// when the path is unmerged; otherwise the sides are synthesized
    /// from conflict markers in the file itself, so the editor also
    /// works on a plain marker file outside any merge. The tab is opened
    /// through the normal text route first (language, LSP, undo all
    /// attach), then the buffer is transformed into the initial Result
    /// in one undo step — the marker text stays one Undo away.
    fn open_merge_editor_for(&mut self, path: &Path) -> bool {
        // Stage specs are repo-toplevel-relative (#139): see `repo_rel`.
        let root = self.scm_root();
        let canon_root = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone());
        let rel = self.repo_rel(path);
        let to_lines = |s: String| -> Vec<String> { s.lines().map(str::to_string).collect() };
        let ours = crate::git::read_file_at_stage(&canon_root, &rel, 2).map(to_lines);
        let theirs = crate::git::read_file_at_stage(&canon_root, &rel, 3).map(to_lines);
        let sides = match (ours, theirs) {
            // Neither stage exists: the path is not unmerged in git at
            // all — fall through to marker synthesis below.
            (Err(_), Err(_)) => None,
            // Unmerged: a missing single stage is a deleted side (DU/UD)
            // and a missing base is added-by-both (AA) — both mean "that
            // side is empty", not an error.
            (o, t) => {
                let base = crate::git::read_file_at_stage(&canon_root, &rel, 1)
                    .map(&to_lines)
                    .unwrap_or_default();
                Some((base, o.unwrap_or_default(), t.unwrap_or_default()))
            }
        };
        let built = match sides {
            Some((base, ours, theirs)) => Some(crate::merge_editor::MergeView::new(
                base, ours, theirs, false,
            )),
            None => std::fs::read_to_string(path).ok().and_then(|text| {
                let lines: Vec<String> = text.lines().map(str::to_string).collect();
                crate::merge_editor::view_from_markers(&lines)
            }),
        };
        let Some((mut mv, result)) = built else {
            self.status = format!("{rel} has no merge conflicts");
            return false;
        };
        if let Err(e) = self.editor.open_pinned(path) {
            self.status = format!("Open failed: {e}");
            return false;
        }
        self.focus_pane(Pane::Editor);
        let end = self.editor.lines.len();
        self.editor.splice_result_rows(0, end, result);
        mv.synced_len = self.editor.lines.len();
        mv.synced_seq = self.editor.edit_seq;
        let n = mv.conflicts.len();
        let first = mv.conflicts.first().map(|c| c.result_start);
        mv.anchor_panes_on(0);
        self.editor.merge = Some(mv);
        if let Some(row) = first {
            self.editor.clear_selection();
            self.editor.cursor_row = row.min(self.editor.lines.len().saturating_sub(1));
            self.editor.cursor_col = 0;
            self.editor.ensure_cursor_col_visible();
        }
        self.status = format!(
            "Merge editor: {n} conflict{} — F7 jumps, checkboxes or Merge commands accept, \"Reopen as Text\" for the marker flow",
            if n == 1 { "" } else { "s" }
        );
        true
    }

    /// `path` relative to the repo toplevel, both sides canonicalized —
    /// a workspace under a symlink (macOS /var → /private/var) otherwise
    /// fails the strip and yields an absolute "relative" path, which git
    /// stage specs refuse and status messages shouldn't show.
    fn repo_rel(&self, path: &Path) -> String {
        let root = self.scm_root();
        let canon_root = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone());
        let canon_path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        canon_path
            .strip_prefix(&canon_root)
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|_| self.status_path(path))
    }

    /// Reconcile the merge view's tracked regions with any buffer edit it
    /// has not seen yet (the render loop does this each frame; command
    /// paths call it first so they also work headless, e.g. under test).
    fn merge_view_sync(&mut self) {
        let (len, seq, row) = (
            self.editor.lines.len(),
            self.editor.edit_seq,
            self.editor.merge_edit_row,
        );
        if let Some(mv) = self.editor.merge.as_mut() {
            mv.sync_with_buffer(len, seq, row);
        }
    }

    /// The conflict an accept action targets: the one under the cursor,
    /// else the one navigation last landed on.
    fn merge_target_conflict(&self) -> Option<usize> {
        let mv = self.editor.merge.as_ref()?;
        mv.conflict_at_result_row(self.editor.cursor_row)
            .or_else(|| (mv.active < mv.conflicts.len()).then_some(mv.active))
    }

    /// Set conflict `idx` to `state`, splicing its replacement into the
    /// Result as one undo step and updating the tracked regions.
    fn merge_set_conflict(&mut self, idx: usize, state: crate::merge_editor::ConflictState) {
        self.merge_view_sync();
        let Some(mv) = self.editor.merge.as_ref() else {
            return;
        };
        let Some(c) = mv.conflicts.get(idx) else {
            return;
        };
        let (start, end) = (c.result_start, c.result_start + c.result_len);
        let repl = c.replacement(state);
        let new_len = repl.len();
        self.editor.splice_result_rows(start, end, repl);
        let (len, seq) = (self.editor.lines.len(), self.editor.edit_seq);
        let mv = self.editor.merge.as_mut().expect("checked above");
        mv.note_accept(idx, new_len, state, len, seq);
        let (resolved, total) = (mv.resolved_count(), mv.conflicts.len());
        self.status = format!(
            "Conflict {} of {total}: {} ({resolved}/{total} resolved)",
            idx + 1,
            match state {
                crate::merge_editor::ConflictState::Current => "accepted current",
                crate::merge_editor::ConflictState::Incoming => "accepted incoming",
                crate::merge_editor::ConflictState::Both => "accepted both (current first)",
                crate::merge_editor::ConflictState::BothReverse => "accepted both (incoming first)",
                crate::merge_editor::ConflictState::Base => "kept base",
                crate::merge_editor::ConflictState::Unresolved => "back to unresolved",
                crate::merge_editor::ConflictState::Manual => "manual",
            }
        );
    }

    /// Accept-action entry for the palette commands: target the cursor's
    /// conflict (falling back to the active one).
    fn merge_apply(&mut self, state: crate::merge_editor::ConflictState) {
        self.merge_view_sync();
        match self.merge_target_conflict() {
            Some(idx) => self.merge_set_conflict(idx, state),
            None => self.status = String::from("No conflict at the cursor — F7 jumps to one"),
        }
    }

    /// Accept every remaining unresolved conflict as `state` (the
    /// Accept-All commands in the merge editor).
    fn merge_accept_all(&mut self, state: crate::merge_editor::ConflictState) {
        self.merge_view_sync();
        let Some(mv) = self.editor.merge.as_ref() else {
            return;
        };
        // Back-to-front so earlier indices' spans stay valid inside each
        // splice's own bookkeeping (note_accept shifts only later ones).
        let targets: Vec<usize> = (0..mv.conflicts.len())
            .rev()
            .filter(|&i| !mv.conflicts[i].state.resolved())
            .collect();
        let n = targets.len();
        for idx in targets {
            self.merge_set_conflict(idx, state);
        }
        let total = self
            .editor
            .merge
            .as_ref()
            .map(|m| m.conflicts.len())
            .unwrap_or(0);
        self.status = format!(
            "Accepted {n} conflict{} ({total} total)",
            if n == 1 { "" } else { "s" }
        );
    }

    /// Checkbox click: toggle one side's inclusion, VS Code's model —
    /// both checked is Accept Combination, neither reverts to base.
    fn merge_toggle_side(&mut self, idx: usize, side: crate::merge_editor::CheckSide) {
        use crate::merge_editor::{CheckSide, ConflictState as S};
        let Some(mv) = self.editor.merge.as_ref() else {
            return;
        };
        let Some(c) = mv.conflicts.get(idx) else {
            return;
        };
        let (mut cur, mut inc) = match c.state {
            S::Current => (true, false),
            S::Incoming => (false, true),
            S::Both | S::BothReverse => (true, true),
            S::Unresolved | S::Base | S::Manual => (false, false),
        };
        match side {
            CheckSide::Current => cur = !cur,
            CheckSide::Incoming => inc = !inc,
        }
        let state = match (cur, inc) {
            (true, false) => S::Current,
            (false, true) => S::Incoming,
            (true, true) => S::Both,
            (false, false) => S::Unresolved,
        };
        self.merge_set_conflict(idx, state);
    }

    /// F7 / Shift+F7 in the merge editor: hop conflicts in the Result and
    /// re-anchor every source pane on the same conflict.
    fn merge_jump(&mut self, backwards: bool) {
        self.merge_view_sync();
        let row = self.editor.cursor_row;
        let Some(mv) = self.editor.merge.as_mut() else {
            return;
        };
        let Some(idx) = mv.next_conflict(row, backwards) else {
            self.status = String::from("No conflicts");
            return;
        };
        mv.anchor_panes_on(idx);
        let target = mv.conflicts[idx].result_start;
        let total = mv.conflicts.len();
        self.editor.clear_selection();
        self.editor.cursor_row = target.min(self.editor.lines.len().saturating_sub(1));
        self.editor.cursor_col = 0;
        self.editor.ensure_cursor_col_visible();
        self.status = format!("Conflict {} of {total}", idx + 1);
    }

    fn start_code_action(&mut self) {
        if self.editor.has_non_text_view() {
            return;
        }
        // A merge conflict at the cursor takes the Quick Fix over LSP code
        // actions, like VS Code's Accept Current / Incoming / Both lenses:
        // resolving markers is what the user wants there, and it needs no
        // server round-trip.
        let cursor_row = self.editor.cursor_row;
        if crate::merge::conflict_containing(self.editor.conflicts(), cursor_row).is_some() {
            self.open_merge_conflict_picker();
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return;
        };
        // `row`/`col` go to the server, so the column must be UTF-16;
        // `diagnostics_in_line_range` takes a plain row and is unaffected.
        let (row, col) = self
            .editor
            .pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
        let diagnostics = self.editor.diagnostics_in_line_range(row, row);
        let Some(lsp) = self.lsp.as_mut() else {
            self.status = String::from("No language server for this file");
            return;
        };
        let id = lsp.request_code_action(path, row, col, row, col, diagnostics);
        self.code_action_request_id = Some(id);
        self.code_action_pending_resolve = false;
        self.status = String::from("Finding quick fixes");
    }

    pub fn drain_lsp_code_actions(&mut self) -> bool {
        let mut arrived = false;
        let mut items: Option<Vec<crate::lsp::manager::CodeActionItem>> = None;
        let mut unsupported = false;
        {
            let Some(lsp) = self.lsp.as_ref() else {
                return false;
            };
            while let Some(result) = lsp.drain_code_action() {
                if Some(result.request_id) != self.code_action_request_id {
                    continue;
                }
                arrived = true;
                items = result.items;
                unsupported = result.unsupported;
            }
        }
        if !arrived {
            return false;
        }
        self.code_action_request_id = None;
        let was_resolve = std::mem::take(&mut self.code_action_pending_resolve);
        if unsupported {
            // No code-action server, but a seated navigator can still take
            // the diagnostic under the caret (#374).
            if self.navigator_fix_candidate().is_some() {
                self.open_code_action_picker(Vec::new());
            } else {
                self.status = String::from("No quick fixes: no code-action server for this file");
            }
            return true;
        }
        // A resolve reply carries the one action the user already chose, now with
        // its edit filled in: apply it directly instead of re-opening a menu.
        if was_resolve {
            match items.and_then(|mut v| v.pop()) {
                Some(item) => self.apply_resolved_code_action(item),
                None => self.status = String::from("Quick fix could not be resolved"),
            }
            return true;
        }
        match items {
            Some(items) if items.len() == 1 && items[0].needs_resolve => {
                // A single resolve-only action (e.g. a deferred auto-import):
                // resolve it straight away rather than popping a one-row menu.
                self.resolve_and_apply_code_action(items.into_iter().next().unwrap());
            }
            Some(items) if !items.is_empty() => self.open_code_action_picker(items),
            // Nothing from the server: the navigator entry alone, when a
            // diagnostic sits under the caret (#374).
            _ if self.navigator_fix_candidate().is_some() => {
                self.open_code_action_picker(Vec::new());
            }
            _ => self.status = String::from("No quick fixes available here"),
        }
        true
    }

    /// Present the available code actions in the shared list picker, tagging
    /// each row with its index into `pending_code_actions`. When a diagnostic
    /// sits under the caret, one more row follows the server's: Fix with
    /// Navigator (#374), at index `items.len()`, offered whether or not a
    /// navigator is seated (the action says so if none is).
    fn open_code_action_picker(&mut self, items: Vec<crate::lsp::manager::CodeActionItem>) {
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let mut rows: Vec<ListRow> = items
            .iter()
            .enumerate()
            .map(|(i, item)| ListRow {
                id: i.to_string(),
                label: if item.is_preferred {
                    format!("{} (preferred)", item.title)
                } else {
                    item.title.clone()
                },
            })
            .collect();
        if self.navigator_fix_candidate().is_some() {
            rows.push(ListRow {
                id: String::from("navigator"),
                label: String::from("Fix with Navigator"),
            });
        }
        self.pending_code_actions = items;
        self.open_list_picker(
            ListPicker::new(ListPurpose::CodeAction, "Quick Fix", rows),
            "No quick fixes available here",
        );
    }

    /// Apply the chosen code action: edits first (as one undo step, like rename),
    /// then any command. A resolve-only action is sent for resolution first; its
    /// resolved edit/command arrives back through [`Self::drain_lsp_code_actions`].
    fn apply_code_action(&mut self, item: crate::lsp::manager::CodeActionItem) {
        if item.needs_resolve {
            self.resolve_and_apply_code_action(item);
            return;
        }
        self.apply_resolved_code_action(item);
    }

    /// Apply an action that already carries its edit / command (the leaf of both
    /// the direct and the post-resolve paths). Never re-resolves, so a server
    /// that returns a still-edit-less action after resolve can't loop.
    fn apply_resolved_code_action(&mut self, item: crate::lsp::manager::CodeActionItem) {
        let mut applied = false;
        if !item.edits.is_empty() {
            match self.apply_rename_edits(&item.edits) {
                Ok((files, occ)) => {
                    applied = true;
                    self.status = format!(
                        "{}: changed {occ} edit(s) across {files} file(s)",
                        item.title
                    );
                }
                Err(e) => {
                    self.status = format!("Quick fix failed: {e}");
                    return;
                }
            }
        }
        if let Some(cmd) = item.command
            && let (Some(path), Some(lsp)) = (self.editor.path.clone(), self.lsp.as_mut())
        {
            lsp.execute_command(path, cmd.command, cmd.arguments);
            applied = true;
            self.status = format!("Applied quick fix: {}", item.title);
        }
        if !applied {
            self.status = format!("Quick fix had no effect: {}", item.title);
        }
    }

    /// Send a resolve-only action for `codeAction/resolve`; the resolved item
    /// comes back as a single-item reply that the drain applies.
    fn resolve_and_apply_code_action(&mut self, item: crate::lsp::manager::CodeActionItem) {
        let Some(action) = item.resolve_action else {
            self.status = format!("Quick fix cannot be resolved: {}", item.title);
            return;
        };
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(lsp) = self.lsp.as_mut() else {
            return;
        };
        let id = lsp.request_code_action_resolve(path, item.server, action);
        self.code_action_request_id = Some(id);
        self.code_action_pending_resolve = true;
        self.status = String::from("Resolving quick fix");
    }

    /// Route the key through the completion popup when one is open.
    /// Up/Down navigate, Enter/Tab accept and replace the typed prefix
    /// with the chosen completion's full text, Esc dismisses. Printable
    /// chars and Backspace pass through to the editor and refresh the
    /// popup's filter prefix in place; if no items match the new prefix
    /// the popup dismisses on the next tick.
    fn handle_completion_popup_key(&mut self, key: KeyEvent) -> bool {
        if self.completion_popup.is_none() {
            return false;
        }
        match key.code {
            KeyCode::Up => {
                if let Some(p) = self.completion_popup.as_mut() {
                    p.move_up();
                }
                true
            }
            KeyCode::Down => {
                if let Some(p) = self.completion_popup.as_mut() {
                    p.move_down();
                }
                true
            }
            KeyCode::Enter | KeyCode::Tab => {
                let prefix_len = self
                    .completion_popup
                    .as_ref()
                    .map(|p| p.prefix.chars().count())
                    .unwrap_or(0);
                let text = self
                    .completion_popup
                    .as_ref()
                    .and_then(|p| p.selected_label());
                let is_snippet = self
                    .completion_popup
                    .as_ref()
                    .is_some_and(|p| p.selected_is_snippet());
                self.completion_popup = None;
                self.completion_request_id = None;
                if let Some(t) = text {
                    if is_snippet {
                        // The body carries $1/$0 tab stops; expand_snippet
                        // removes the typed prefix itself and drives the caret.
                        self.editor.expand_snippet(&t, prefix_len);
                    } else {
                        for _ in 0..prefix_len {
                            self.editor.backspace();
                        }
                        // An accepted completion is the SERVER's text, not
                        // the user's: they picked it from a list rather than
                        // writing it (#349).
                        self.editor
                            .insert_str_as(&t, crate::provenance::Seat::Generated);
                    }
                }
                true
            }
            KeyCode::Esc => {
                self.completion_popup = None;
                self.completion_request_id = None;
                true
            }
            KeyCode::Backspace => {
                self.editor.backspace();
                self.refresh_completion_prefix();
                true
            }
            KeyCode::Char(c) => {
                if key.modifiers.contains(KeyModifiers::CONTROL)
                    || key.modifiers.contains(KeyModifiers::ALT)
                    || key.modifiers.contains(KeyModifiers::SUPER)
                {
                    self.completion_popup = None;
                    self.completion_request_id = None;
                    return false;
                }
                self.editor.insert_char(c);
                self.refresh_completion_prefix();
                if !is_word_continuation(c) {
                    self.completion_popup = None;
                    self.completion_request_id = None;
                }
                if is_signature_help_trigger(c) {
                    self.trigger_signature_help();
                }
                true
            }
            _ => {
                self.completion_popup = None;
                self.completion_request_id = None;
                false
            }
        }
    }

    fn refresh_completion_prefix(&mut self) {
        let prefix = self.editor.word_before_cursor();
        let Some(popup) = self.completion_popup.as_mut() else {
            return;
        };
        popup.set_prefix(prefix);
        if popup.visible_is_empty() {
            self.completion_popup = None;
            self.completion_request_id = None;
        }
    }

    fn drain_fs_events(&mut self) -> bool {
        let init_changed = self.try_install_pending_init();
        let mut drain = self.fs_watch.drain(&mut self.tree, &self.editor);
        for w in &mut self.fs_watch_extra {
            let d = w.drain(&mut self.tree, &self.editor);
            drain.got_any |= d.got_any;
            drain.touched_open_file |= d.touched_open_file;
            drain.dirs_changed |= d.dirs_changed;
            drain.finder_relevant |= d.finder_relevant;
            // A secondary root's writes are an agent's writes too: dropping
            // them here would silently give a multi-root workspace an empty
            // review queue for every folder but the first (#345).
            drain.changed_files.extend(d.changed_files);
            drain.rescan_dropped_events |= d.rescan_dropped_events;
        }
        if drain.dirs_changed {
            self.refresh_git_status_debounced();
            if drain.finder_relevant {
                self.kick_file_finder_index_rebuild();
            }
        }
        // `touched_open_file` only tracks the ACTIVE tab; a background tab's
        // file change still arrives as a watcher event (got_any), so sweep
        // every tab whenever any event lands. The sweep is stamp-based, so
        // a benign Access/Metadata event that didn't move mtime+len is a
        // no-op and won't clobber selection or reload spuriously.
        if drain.got_any {
            self.reload_open_file_after_external_change();
            // An open diff view follows the file the same way a buffer does
            // (#471): an agent rewriting the working file, or a save from a
            // sibling tab, re-diffs it in place.
            self.refresh_open_diff_views(false, &[], &drain.changed_files);
        }
        // Attribute the writes to whichever agents were working when they
        // landed (#345). Done after the reload so an agent's write to the
        // ACTIVE tab is hashed from the content the user is about to see.
        if !drain.changed_files.is_empty()
            && self.attribute_writes_to_working_agents(&drain.changed_files)
        {
            // Only when the ledger actually moved: the Explorer's dots must
            // match it, and a decoration that lags is worse than none.
            self.sync_agent_lane_decorations();
        }
        // A rescan means the watcher dropped events, so the queue is a
        // LOWER BOUND from here until it is emptied (#345). Recorded in the
        // ledger rather than only announced: a status line the next
        // keystroke clears would leave a partial queue looking complete.
        // Unconditional on whether an agent is working right now — the
        // dropped writes may have landed a moment ago, while the pane's
        // sampled status has since flipped to idle.
        if drain.rescan_dropped_events {
            self.agent_ledger.note_dropped_events();
            if !self.working_agents().is_empty() {
                self.status = String::from(
                    "File watcher overflowed: some agent changes may be missing from the review queue",
                );
            }
        }
        let polled = self.poll_filesystem_changes();
        drain.got_any || init_changed || polled
    }

    fn cycle_focus(&mut self) {
        // Skip hidden panes when cycling.
        let mut next = self.focus;
        for _ in 0..3 {
            next = match next {
                Pane::Tree => Pane::Editor,
                Pane::Editor => Pane::Terminal,
                Pane::Terminal => Pane::Tree,
            };
            if self.pane_visible(next) {
                break;
            }
        }
        // Through `focus_pane`, never a bare assignment: every route into a
        // pane shares its guarantees (terminal find/copy-mode teardown, and
        // restoring the editor from under a maximized terminal).
        self.focus_pane(next);
    }

    /// Returns true exactly once after the welcome OSC-1337 image has been
    /// emitted and the editor pane has stopped being blank (i.e. a file is
    /// now open). The caller — the main draw loop — must respond by
    /// invalidating the prev buffer so ratatui repaints every cell on the
    /// next draw, wiping iTerm's image cache for the welcome region.
    pub fn consume_welcome_image_clear(&mut self) -> bool {
        let opened_file = !self.editor.is_blank_initial();
        self.overlays.welcome.consume_clear_or(opened_file)
    }

    fn render_welcome(&mut self, frame: &mut ratatui::Frame, outer_area: Rect) {
        if outer_area.width == 0 || outer_area.height == 0 {
            return;
        }
        // In iTerm2 image mode we let the iTerm session bg (forced to
        // sRGB(EDITOR_BG_RGB) by `SetColors=bg=srgb:…` at startup) show
        // through the welcome cells via SGR 49 (default bg). The OSC-1337
        // PNG canvas is filled with the same sRGB hex, so both surfaces
        // display the same physical pixel — no Generic-RGB vs sRGB seam.
        // Outside iTerm we fall back to explicit truecolor since there's
        // no PNG to match against.
        let bg = if crate::iterm2_inline::detect_iterm2_inline_support() {
            Style::default().bg(Color::Reset)
        } else {
            Style::default().bg(self.theme.editor_bg())
        };
        // Paint a full bordered box around the welcome area so the editor
        // pane has the same visible envelope as when a file is open
        // (Borders::ALL on the editor widget). Without this, the welcome
        // bg bleeds into the tree, the terminal, and the window edge with
        // no perceptible seam — and the sidebar splitter looks
        // unreachable. The bg style is applied to the same block so the
        // inside is filled in one pass. The welcome content then renders
        // into `block.inner(outer_area)` so a tall recents list can never
        // paint over the border rows.
        let outer_block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(Color::DarkGray))
            .style(bg);
        let area = outer_block.inner(outer_area);
        frame.render_widget(outer_block, outer_area);
        if area.width == 0 || area.height == 0 {
            return;
        }
        // Layout-control icons at the welcome screen's top-right, inside the
        // border row — same controls as the editor tab strip (placement A).
        let icon_row = Rect {
            x: outer_area.x + 1,
            y: outer_area.y,
            width: outer_area.width.saturating_sub(2),
            height: 1,
        };
        self.paint_layout_icons(frame, icon_row);

        // Layout regions, top-to-bottom:
        //   [logo + version badge]
        //   [tagline]
        //   [gradient box: header + release highlights]
        //   [footer chevron line]
        let block_left = area.x + area.width / 8;
        let block_right = area.x + area.width - area.width / 8;
        let block_w = block_right.saturating_sub(block_left);
        let has_recent_panel = self.welcome.has_recent_panel();
        let recents_inner_h =
            welcome_recents_height(self.welcome.notes(), welcome_card_inner_width(block_w));
        let tagline_h = 1u16;
        let footer_h = 1u16;
        // Gaps: blank row after logo, after tagline, after box.
        let gaps_h = 3u16;

        let logo_max_w = (area.width as u32).saturating_sub(4) as u16;
        let logo_w_cells = logo_max_w.clamp(8, 48);
        // Box content needs at least the 4-cell border+inset envelope to be
        // worth drawing.
        let desired_box_h = if has_recent_panel {
            recents_inner_h.saturating_add(4)
        } else {
            0
        };
        // Size the card first, then give the logo whatever remains (still
        // capped to its 4..14 band, so the stack can never overrun the
        // fixed-size ratatui buffer). The release note is the panel's
        // information and the logo is decoration: in a height-starved
        // welcome area (a 40-row window with the terminal panel open) the
        // old logo-first order kept a full 14-row logo above a card that
        // was clipped mid-sentence or dropped entirely (#99).
        let logo_h_cells = area
            .height
            .saturating_sub(tagline_h + footer_h + gaps_h)
            .saturating_sub(desired_box_h)
            .clamp(4, 14);
        let used_above_box = logo_h_cells + 1 + tagline_h + 1; // logo, gap, tagline, gap
        let used_below_box = 1 + footer_h; // gap, footer
        let max_box_h = area
            .height
            .saturating_sub(used_above_box)
            .saturating_sub(used_below_box);
        let box_h = desired_box_h.min(max_box_h);

        let total_h = used_above_box + box_h + used_below_box;
        let block_top = area.y + area.height.saturating_sub(total_h) / 2;
        let logo_x = area.x + area.width.saturating_sub(logo_w_cells) / 2;
        let logo_y = block_top;
        let area_max_y = area.y + area.height;

        let desired = WelcomeLayout {
            cell_x: logo_x,
            cell_y: logo_y,
            cell_w: logo_w_cells,
            cell_h: logo_h_cells,
        };

        // Re-bake the OSC-1337 image whenever the layout shifts (resize,
        // sidebar toggle, font size change). The canvas is filled with the
        // raw `EDITOR_BG_RGB` bytes interpreted as sRGB (iTerm2 decodes
        // PNG bytes as sRGB by default). The pane's SGR-painted cells use
        // `Color::Reset` so they fall back to the iTerm session bg, which
        // we force to the same sRGB hex via `SetColors=bg=srgb:…` at
        // startup. Both surfaces therefore display the same physical
        // pixel pair-for-pair.
        if !self.overlays.welcome.layout_matches(&desired) {
            self.overlays.welcome.request_clear_if_displayed();
            if let Some((cw, ch)) = self.cell_pixel {
                let canvas_w = (logo_w_cells as u32) * cw;
                let canvas_h = (logo_h_cells as u32) * ch;
                let bg = self.theme_bg_pixel();
                let protocol = self.inline_protocol;
                // On a light background the asset's white "cr"/"ft"
                // letters would vanish; the ink recolor turns just those
                // pixels dark while the orange/teal strokes pass through.
                let ink = self.theme.is_light().then_some((0x3b_u8, 0x3b_u8, 0x3b_u8));
                if let Ok(baked) = crate::iterm2_inline::fit_image_with_ink(
                    crate::iterm2_inline::WELCOME_LOGO_PNG,
                    canvas_w,
                    canvas_h,
                    bg,
                    ink,
                ) && let Some(raw) = crate::iterm2_inline::build_inline_image(
                    protocol,
                    &baked,
                    logo_w_cells,
                    logo_h_cells,
                    false,
                    crate::iterm2_inline::KITTY_ID_WELCOME,
                ) {
                    let osc = crate::iterm2_inline::maybe_tmux_wrap(
                        protocol,
                        crate::iterm2_inline::detect_tmux(),
                        raw,
                    );
                    self.overlays.welcome.set_image(osc);
                }
            }
            self.overlays.welcome.set_layout(desired);
            self.overlays.welcome.mark_dirty();
        }

        if !self.overlays.welcome.has_image() {
            // Text fallback for non-iTerm2 terminals.
            let label = " croft ";
            let lx = logo_x
                .saturating_add(logo_w_cells.saturating_sub(label.chars().count() as u16) / 2);
            let ly = logo_y + logo_h_cells / 2;
            frame.buffer_mut().set_string(
                lx,
                ly,
                label,
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)))
                    .add_modifier(Modifier::BOLD),
            );
        }

        // Version badge to the right of the wordmark (the wordmark sits
        // in the lower portion of the logo PNG; the badge tracks that row).
        // Plain `vX.Y.Z` (#282). The hash told two builds of one version
        // apart; the drift banner already does that, with an actionable
        // message, at the moment it matters.
        let version_label = format!(" v{} ", env!("CARGO_PKG_VERSION"));
        let version_w = version_label.chars().count() as u16;
        let badge_x = logo_x + logo_w_cells + 1;
        let badge_y = logo_y + (logo_h_cells * 5) / 6;
        if badge_x + version_w + 2 <= area.x + area.width && badge_y + 2 < area_max_y {
            let badge_style = Style::default()
                .fg(self.theme.ui(rgb_color(GRAD_TL)))
                .add_modifier(Modifier::BOLD);
            frame
                .buffer_mut()
                .set_string(badge_x, badge_y, "\u{256d}", badge_style);
            for i in 0..version_w {
                frame
                    .buffer_mut()
                    .set_string(badge_x + 1 + i, badge_y, "\u{2500}", badge_style);
            }
            frame.buffer_mut().set_string(
                badge_x + 1 + version_w,
                badge_y,
                "\u{256e}",
                badge_style,
            );
            frame
                .buffer_mut()
                .set_string(badge_x, badge_y + 1, "\u{2502}", badge_style);
            frame.buffer_mut().set_string(
                badge_x + 1,
                badge_y + 1,
                &version_label,
                Style::default()
                    .fg(self.theme.ui(Color::White))
                    .add_modifier(Modifier::BOLD),
            );
            frame.buffer_mut().set_string(
                badge_x + 1 + version_w,
                badge_y + 1,
                "\u{2502}",
                badge_style,
            );
            frame
                .buffer_mut()
                .set_string(badge_x, badge_y + 2, "\u{2570}", badge_style);
            for i in 0..version_w {
                frame.buffer_mut().set_string(
                    badge_x + 1 + i,
                    badge_y + 2,
                    "\u{2500}",
                    badge_style,
                );
            }
            frame.buffer_mut().set_string(
                badge_x + 1 + version_w,
                badge_y + 2,
                "\u{256f}",
                badge_style,
            );
        }

        // Tagline.
        let tagline_y = logo_y + logo_h_cells + 1;
        let tagline_w = WELCOME_TAGLINE.chars().count() as u16;
        let tagline_x = area.x + area.width.saturating_sub(tagline_w) / 2;
        if tagline_y < area_max_y && tagline_w <= area.width {
            frame.buffer_mut().set_string(
                tagline_x,
                tagline_y,
                WELCOME_TAGLINE,
                Style::default().fg(self.theme.ui(Color::Rgb(0x88, 0xc0, 0xd0))),
            );
        }

        let box_y = tagline_y + tagline_h + 1;
        if has_recent_panel && box_h >= 4 && block_w >= 4 && box_y + box_h <= area_max_y {
            let box_rect = Rect {
                x: block_left,
                y: box_y,
                width: block_w,
                height: box_h,
            };
            if self.theme.is_light() {
                // The brand gradient's teal leg washes out on white; paint
                // the card border in the light widget-border grey instead.
                let border = Style::default().fg(self.theme.ui(Color::Rgb(0x3b, 0x42, 0x52)));
                let b = frame.buffer_mut();
                for x in box_rect.x..box_rect.x + box_rect.width {
                    b.set_string(x, box_rect.y, "\u{2500}", border);
                    b.set_string(x, box_rect.y + box_rect.height - 1, "\u{2500}", border);
                }
                for y in box_rect.y..box_rect.y + box_rect.height {
                    b.set_string(box_rect.x, y, "\u{2502}", border);
                    b.set_string(box_rect.x + box_rect.width - 1, y, "\u{2502}", border);
                }
                b.set_string(box_rect.x, box_rect.y, "\u{256d}", border);
                b.set_string(
                    box_rect.x + box_rect.width - 1,
                    box_rect.y,
                    "\u{256e}",
                    border,
                );
                b.set_string(
                    box_rect.x,
                    box_rect.y + box_rect.height - 1,
                    "\u{2570}",
                    border,
                );
                b.set_string(
                    box_rect.x + box_rect.width - 1,
                    box_rect.y + box_rect.height - 1,
                    "\u{256f}",
                    border,
                );
            } else {
                paint_gradient_box(frame.buffer_mut(), box_rect);
            }

            // Inner content area: 1-cell inset from each border. The width
            // comes from the same helper the height measure used, so the
            // wrap below reproduces exactly the line count the card
            // reserved rows for (#99).
            let inner_x = box_rect.x + 2;
            let inner_y = box_rect.y + 1;
            let inner_w_actual = welcome_card_inner_width(box_rect.width);

            let row_style = Style::default().fg(self.theme.ui(Color::Rgb(0xc5, 0xcd, 0xd9)));

            // Header row: "> IN THIS RELEASE (vX.Y.Z)". The leading chevron
            // echoes the cr<>ft wordmark's bracket. The highlights below are
            // hand-curated data baked into this build (see
            // `crate::release_notes`), so the heading names the exact version.
            let header_y = inner_y;
            frame.buffer_mut().set_string(
                inner_x,
                header_y,
                "> ",
                Style::default()
                    .fg(self.theme.ui(rgb_color(GRAD_TR)))
                    .add_modifier(Modifier::BOLD),
            );
            frame.buffer_mut().set_string(
                inner_x + 2,
                header_y,
                format!("IN THIS RELEASE (v{})", env!("CARGO_PKG_VERSION")),
                Style::default()
                    .fg(self.theme.ui(Color::White))
                    .add_modifier(Modifier::BOLD),
            );

            // Each highlight: a kind glyph in the gutter (rocket = new feature,
            // bug = fix) tinted by kind, then the wrapped one-line summary.
            // Continuation lines align under the summary, leaving the gutter
            // clear so the glyph reads as a single bullet.
            let summary_x = inner_x + WELCOME_NOTE_GUTTER;
            let summary_w = inner_w_actual.saturating_sub(WELCOME_NOTE_GUTTER);
            let last_row = box_rect.y + box_rect.height - 1;
            let mut row_y = header_y + 2;
            for note in self.welcome.notes() {
                if row_y >= last_row {
                    break;
                }
                frame.buffer_mut().set_string(
                    inner_x,
                    row_y,
                    note.kind.icon(),
                    Style::default()
                        .fg(note.kind.color())
                        .add_modifier(Modifier::BOLD),
                );
                let lines = wrapped_welcome_note_summary(note, inner_w_actual);
                for (line_idx, line) in lines.iter().enumerate() {
                    let line_y = row_y + line_idx as u16;
                    if line_y >= last_row {
                        break;
                    }
                    let clipped: String = line.chars().take(summary_w as usize).collect();
                    frame
                        .buffer_mut()
                        .set_string(summary_x, line_y, clipped, row_style);
                }
                row_y = row_y.saturating_add(lines.len().max(1) as u16);
            }
        }
    }

    /// Render the secondary side bar (VS Code's auxiliary bar): the active
    /// file's Outline, on the edge opposite the primary side bar. Reuses the
    /// single `OutlinePanel`, forced expanded for this dedicated panel; its
    /// collapse state is saved/restored so the Explorer's own OUTLINE section
    /// (which may render the same widget afterward) keeps its toggle.
    fn render_secondary_side_bar(&mut self, frame: &mut ratatui::Frame, area: Option<Rect>) {
        let Some(area) = area else {
            return;
        };
        if area.width == 0 || area.height == 0 {
            return;
        }
        // A left border + bg fill so the panel reads as a distinct column,
        // like the primary side bar's seam against the editor.
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::LEFT)
            .border_style(Style::default().fg(self.theme.ui(Color::Rgb(0x2b, 0x2b, 0x2b))))
            .style(Style::default().bg(self.theme.editor_bg()));
        let inner = block.inner(area);
        frame.render_widget(block, area);
        let saved_collapsed = self.outline.collapsed;
        self.outline.collapsed = false;
        self.outline.theme = self.theme;
        self.outline.focus_gradient = self.theme.gradient();
        self.outline.focused = false;
        self.outline.hover_pointer = self.pointer_cell;
        frame.render_widget(&mut self.outline, inner);
        self.outline.collapsed = saved_collapsed;
    }

    /// Paint the three layout-control icons (Toggle Primary Side Bar, Toggle
    /// Panel, Customize Layout) right-aligned on the single-row `row` — the top
    /// of the editor tab strip, or the welcome screen's top edge. croft's
    /// analog of VS Code's title-bar layout controls (placement A). Records the
    /// hit rects in `self.layout_icon_areas`.
    fn paint_layout_icons(&mut self, frame: &mut ratatui::Frame, row: Rect) {
        self.layout_icon_areas = LayoutIconAreas::default();
        let w = LAYOUT_ICON_CELLS_W;
        let stride = w + 1; // one-column gap between icons
        // Three icons + a one-column right pad.
        let needed = stride * 3;
        if row.height == 0 || row.width < needed {
            return;
        }
        let y = row.y;
        let right = row.x + row.width;
        let cust_x = right.saturating_sub(w + 1); // 1-col right pad
        let panel_x = cust_x.saturating_sub(stride);
        let side_x = panel_x.saturating_sub(stride);
        if side_x < row.x {
            return;
        }
        let rect = |x: u16| Rect {
            x,
            y,
            width: w,
            height: LAYOUT_ICON_CELLS_H,
        };
        self.layout_icon_areas = LayoutIconAreas {
            toggle_side_bar: rect(side_x),
            toggle_panel: rect(panel_x),
            customize: rect(cust_x),
        };
        // On an image-capable terminal the post-draw flush paints crisp 2× PNG
        // icons at these cells (see `pending_activity_image_overlays`); the text
        // path below is only the fallback for terminals without inline images.
        if self.overlays.activity.has_images() {
            return;
        }
        let pointer = self.pointer_cell;
        // The codicon shape carries the on/off state (filled vs. hollow), like
        // VS Code; colour brightens to the accent on hover. Glyphs sit centred
        // in the 4-wide slot.
        let base = self.theme.ui(Color::Rgb(0xcc, 0xcc, 0xcc));
        let accent = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
        let mut paint = |x: u16, glyph: char| {
            let hovered = pointer.is_some_and(|(px, py)| py == y && px >= x && px < x + w);
            let color = if hovered { accent } else { base };
            frame.buffer_mut().set_string(
                x + w / 2,
                y,
                glyph.to_string(),
                Style::default().fg(color),
            );
        };
        let side_glyph = if self.show_tree {
            crate::icons::LAYOUT_SIDEBAR_ON
        } else {
            crate::icons::LAYOUT_SIDEBAR_OFF
        };
        let panel_glyph = if self.show_terminal {
            crate::icons::LAYOUT_PANEL_ON
        } else {
            crate::icons::LAYOUT_PANEL_OFF
        };
        paint(side_x, side_glyph);
        paint(panel_x, panel_glyph);
        paint(cust_x, crate::icons::LAYOUT_CUSTOMIZE);
    }

    fn render_activity_bar(&mut self, frame: &mut ratatui::Frame, area: Rect) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        // Keep the per-frame activity badges current before the post-draw flush
        // emits them. Both are count-gated, so a frame with no churn is a cheap
        // no-op. (The SCM badge refreshes off the git worker instead.)
        self.refresh_explorer_unsaved_badge();
        self.refresh_remote_ports_badge();
        self.refresh_testing_badge();
        self.refresh_problems_badge();
        // In images mode the activity bar inherits the iTerm session bg
        // (forced to sRGB(EDITOR_BG_RGB) via SetColors), matching the rest
        // of the panes. The glyph-fallback path keeps a solid bg for
        // terminals that can't render OSC-1337.
        let bg = if self.overlays.activity.has_images() {
            Style::default().bg(Color::Reset)
        } else {
            Style::default().bg(self.theme.editor_bg())
        };
        // In images mode the icon PNG owns the entire activity-bar block —
        // background, codicon, and active pill are baked in. Rendering a bg
        // block here would force a per-cell diff every frame, which in turn
        // would force us to re-emit the OSC-1337 images on every draw. Both
        // are visible to the user. So in images mode we leave the cells
        // untouched and let the post-draw OSC writer paint them once.
        if !self.overlays.activity.has_images() {
            frame.render_widget(ratatui::widgets::Block::default().style(bg), area);
        }
        let active_bar = self.theme.activity_icon_pill();
        let bg_color = bg.bg.unwrap_or(Color::Reset);
        let explorer_block = activity_explorer_block(area);
        let search_block = activity_search_block(area);
        let source_control_block = activity_source_control_block(area);
        let remote_block = activity_remote_block(area);
        let run_debug_block = activity_run_debug_block(area);
        let extensions_block = activity_extensions_block(area);
        let testing_block = activity_testing_block(area);
        let settings_block = activity_settings_block(area);
        let explorer_active = self.sidebar_view == SidebarView::Explorer;
        let search_active = self.sidebar_view == SidebarView::Search;
        let source_control_active = self.sidebar_view == SidebarView::SourceControl;
        let remote_active = self.sidebar_view == SidebarView::Remote;
        let run_debug_active = self.sidebar_view == SidebarView::RunDebug;
        let extensions_active = self.sidebar_view == SidebarView::Extensions;
        let testing_active = self.sidebar_view == SidebarView::Testing;
        let settings_active = self.settings_menu_active();
        // Hover brightens the glyph (like active) but draws no selection pill,
        // mirroring the image path's hovered variant. Selected wins over hover.
        let hov = self.hovered_activity_icon;
        let explorer_hovered = hov == Some(ActivityIcon::Explorer);
        let search_hovered = hov == Some(ActivityIcon::Search);
        let source_control_hovered = hov == Some(ActivityIcon::SourceControl);
        let remote_hovered = hov == Some(ActivityIcon::Remote);
        let run_debug_hovered = hov == Some(ActivityIcon::RunDebug);
        let extensions_hovered = hov == Some(ActivityIcon::Extensions);
        let testing_hovered = hov == Some(ActivityIcon::Testing);
        let settings_hovered = hov == Some(ActivityIcon::Settings);

        // Same palette the baked icons use, so an image-less terminal renders
        // the bar in the same colors as an image-capable one instead of a
        // second, slightly-off set of greys.
        let active_color = self.theme.activity_icon_active();
        let inactive_color = self.theme.activity_icon_inactive();
        let glyph_x = activity_icon_glyph_x(area);
        let render_glyph = |frame: &mut ratatui::Frame,
                            block: Rect,
                            glyph: char,
                            is_active: bool,
                            is_hovered: bool| {
            let mid = block.y + block.height.saturating_sub(1) / 2;
            if is_active {
                let pill = Rect {
                    x: block.x,
                    y: mid,
                    width: 1,
                    height: 1,
                };
                frame.render_widget(
                    ratatui::widgets::Paragraph::new("▎")
                        .style(Style::default().fg(active_bar).bg(bg_color)),
                    pill,
                );
            }
            let cell = Rect {
                x: glyph_x,
                y: mid,
                width: 1,
                height: 1,
            };
            let color = if is_active || is_hovered {
                active_color
            } else {
                inactive_color
            };
            frame.render_widget(
                ratatui::widgets::Paragraph::new(glyph.to_string()).style(
                    Style::default()
                        .fg(color)
                        .bg(bg_color)
                        .add_modifier(Modifier::BOLD),
                ),
                cell,
            );
        };
        // Text analogue of the baked count badge for image-less terminals: an
        // accent cell with the count at the icon's bottom-right corner.
        let badge_bg = self.theme.accent();
        let render_count_badge = |frame: &mut ratatui::Frame, block: Rect, count: usize| {
            if count == 0 {
                return;
            }
            let label = if count > 9 {
                String::from("9+")
            } else {
                count.to_string()
            };
            let w = label.chars().count() as u16;
            frame.render_widget(
                ratatui::widgets::Paragraph::new(label).style(
                    Style::default()
                        .fg(Color::White)
                        .bg(badge_bg)
                        .add_modifier(Modifier::BOLD),
                ),
                Rect {
                    x: block.x + block.width.saturating_sub(w),
                    y: block.y + block.height.saturating_sub(1),
                    width: w,
                    height: 1,
                },
            );
        };

        if !self.overlays.activity.has_images() {
            // Glyph fallback path: render the codicon and a separate active
            // pill on the leftmost column. iTerm2's image path bakes the
            // pill into the PNG itself, so this branch is only used on
            // terminals that can't render OSC-1337.
            render_glyph(
                frame,
                explorer_block,
                crate::icons::ACTIVITY_EXPLORER,
                explorer_active,
                explorer_hovered,
            );
            render_count_badge(frame, explorer_block, self.unsaved_count());
            render_glyph(
                frame,
                search_block,
                crate::icons::ACTIVITY_SEARCH,
                search_active,
                search_hovered,
            );
            render_glyph(
                frame,
                source_control_block,
                crate::icons::ACTIVITY_SOURCE_CONTROL,
                source_control_active,
                source_control_hovered,
            );
            let scm_count = if self.scm_worker().status().in_repo {
                self.source_control.changes_count()
            } else {
                0
            };
            render_count_badge(frame, source_control_block, scm_count);
            render_glyph(
                frame,
                remote_block,
                crate::icons::ACTIVITY_REMOTE,
                remote_active,
                remote_hovered,
            );
            render_count_badge(frame, remote_block, self.ports.forwarded_count());
            render_glyph(
                frame,
                run_debug_block,
                crate::icons::ACTIVITY_RUN_DEBUG,
                run_debug_active,
                run_debug_hovered,
            );
            render_glyph(
                frame,
                extensions_block,
                crate::icons::ACTIVITY_EXTENSIONS,
                extensions_active,
                extensions_hovered,
            );
            render_glyph(
                frame,
                testing_block,
                crate::icons::ACTIVITY_TESTING,
                testing_active,
                testing_hovered,
            );
            render_count_badge(frame, testing_block, self.testing.failed_count());
            if settings_block.width > 0 {
                render_glyph(
                    frame,
                    settings_block,
                    crate::icons::ACTIVITY_SETTINGS,
                    settings_active,
                    settings_hovered,
                );
            }
        }

        self.sidebar_areas.explorer_icon = explorer_block;
        self.sidebar_areas.search_icon = search_block;
        self.sidebar_areas.source_control_icon = source_control_block;
        self.sidebar_areas.remote_icon = remote_block;
        self.sidebar_areas.run_debug_icon = run_debug_block;
        self.sidebar_areas.extensions_icon = extensions_block;
        self.sidebar_areas.testing_icon = testing_block;
        self.sidebar_areas.settings_icon = settings_block;
    }

    fn set_sidebar_view(&mut self, view: SidebarView) {
        // Choosing a sidebar view is a deliberate sidebar action, so it must
        // reveal under auto-hide (#260). No pin is needed: every arm below
        // focuses Pane::Tree, and auto-hide only collapses on a move to the
        // editor or a terminal, so the reveal is not at risk from its own
        // focus move.
        if self.sidebar_view != view {
            self.overlays.activity.mark_dirty();
            // Leaving Search while a scan is in flight: send an
            // empty-query request so the worker cancels the live walker
            // threads instead of letting them keep saturating every core
            // until the scan finishes. The user's hits stay populated for
            // when they come back; only the live work is dropped.
            if self.sidebar_view == SidebarView::Search && view != SidebarView::Search {
                let _ = self
                    .search_query_tx
                    .send(SearchRequest::Query(String::new(), self.search.opts));
            }
            // Leaving Run-Debug after the headline icon was on screen:
            // arm a one-shot `terminal.clear()` so iTerm2 evicts the
            // cached OSC-1337 image cells. Plain SGR overwrites do not
            // reliably evict those cells, but `\x1b[2J` (which
            // `terminal.clear()` emits) does — same gate the welcome
            // wordmark and editor preview pipelines use. The post-draw
            // flush function is silent on the non-Run-Debug path, so
            // nothing stomps the freshly-drawn next sidebar.
            if self.sidebar_view == SidebarView::RunDebug
                && view != SidebarView::RunDebug
                && self.overlays.run_debug.was_emitted()
            {
                self.overlays.run_debug.request_clear();
            }
            // Same eviction trick for the Source Control no-repo hero
            // PNG: leaving Source Control after the image was painted
            // would otherwise leave the cached PNG under whatever
            // sidebar replaces it.
            if self.sidebar_view == SidebarView::SourceControl && view != SidebarView::SourceControl
            {
                self.overlays.hero.request_clear_if_displayed();
            }
            // The Source Control commit dropdown is anchored to that view;
            // close it on any view change so it can't linger over the next
            // sidebar.
            self.commit_menu_open = false;
        }
        self.sidebar_view = view;
        if self.sidebar_view == SidebarView::Remote && self.remote.refresh_if_config_changed() {
            self.status = String::from("Reloaded SSH remotes");
        }
        if !self.show_tree {
            self.show_tree = true; // ensure the side panel is open when switching
        }
        match view {
            SidebarView::Explorer => self.focus_pane(Pane::Tree),
            SidebarView::Search => {
                self.focus_pane(Pane::Tree); // tree pane = side panel; dispatch by view
                self.search.select_all_query();
            }
            SidebarView::SourceControl => {
                self.refresh_source_control();
                self.focus_pane(Pane::Tree);
            }
            SidebarView::Remote => self.focus_pane(Pane::Tree),
            SidebarView::RunDebug => {
                self.refresh_run_debug();
                self.focus_pane(Pane::Tree);
            }
            SidebarView::Extensions => {
                self.refresh_extensions();
                self.focus_pane(Pane::Tree);
            }
            SidebarView::Testing => self.focus_pane(Pane::Tree),
        }
    }

    /// Rebuild the Extensions panel's row list from the bundled + user manifests,
    /// stamping each with its live enabled state from prefs. Called whenever the
    /// view is shown or a toggle flips, so the list always reflects the manifests
    /// on disk and the current disable set.
    fn refresh_extensions(&mut self) {
        let mut vscode: Vec<String> = self
            .roots
            .iter()
            .flat_map(crate::vscode_extensions::workspace_recommendations)
            .collect();
        vscode.extend(self.vscode_listed.iter().cloned());
        let compared = crate::vscode_extensions::compare(vscode);
        let items = build_extension_items(&self.disabled_extensions, &compared);
        self.extensions.set_items(items);
    }

    /// Extensions: Compare with VS Code (#352). Lists what VS Code has
    /// installed (one `code --list-extensions`, which is why it is a command
    /// and not a refresh), merges it with the workspace's recommendations,
    /// and shows the panel with the FROM VS CODE group filled in.
    fn compare_extensions_with_vscode(&mut self) {
        self.vscode_listed = crate::vscode_extensions::installed_via_code();
        self.refresh_extensions();
        self.set_sidebar_view(SidebarView::Extensions);
        let n = self
            .extensions
            .items()
            .iter()
            .filter(|it| it.vscode)
            .count();
        self.status = if self.vscode_listed.is_empty() {
            format!(
                "{n} VS Code extension{} from this workspace's recommendations; `code` was not found on PATH, so the installed list is not included",
                if n == 1 { "" } else { "s" }
            )
        } else {
            format!(
                "{n} VS Code extension{} compared under FROM VS CODE",
                if n == 1 { "" } else { "s" }
            )
        };
    }

    fn pane_visible(&self, p: Pane) -> bool {
        match p {
            Pane::Tree => self.show_tree,
            Pane::Terminal => self.show_terminal,
            Pane::Editor => true,
        }
    }

    fn toggle_terminal(&mut self) {
        self.show_terminal = !self.show_terminal;
        // Hiding the terminal must also clear the maximize flag, otherwise
        // the next time the user reopens the terminal it would still hide
        // the editor — which is surprising because Ctrl+J is the user's
        // mental "show my normal layout again" key.
        if !self.show_terminal {
            self.terminal_maximized = false;
        }
        // If we just hid the terminal while it was focused, fall back to editor.
        if !self.show_terminal && self.focus == Pane::Terminal {
            self.focus_pane(Pane::Editor);
        }
        // If we just showed the terminal, optionally jump focus to it for quick use.
        if self.show_terminal {
            self.focus_pane(Pane::Terminal);
        }
    }

    /// `Ctrl+Shift+J`: flip the maximize-terminal flag. When turning ON,
    /// also ensure the terminal pane is visible and focused so the user
    /// can start typing immediately. When turning OFF, re-arm the welcome
    /// wordmark so it re-paints in the restored editor area.
    fn toggle_terminal_maximize(&mut self) {
        self.terminal_maximized = !self.terminal_maximized;
        if self.terminal_maximized {
            if !self.show_terminal {
                self.show_terminal = true;
            }
            self.focus_pane(Pane::Terminal);
            self.overlays.welcome.request_clear_if_displayed();
        } else {
            self.overlays.welcome.mark_dirty();
        }
    }

    pub fn terminal(&self) -> &PtyTerminal {
        &self.terminals[self.active_terminal]
    }

    pub fn terminal_mut(&mut self) -> &mut PtyTerminal {
        &mut self.terminals[self.active_terminal]
    }

    /// Spawn a new PTY-backed terminal next to the existing ones and make
    /// it the active one. The pane becomes visible if it was hidden. The
    /// new terminal's cwd is the *live* cwd of the active terminal's shell
    /// (so a `cd somewhere` inside the user's prompt is reflected), with
    /// the workspace root as a fallback if we can't resolve it.
    ///
    /// The new terminal lands immediately to the right of the currently
    /// active one, not at the far end of the strip, so the user's mental
    /// model of "the new tab sits next to where I was" matches what they
    /// see. Inserting at the end would scatter related splits across the
    /// row whenever the active terminal wasn't already on the right edge.
    pub fn split_terminal(&mut self) -> Result<()> {
        self.insert_terminal(
            PtyTerminal::new(&self.next_terminal_cwd()).context("spawning terminal")?,
        );
        Ok(())
    }

    /// Open a new pane running a specific shell (a terminal profile) instead of
    /// `$SHELL`. Same placement and focus behaviour as [`split_terminal`].
    pub fn split_terminal_with_shell(&mut self, shell_path: &str) -> Result<()> {
        let cwd = self.next_terminal_cwd();
        self.insert_terminal(
            PtyTerminal::new_shell(shell_path, &cwd).context("spawning terminal")?,
        );
        Ok(())
    }

    /// The cwd a new terminal should inherit: the active terminal's live
    /// directory if it has one, else the workspace root.
    fn next_terminal_cwd(&self) -> PathBuf {
        // The shell's own OSC 7 report (shell integration) beats sampling
        // the process table — it is exact and free of proc-inspection
        // races — but only when the REPORTING host is this machine: an
        // in-pane ssh session names a remote path that would silently
        // resolve to the wrong local directory whenever it exists here.
        self.terminal()
            .local_shell_cwd()
            .filter(|p| p.is_dir())
            .or_else(|| {
                self.terminal()
                    .pid()
                    .and_then(cwd_of_pid)
                    .filter(|p| p.is_dir())
            })
            .unwrap_or_else(|| self.workspace_root().to_path_buf())
    }

    /// Insert `term` just after the active pane, make it active, and reveal the
    /// terminal pane.
    fn insert_terminal(&mut self, term: PtyTerminal) {
        let target = self.active_terminal + 1;
        self.terminals.insert(target, term);
        self.active_terminal = target;
        if !self.show_terminal {
            self.show_terminal = true;
        }
        self.focus_pane(Pane::Terminal);
        self.save_terminal_session();
    }

    /// Set a structural-change status, keeping any latched session-store
    /// failure visible beside it (#158 review: plain assignments right
    /// after a failed save silently hid the persistence error).
    fn terminal_status(&mut self, msg: String) {
        self.status = match &self.terminal_store_error {
            Some(e) => format!("{msg} — session not saved: {e}"),
            None => msg,
        };
    }

    /// Snapshot the terminal panel (pane order, cwds, names, focus) into
    /// the per-workspace session store. Called on structural changes and at
    /// quit; the default single-pane layout prunes the record instead.
    pub fn save_terminal_session(&mut self) {
        let root = self.workspace_root().display().to_string();
        let triggers = self.triggers.clone();
        let panes = self
            .terminals
            .iter()
            .map(|t| crate::terminal_session::PaneRecord {
                cwd: t
                    .local_shell_cwd()
                    .filter(|p| p.is_dir())
                    .or_else(|| t.pid().and_then(cwd_of_pid).filter(|p| p.is_dir()))
                    .unwrap_or_else(|| self.workspace_root().to_path_buf())
                    .display()
                    .to_string(),
                name: t.manual_name().map(str::to_string),
                lane: self.lane_panes.get(&t.uid()).cloned(),
                // The pane's own output, so a restored pane shows what you
                // were doing instead of a blank grid (#249). Trailing blank
                // rows are dropped: a mostly-empty screen would otherwise
                // restore as a wall of nothing.
                transcript: if t.alt_screen() {
                    // A full-screen program's frame is not scrollback: the
                    // alternate screen exists precisely so its contents
                    // vanish on exit. Persisting vim's tildes or htop's
                    // meters and replaying them as inert text above a fresh
                    // prompt would be worse than restoring nothing.
                    // `grid_lines` is the one grid reader here without an
                    // ALT_SCREEN guard of its own, so the check lives here.
                    Vec::new()
                } else {
                    let (lines, _) = t.grid_lines();
                    let end = lines
                        .iter()
                        .rposition(|l| !l.trim().is_empty())
                        .map_or(0, |i| i + 1);
                    let start = end.saturating_sub(crate::terminal_session::TRANSCRIPT_LINES);
                    // Persisted to disk and replayed next launch: every
                    // redact rule applies (#360), as for the dump.
                    lines[start..end]
                        .iter()
                        .map(|l| crate::triggers::mask_text(l, &triggers, false))
                        .collect()
                },
            })
            .collect();
        let record = crate::terminal_session::SessionRecord {
            panes,
            active: self.active_terminal,
        };
        // A corrupt store is refused, never replaced (#157). The error is
        // LATCHED, not just put in the status line: the structural-change
        // call sites set their own success statuses right after this
        // returns, which silently clobbered a transient message (#158
        // review) — terminal_status() re-attaches it to whatever they say.
        self.terminal_store_error =
            crate::terminal_session::save_for_root(&self.terminal_session_path, &root, record)
                .err();
    }

    /// Resurrect this workspace's terminal panel from the session store:
    /// each recorded pane comes back as a fresh shell in its directory
    /// (with its name), and focus returns to the pane that had it. Called
    /// once at startup, replacing the default lone pane. A recorded
    /// directory that no longer exists falls back to the workspace root; a
    /// pane whose shell fails to spawn is skipped.
    pub fn restore_terminal_session(&mut self) {
        let map = crate::terminal_session::load(&self.terminal_session_path);
        let Some(rec) = map.get(&self.workspace_root().display().to_string()) else {
            return;
        };
        let mut terms = Vec::new();
        let mut lanes = std::collections::BTreeMap::new();
        for p in &rec.panes {
            // A lane pane belongs in its worktree, whatever cwd its shell
            // had drifted to at save time (#348): the launch line below is
            // typed into THIS shell, so the directory and the lane are
            // decided together. Deciding them apart seated the agent where
            // the shell had wandered, or, when that cwd was gone, in the
            // PRIMARY repo the fallback names, which is the one directory a
            // lane exists to keep the agent out of. A lane whose worktree
            // is gone is an ordinary pane now.
            let lane = p.lane.as_ref().filter(|l| Path::new(&l.path).is_dir());
            let dir = match lane {
                Some(l) => PathBuf::from(&l.path),
                None => {
                    let dir = PathBuf::from(&p.cwd);
                    if dir.is_dir() {
                        dir
                    } else {
                        self.workspace_root().to_path_buf()
                    }
                }
            };
            // The transcript is painted during the spawn, not after it: a
            // replay that follows the constructor races the new shell's
            // first prompt for the same grid (#249).
            if let Ok(mut t) = PtyTerminal::new_with_transcript(&dir, &p.transcript) {
                t.set_manual_name(p.name.clone());
                // The agent is seated again, from the row's CURRENT launch
                // line, so an edited row applies.
                if let Some(lane) = lane {
                    if let Some(cmd) = lane
                        .agent
                        .as_deref()
                        .and_then(|a| self.agents.launch_line(a))
                    {
                        t.write_input(lane_launch_input(cmd).as_bytes());
                    }
                    lanes.insert(t.uid(), lane.clone());
                }
                terms.push(t);
            }
        }
        if terms.is_empty() {
            return;
        }
        self.lane_panes = lanes;
        // The restored panes are brand-new PtyTerminals, but everything
        // bound to a pane of the OUTGOING panel is keyed by pane index —
        // copy mode, find, quick-select — which an identical index in the
        // restored panel would wrongly satisfy, applying stale grid
        // coordinates to a grid that never produced them. The undo-close
        // park would likewise resurrect an outgoing workspace's PTY into
        // the restored panel. Drop them all before the swap.
        self.close_terminal_copy_mode();
        self.close_terminal_find();
        self.close_terminal_quick_select();
        self.closed_terminals.clear();
        self.terminals = terms;
        self.active_terminal = rec.active.min(self.terminals.len() - 1);
        self.sync_focus_flags();
        self.status = format!("Restored terminal session ({} panes)", self.terminals.len());
    }

    /// Available terminal profiles as `(shell_path, label)`: the shells in
    /// `/etc/shells`, with the user's current `$SHELL` ensured present
    /// (prepended) so the default is always an option even on a box with no
    /// `/etc/shells`.
    fn terminal_profiles(&self) -> Vec<(String, String)> {
        let contents = std::fs::read_to_string("/etc/shells").unwrap_or_default();
        let mut shells = crate::widgets::terminal::parse_shells(&contents);
        if let Ok(current) = std::env::var("SHELL")
            && !current.is_empty()
        {
            let base = std::path::Path::new(&current)
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or(&current)
                .to_string();
            if !shells.iter().any(|(_, b)| *b == base) {
                shells.insert(0, (current, base));
            }
        }
        shells
    }

    /// Where the profile dropdown hangs: under the `⌄` caret of the pane it was
    /// opened from, with the menu auto-clamping up/left to stay on screen.
    /// Anchoring on the first caret in the vec is wrong twice over — hidden
    /// panes hold `Rect::default()` placeholders so a button's position names
    /// its terminal, and side by side every pane has a live caret, so every
    /// pane's dropdown would hang under the leftmost one. Falls back to the
    /// toolbar's top-right corner before the caret has been painted.
    fn terminal_caret_origin(&self, pane: usize) -> (u16, u16) {
        self.terminal_profile_buttons
            .get(pane)
            .filter(|c| c.width > 0)
            .map(|c| (c.x, c.y.saturating_add(1)))
            .unwrap_or((self.last_frame_area.width.saturating_sub(20), 1))
    }

    /// Open the terminal-profile dropdown (VS Code's `⌄` next to `+`): a compact
    /// context menu anchored under the caret, one row per shell. Picking a row
    /// opens a new pane running that shell.
    fn open_terminal_profile_picker(&mut self, pane: usize) {
        let items: Vec<MenuEntry> = self
            .terminal_profiles()
            .into_iter()
            .map(|(path, label)| MenuEntry::Item {
                label,
                action: MenuAction::NewTerminalWithProfile(path),
            })
            .collect();
        if items.is_empty() {
            self.status = String::from("No terminal profiles found");
            return;
        }
        let origin = self.terminal_caret_origin(pane);
        // The dropdown is anchored under the `⌄` caret in the terminal
        // toolbar and grows downward into the terminal panel — it never
        // overlaps the editor's welcome logo, so the cached OSC-1337 image
        // is left intact rather than evicted (evicting it left the logo
        // blank, since the welcome emit is gated off while a menu is open).
        self.context_menu = Some(ContextMenu {
            origin,
            items,
            selected: 0,
            open_submenu: None,
            submenu_selected: 0,
            target_dir: self.tree.root.clone(),
        });
    }

    /// Clear the terminal at `idx`'s screen and scrollback (Cmd+K K / menu).
    fn clear_terminal_at(&mut self, idx: usize) {
        if let Some(t) = self.terminals.get_mut(idx) {
            t.clear_screen_and_scrollback();
            // The cleared grid invalidates find's state on this pane: the
            // anchored match names content that no longer exists (and the
            // clear can kill the scroll clock's tracer), so navigation
            // restarts from scratch and the count reflects the empty grid.
            if self.terminal_find.is_some() && self.terminal_find_pane == idx {
                self.terminal_find_match = None;
                self.terminals[idx].set_current_match(None, 0);
                let (lines, _top) = self.terminals[idx].grid_lines();
                if let Some(state) = self.terminal_find.as_mut() {
                    state.set_match_count(
                        crate::widgets::editor_find::count_matches(
                            &lines,
                            &state.query,
                            state.opts,
                        ),
                        false,
                    );
                    state.match_index = None;
                }
            }
            self.status = String::from("Cleared terminal");
        }
    }

    /// Open a prompt to rename the terminal pane at `idx` (Cmd+K R / menu),
    /// pre-filled with its current label.
    fn begin_rename_terminal(&mut self, idx: usize) {
        let Some(t) = self.terminals.get(idx) else {
            return;
        };
        let current = t.label().to_string();
        self.prompt = Some(Prompt {
            label: String::from("Rename Terminal"),
            buffer: current,
            kind: PromptKind::RenameTerminal(idx),
            target_dir: PathBuf::new(),
            error: None,
        });
    }

    /// Cmd+K N: open the annotation prompt for the active pane's selection
    /// (its first line's span). When the span overlaps an existing
    /// annotation, the prompt edits that note instead.
    fn begin_annotate_terminal(&mut self) {
        let pane = self.active_terminal;
        // Selection and clock from ONE snapshot: separate reads let PTY
        // output land in between, pairing a pre-output line with a
        // post-output clock and pinning the note to the wrong row.
        let (sel, clock) = self.terminals[pane].selection_and_clock();
        let Some(sel) = sel.filter(|s| s.has_area()) else {
            self.status = String::from("Annotate: select some output first (drag or copy mode)");
            return;
        };
        let (sr, sc, er, ec) = sel.normalised();
        let (_, _, cols, _) = self.terminals[pane].grid_bounds();
        let end = if er > sr { cols.saturating_sub(1) } else { ec };
        let (start, len) = (sc, end.saturating_sub(sc) + 1);
        // Translate the existing annotations at the SAME captured clock as
        // the selection, or output scrolling in between shifts them off the
        // fixed `sr` and the same span duplicates instead of editing.
        let current = self.terminals[pane].annotations_at_clock(clock);
        let existing = current
            .iter()
            .position(|&(l, s0, ln, _)| l == sr && s0 < start + len && start < s0 + ln);
        let buffer = existing
            .and_then(|i| current.get(i).map(|a| a.3.clone()))
            .unwrap_or_default();
        self.prompt = Some(Prompt {
            label: String::from("Annotate Selection"),
            buffer,
            kind: PromptKind::AnnotateTerminal {
                pane,
                line: sr,
                clock,
                start,
                len,
                existing,
            },
            target_dir: PathBuf::new(),
            error: None,
        });
    }

    /// Cmd+K Shift+N: drop every annotation whose span intersects the
    /// selection's first line span.
    fn delete_terminal_annotations_in_selection(&mut self) {
        let pane = self.active_terminal;
        let Some(sel) = self.terminals[pane].selection().filter(|s| s.has_area()) else {
            self.status = String::from("Delete annotation: select over the note first");
            return;
        };
        let (sr, sc, er, ec) = sel.normalised();
        let (_, _, cols, _) = self.terminals[pane].grid_bounds();
        let end = if er > sr { cols.saturating_sub(1) } else { ec };
        let hits: Vec<usize> = self.terminals[pane]
            .annotations_current()
            .iter()
            .enumerate()
            .filter(|&(_, &(l, s0, ln, _))| l == sr && s0 <= end && sc < s0 + ln)
            .map(|(i, _)| i)
            .collect();
        if hits.is_empty() {
            self.status = String::from("No annotation under the selection");
            return;
        }
        for i in hits.into_iter().rev() {
            self.terminals[pane].remove_annotation(i);
        }
        self.status = String::from("Deleted annotation");
    }

    /// Drop the terminal at `idx`. Returns false (and does nothing) when
    /// only one terminal is left or `idx` is out of range. Hiding the pane
    /// is the user's job (Ctrl+J), not ours, so the last terminal stays.
    /// The active index shifts so the same logical terminal remains active
    /// when an inactive pane is closed; closing the active pane reseats the
    /// focus on the neighbour to the left (or the new last if we removed
    /// the right edge).
    ///
    /// The pane is not dropped (which would kill its child): it parks in
    /// `closed_terminals` for [`UNDO_CLOSE_GRACE`] so Cmd+K ⇧T can bring it
    /// back, process and scrollback intact. The tick reaps expired entries.
    pub fn close_terminal_at(&mut self, idx: usize) -> bool {
        if self.terminals.len() <= 1 || idx >= self.terminals.len() {
            return false;
        }
        let term = self.terminals.remove(idx);
        // A lane pane closed by any route stops being the lane's (#348): the
        // map is keyed by uid, and an undo-close brings the pane back as an
        // ordinary one rather than re-seating an agent nobody asked for.
        self.lane_panes.remove(&term.uid());
        self.closed_terminals.push(ClosedTerminal {
            term,
            idx,
            closed_at: std::time::Instant::now(),
        });
        if self.active_terminal == idx {
            if self.active_terminal >= self.terminals.len() {
                self.active_terminal = self.terminals.len() - 1;
            }
        } else if self.active_terminal > idx {
            self.active_terminal -= 1;
        }
        // Closing the only expanded pane would leave the row nothing but
        // strips; the collapse gesture refuses that from its own side and
        // this closes the other route to it.
        self.ensure_a_terminal_pane_is_expanded();
        // A lone terminal has nothing to maximize against; the rail would be
        // empty, so the split view is the honest state.
        if self.terminals.len() <= 1 {
            self.terminal_pane_maximized = false;
            // Safety: never keep broadcast armed against a single pane —
            // the next split would silently start receiving mirrored input.
            if self.broadcast_input {
                self.broadcast_input = false;
                self.status = String::from("Broadcast input off (one pane left)");
            }
        }
        self.sync_focus_flags();
        self.save_terminal_session();
        true
    }

    /// Toggle maximize mode for the active terminal pane (Cmd+K M / the
    /// pane's `⛶` button): one pane spans the panel's width and the other
    /// terminals move to the right rail, where clicking a row hands it the
    /// maximized pane. Orthogonal to `toggle_terminal_maximize`
    /// (Ctrl+Shift+J), which grows the panel over the editor: this
    /// reapportions the panel's width, not the window's rows.
    pub fn toggle_terminal_pane_maximize(&mut self) {
        if self.terminal_pane_maximized {
            self.terminal_pane_maximized = false;
            // The rail lists folded panes too, so the pane that held the
            // maximized view may be a strip once the split comes back. The
            // invariant lives in `sync_focus_flags` and this is the gesture
            // that re-enters its scope.
            self.sync_focus_flags();
            self.terminal_status(String::from("Restored terminal split"));
        } else if self.terminals.len() > 1 {
            self.terminal_pane_maximized = true;
            self.status = String::from("Maximized terminal");
        } else {
            self.status = String::from("Only one terminal open");
        }
    }

    /// Serve one accepted `croft view` client: bound the socket, read the
    /// request, apply it, and answer. Returns the reply and whether anything
    /// was opened (so the caller can redraw).
    ///
    /// Split out of the accept loop so a test can hand it a stream and observe
    /// the REPLY. The previous test for the blocking-mode fix accepted a
    /// connection, called `set_nonblocking(false)` itself, and then asserted
    /// the flag it had just set - it could not fail on any platform, which is
    /// the false-green shape this repo's own guidance names. Given this seam a
    /// test can hand in a deliberately NON-blocking stream and assert the
    /// reply is `Ok`, which fails everywhere if the call below is dropped.
    fn answer_view_client(
        &mut self,
        mut stream: std::os::unix::net::UnixStream,
        deadline: std::time::Instant,
    ) -> (crate::view_ipc::ViewReply, bool) {
        // An accepted socket's flags are not portably inherited: Linux's
        // accept(2) says the new socket does NOT inherit O_NONBLOCK and that
        // portable programs must set flags explicitly, while BSD (so macOS,
        // croft's primary platform) does inherit them. Inherited, every read
        // returns EAGAIN before any timeout applies and every `croft view`
        // comes back "unreadable request: Resource temporarily unavailable"
        // while Linux CI stays green.
        let _ = stream.set_nonblocking(false);
        // `read_request` re-arms its own read timeout from the deadline on
        // every recv, so none is set here. The WRITE bound is armed below,
        // after the read, from whatever the read left — and it exists because
        // the reply embeds the client-supplied path, so a client that sends a
        // valid long request and never reads can block `write_all` on a full
        // socket buffer. Not reproducible on Linux, whose default unix-socket
        // buffer is far larger than any legal reply, which is why it is set
        // rather than tested.
        let reply = match crate::view_ipc::read_request(&stream, deadline) {
            Ok(req) => self.apply_view_request(&req.to_path()),
            Err(e) => crate::view_ipc::ViewReply::Err {
                message: format!("unreadable request: {e}"),
            },
        };
        // Armed AFTER the read, from what the read left: computing it before
        // gives a client that spent the whole budget reading a fresh window to
        // spend writing, so one client could cost the frame loop twice the
        // documented 20ms.
        //
        // The floor is 1ms and the write's result is discarded, which is worth
        // being explicit about rather than leaving as an accident. If that
        // 1ms ever fired on an `Ok`, the file is open in the editor while the
        // client's shell exits 1 saying croft closed without replying: the
        // reply is 16 bytes to a socket with a reader already waiting, so it
        // is unreachable in practice, and the alternative (dropping the reply
        // rather than the timeout) trades a wrong message for no message.
        let left = deadline
            .saturating_duration_since(std::time::Instant::now())
            .max(std::time::Duration::from_millis(1));
        let _ = stream.set_write_timeout(Some(left));
        let opened = matches!(reply, crate::view_ipc::ViewReply::Ok);
        let _ = crate::view_ipc::write_reply(&mut stream, &reply);
        (reply, opened)
    }

    /// Paint a collapsed pane's one-column strip (#313) and return its hit
    /// rect: the expand chevron on the header row, then the pane's name set
    /// vertically down the column.
    ///
    /// A strip rather than hiding the pane outright. A pane that vanishes is
    /// indistinguishable from one that was closed, and croft already has
    /// closing, with its own undo window; the strip keeps the pane counted,
    /// named and clickable, which is what makes folding it obviously
    /// reversible.
    fn paint_terminal_collapsed_strip(
        &mut self,
        frame: &mut ratatui::Frame,
        area: Rect,
        idx: usize,
    ) -> Rect {
        if area.width == 0 || area.height == 0 {
            return Rect::default();
        }
        let hovered = self.pointer_cell.is_some_and(|(px, py)| {
            px >= area.x && px < area.x + area.width && py >= area.y && py < area.y + area.height
        });
        frame.render_widget(
            ratatui::widgets::Block::default().style(Style::default().bg(self.theme.editor_bg())),
            area,
        );
        let chevron = crate::widgets::header_pill::action_style(self.theme, hovered);
        let name = crate::widgets::header_pill::action_style(self.theme, false);
        let label = self.terminals[idx].label().to_string();
        let buf = frame.buffer_mut();
        buf.set_string(area.x, area.y, TERMINAL_EXPAND_GLYPH.to_string(), chevron);
        // The name runs down the strip so a folded pane is still identifiable
        // without unfolding it. Only single-width characters are placed: a CJK
        // glyph or an emoji is two cells wide and would paint over the pane
        // next door, which is one column away.
        for (row, ch) in label
            .chars()
            .filter_map(|c| match unicode_width::UnicodeWidthChar::width(c) {
                Some(1) => Some(c),
                // Wide: keep the position, lose the glyph.
                Some(w) if w > 1 => Some(TERMINAL_STRIP_WIDE_STANDIN),
                // Zero-width — a combining mark or a control character —
                // has nothing to stand in for and no cell of its own.
                _ => None,
            })
            .take(area.height.saturating_sub(1) as usize)
            .enumerate()
        {
            buf.set_string(area.x, area.y + 1 + row as u16, ch.to_string(), name);
        }
        area
    }

    /// Collapse the pane at `idx` to a strip, or give a collapsed one its
    /// width back (#313). The `‹` header button, the strip, the right-click
    /// entry and the palette command all land here.
    ///
    /// Collapsing the LAST expanded pane is refused: folding every pane away
    /// leaves a row of strips with nothing in it, and croft already has
    /// Ctrl+J for putting the panel away entirely (Ctrl+Shift+J is the
    /// opposite gesture, growing it over the editor). The refusal says so
    /// on the status line rather than swallowing the click, so the button
    /// never reads as broken.
    pub fn toggle_terminal_collapse(&mut self, idx: usize) {
        let Some(pane) = self.terminals.get(idx) else {
            return;
        };
        if pane.collapsed {
            self.terminals[idx].collapsed = false;
            self.active_terminal = idx;
            self.focus_pane(Pane::Terminal);
            let msg = format!("Expanded terminal {}", self.terminals[idx].label());
            self.terminal_status(msg);
            return;
        }
        if self.terminals.iter().filter(|t| !t.collapsed).count() <= 1 {
            self.status = String::from("Cannot collapse the last expanded terminal");
            return;
        }
        self.terminals[idx].collapsed = true;
        // Focus cannot stay on a pane that is now one column wide: it shows no
        // cursor, so the keystrokes would go somewhere the user cannot see
        // them arrive. `sync_focus_flags` owns that rule for every path, this
        // one included - a second copy of the nearest-expanded walk here would
        // be dead weight AND a tie-break that can drift out of step with the
        // one that matters.
        self.sync_focus_flags();
        let msg = format!("Collapsed terminal {}", self.terminals[idx].label());
        self.terminal_status(msg);
    }

    /// Fold the active pane, unless maximize owns the panel (#313).
    ///
    /// The `‹` button is not painted while maximized and the right-click entry
    /// is suppressed there, but the chord and the palette command reached
    /// `toggle_terminal_collapse` directly and so had no such guard. Because
    /// collapsing reassigns `active_terminal` and the maximize branch hands
    /// the panel to whatever that is, the effect was to swap the maximized
    /// pane for a neighbour while the status line announced a collapse that
    /// was invisible until you left maximize.
    pub fn collapse_active_terminal_pane(&mut self) {
        if self.terminal_pane_maximized {
            self.status = String::from("Collapse is unavailable while a pane is maximized");
            return;
        }
        self.toggle_terminal_collapse(self.active_terminal);
    }

    /// Make the pane at `idx` the active one AND visible (#313).
    ///
    /// For callers that deliberately TARGET a pane by index - jump to a
    /// captured line, run a task in its own pane, run a fenced block, focus an
    /// agent's pane - rather than for a gesture that merely moves focus.
    ///
    /// The distinction is load-bearing. `sync_focus_flags` walks focus OFF a
    /// folded pane, which is right for a drifting gesture and wrong here: it
    /// silently redirected these callers to a neighbour, so a task command was
    /// written into a pane that is never rendered while the status line
    /// reported it running. Reaching for a pane by index is a request to see
    /// it, which is the rationale `undo_close_terminal` already applies when
    /// it force-expands a reopened pane.
    fn reveal_terminal_pane(&mut self, idx: usize) {
        if let Some(t) = self.terminals.get_mut(idx) {
            t.collapsed = false;
        }
        self.active_terminal = idx;
    }

    /// Give every collapsed pane its width back (Cmd+K `]`): the issue's
    /// "maximise the terminals back to the same equal-sized terminal
    /// windows", which has to be one gesture rather than one per pane.
    pub fn restore_all_terminal_panes(&mut self) {
        // The mirror of the guard on `collapse_active_terminal_pane`. Without
        // it, Cmd+K ] while maximized cleared every flag and announced it, for
        // a change the user cannot see until they leave maximize: the same
        // silent-state-change this pair already refuses in the other
        // direction.
        if self.terminal_pane_maximized {
            self.terminal_status(String::from(
                "Restore is unavailable while a pane is maximized",
            ));
            return;
        }
        let folded = self.terminals.iter().filter(|t| t.collapsed).count();
        if folded == 0 {
            self.terminal_status(String::from("No collapsed terminal panes"));
            return;
        }
        for t in self.terminals.iter_mut() {
            t.collapsed = false;
        }
        self.terminal_status(format!(
            "Restored {folded} terminal pane{}",
            if folded == 1 { "" } else { "s" }
        ));
    }

    /// Keep at least one pane expanded after a pane leaves the row (#313).
    ///
    /// [`Self::toggle_terminal_collapse`] refuses to fold the last expanded
    /// pane, but CLOSING reaches the same state from the other side: two
    /// panes with one collapsed, close the expanded one, and the panel is a
    /// single strip with nothing behind it. Expanding the pane that is now
    /// active, rather than all of them, keeps the rest of the user's
    /// folding intact.
    fn ensure_a_terminal_pane_is_expanded(&mut self) {
        if self.terminals.is_empty() || self.terminals.iter().any(|t| !t.collapsed) {
            return;
        }
        let idx = self.active_terminal.min(self.terminals.len() - 1);
        self.terminals[idx].collapsed = false;
    }

    /// Drop the rail's hit rects and its column. Both must go together: a
    /// stale area would keep swallowing the wheel after the rail left screen.
    fn clear_terminal_rail(&mut self) {
        self.terminal_rail_rects.clear();
        self.terminal_rail_area = Rect::default();
    }

    /// Paint the maximize-mode rail: one row per terminal down the panel's
    /// right edge — the active one highlighted, the rest hover-lit — so the
    /// user can shuffle between maximized terminals. Records one hit rect
    /// per row in `terminal_rail_rects`, index-aligned with `terminals`.
    fn paint_terminal_rail(&mut self, frame: &mut ratatui::Frame, rail: Rect) {
        self.terminal_rail_area = rail;
        if rail.width == 0 || rail.height == 0 {
            return;
        }
        let brand = self.theme.gradient();
        // Same selected-row treatment as the OPEN EDITORS list, so the rail
        // reads as the same family of chrome in both themes.
        let sel_bg = if brand {
            crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG)
        } else {
            self.theme.ui(Color::Rgb(0x09, 0x4d, 0x77))
        };
        // With more terminals than rows the rail is a window over the list,
        // scrolled by the wheel — the panel floors at 3 rows, so four panes
        // are enough to reach this. Switching panes scrolls the new one into
        // view so its highlight is never off-screen, but only on the frame the
        // active pane CHANGES: revealing every frame would pin the window
        // whenever the active pane sits at either end and make the wheel inert.
        let rows = rail.height as usize;
        let max_scroll = self.terminals.len().saturating_sub(rows);
        let mut scroll = self.terminal_rail_scroll.min(max_scroll);
        if self.terminal_rail_revealed != Some(self.active_terminal) {
            if self.active_terminal < scroll {
                scroll = self.active_terminal;
            } else if self.active_terminal >= scroll + rows {
                scroll = self.active_terminal + 1 - rows;
            }
            self.terminal_rail_revealed = Some(self.active_terminal);
        }
        self.terminal_rail_scroll = scroll;
        for i in 0..self.terminals.len() {
            // Rows outside the window still push a placeholder, so a rect's
            // position in the vec keeps naming its terminal. `rect_contains`
            // rejects empty rects, so they can never phantom-match a click.
            if i < scroll || i >= scroll + rows {
                self.terminal_rail_rects.push(Rect::default());
                continue;
            }
            let y = rail.y + (i - scroll) as u16;
            let row = Rect {
                x: rail.x,
                y,
                width: rail.width,
                height: 1,
            };
            let active = i == self.active_terminal;
            let bg = if active {
                Some(sel_bg)
            } else {
                crate::widgets::hover::row_hover_bg(row, self.pointer_cell, self.theme)
            };
            if let Some(bg) = bg {
                frame.buffer_mut().set_style(row, Style::default().bg(bg));
            }
            let label = self.terminals[i].label().to_string();
            let room = TERMINAL_RAIL_LABEL_W as usize;
            let shown: String = label.chars().take(room).collect();
            let fg = if active {
                Style::default()
                    .fg(self.theme.ui(Color::White))
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            // `set_string` clips at the buffer edge, not the rail's, so a
            // label wider than a clamped rail would paint its tail over the
            // panel to the right. Clip to the rail's own width.
            frame.buffer_mut().set_stringn(
                row.x,
                y,
                format!(" {TERMINAL_RAIL_ICON} {shown}"),
                row.width as usize,
                fg,
            );
            self.terminal_rail_rects.push(row);
        }
    }

    /// Move the terminal at `from` so it sits at slot `to`, keeping
    /// `active_terminal` pointing at the same terminal it did before. Drives
    /// the drag-reorder of side-by-side panes and maximize-mode rail rows.
    pub fn move_terminal(&mut self, from: usize, to: usize) {
        if from == to || from >= self.terminals.len() || to >= self.terminals.len() {
            return;
        }
        // `last_area` is a SLOT's geometry, but it lives on the terminal
        // object and so travels with it. The panes do not actually move on
        // screen until the next frame, and the drag hit-tests `last_area`
        // between frames — the main loop drains the whole queued mouse burst
        // before drawing. Re-seat the rects in slot order so the next motion
        // report over the same cell resolves to the pane now sitting there
        // instead of swapping the two straight back, which made the final
        // order the parity of however many motion reports arrived.
        let slot_rects: Vec<Rect> = self.terminals.iter().map(|t| t.last_area).collect();
        let t = self.terminals.remove(from);
        self.terminals.insert(to, t);
        self.active_terminal = match self.active_terminal {
            a if a == from => to,
            a if from < a && a <= to => a - 1,
            a if to <= a && a < from => a + 1,
            a => a,
        };
        if self.terminal_pane_maximized {
            // Maximize mode has exactly one live rect, and it belongs to
            // whichever pane was active at the LAST PAINT — not to the dragged
            // terminal, since the press and the drag are drained together. So
            // neither positional rule works here: find the live rect and hand
            // it to the pane the drag leaves active, which is the one that will
            // own the panel on the next frame.
            let pane = slot_rects
                .iter()
                .copied()
                .find(|r| r.width > 0)
                .unwrap_or_default();
            let active = self.active_terminal;
            for (i, term) in self.terminals.iter_mut().enumerate() {
                term.last_area = if i == active { pane } else { Rect::default() };
            }
        } else {
            for (term, rect) in self.terminals.iter_mut().zip(slot_rects) {
                // A folded pane is not painted in whatever slot the drag left
                // it in, so it must not inherit that slot's geometry (#313):
                // the rest of the drained mouse burst hit-tests these rects,
                // and a live rect over an unpainted pane resolves clicks to a
                // pane that is not there.
                term.last_area = if term.collapsed {
                    Rect::default()
                } else {
                    rect
                };
            }
        }
        self.terminal_session_dirty = true;
    }

    /// Write the pane session if a reorder marked it pending. Called once per
    /// tick so a drag costs one write instead of one per motion report.
    pub fn flush_terminal_session(&mut self) {
        if std::mem::take(&mut self.terminal_session_dirty) {
            self.save_terminal_session();
        }
    }

    /// Drop the currently-active terminal. Thin wrapper kept for the
    /// keyboard shortcut and existing callers.
    pub fn close_active_terminal(&mut self) -> bool {
        self.close_terminal_at(self.active_terminal)
    }

    /// Cmd+K ⇧T: bring back the most recently closed terminal pane while it
    /// is still inside the undo-close grace window. The pane returns to the
    /// slot it occupied (clamped if the layout shrank) and takes focus; its
    /// child process and scrollback were never touched.
    pub fn undo_close_terminal(&mut self) {
        let Some(parked) = self.closed_terminals.pop() else {
            self.status = String::from("No recently closed terminals");
            return;
        };
        let idx = parked.idx.min(self.terminals.len());
        self.terminals.insert(idx, parked.term);
        // Reopening is a request to see the pane, so it comes back expanded
        // whatever it was when it was closed: a restore that put a strip on
        // screen would read as the reopen having failed.
        self.terminals[idx].collapsed = false;
        self.active_terminal = idx;
        if !self.show_terminal {
            self.show_terminal = true;
        }
        self.focus_pane(Pane::Terminal);
        self.sync_focus_flags();
        self.save_terminal_session();
        let msg = format!("Restored terminal {}", self.terminals[idx].label());
        self.terminal_status(msg);
    }

    /// Drop parked closed panes whose grace window lapsed (their Drop kills
    /// the child). Called from the drain tick.
    fn reap_closed_terminals(&mut self) {
        self.closed_terminals
            .retain(|p| p.closed_at.elapsed() <= UNDO_CLOSE_GRACE);
    }

    /// Record the focused group's tab at `idx` as reopenable (Cmd+K ⇧W).
    /// Scratch buffers with no backing file are not recorded. Must run
    /// BEFORE the close mutates the tab list. Tabs that merely move (into a
    /// new window) or whose file was just trashed are deliberately never
    /// recorded by their callers.
    fn record_closed_tab_at(&mut self, idx: usize) {
        let Some(ed) = self.editor.editors.get(idx) else {
            return;
        };
        let Some(path) = ed.path.clone() else {
            return;
        };
        self.closed_tabs.push(ClosedTab {
            path,
            pinned: ed.pinned,
            cursor: (ed.cursor_row, ed.cursor_col),
            scroll: ed.scroll,
        });
        if self.closed_tabs.len() > CLOSED_TAB_STACK_CAP {
            self.closed_tabs.remove(0);
        }
    }

    /// Record every tab the bulk closes (Close Others / Close to the Right)
    /// are about to drop: the unpinned, file-backed ones `pred` selects, in
    /// tab order so the reopen stack pops most-recent-first.
    fn record_closed_tabs_where(&mut self, pred: impl Fn(usize, &Editor) -> bool) {
        let picks: Vec<usize> = self
            .editor
            .editors
            .iter()
            .enumerate()
            .filter(|(i, ed)| pred(*i, ed))
            .map(|(i, _)| i)
            .collect();
        for i in picks {
            self.record_closed_tab_at(i);
        }
    }

    /// Cmd+K ⇧W: reopen the most recently closed editor tab (VS Code
    /// "Reopen Closed Editor"), restoring its pin state, cursor, and
    /// scroll. Entries whose file has vanished since the close are skipped,
    /// falling through to the next reopenable one.
    pub fn reopen_closed_tab(&mut self) {
        while let Some(t) = self.closed_tabs.pop() {
            if !t.path.exists() {
                continue;
            }
            let opened = if t.pinned {
                self.editor.open_pinned(&t.path)
            } else {
                self.editor.open_preview(&t.path)
            };
            match opened {
                Ok(()) => {
                    self.sync_open_file_poll_mtime();
                    let rows = self.editor.lines.len();
                    self.editor.cursor_row = t.cursor.0.min(rows.saturating_sub(1));
                    let max_col = self
                        .editor
                        .lines
                        .get(self.editor.cursor_row)
                        .map(|l| l.chars().count())
                        .unwrap_or(0);
                    self.editor.cursor_col = t.cursor.1.min(max_col);
                    self.editor.scroll = t.scroll.min(rows.saturating_sub(1));
                    self.editor.ensure_cursor_col_visible();
                    self.tree.reveal_path(&t.path);
                    self.focus_pane(Pane::Editor);
                    self.poke_cursor();
                    self.status = format!("Reopened {}", self.status_path(&t.path));
                }
                Err(e) => {
                    self.status = format!("Reopen failed: {e}");
                }
            }
            return;
        }
        self.status = String::from("No closed tabs to reopen");
    }

    /// Swap the per-host accent rules (config.json reload, and tests).
    pub fn set_host_accents(&mut self, rules: &[crate::prefs::HostAccentRule]) {
        self.host_accents = compile_host_accents(rules);
    }

    /// Settings / palette "Terminal: Toggle Secret Redaction" (#360): the
    /// built-in key and token rules leave or rejoin the trigger set; the
    /// user's own `redact` rows in triggers.json are unaffected.
    pub fn toggle_secret_redaction(&mut self) {
        self.secret_redaction = !self.secret_redaction;
        self.triggers = load_trigger_set(self.secret_redaction);
        self.status = String::from(if self.secret_redaction {
            "Secret redaction: on"
        } else {
            "Secret redaction: off"
        });
        if !cfg!(test) {
            let _ = crate::prefs::save_disable_secret_redaction(!self.secret_redaction);
        }
    }

    /// Palette "Terminal: Reveal Redacted Secrets for 10s": every mask on
    /// every pane paints as its real text for ten seconds, then masks
    /// again. Announced so a screen share sees it happen.
    pub fn reveal_redacted_secrets(&mut self) {
        self.redaction_reveal_until =
            Some(std::time::Instant::now() + std::time::Duration::from_secs(10));
        self.status = String::from("Redacted secrets revealed for 10s");
    }

    /// Whether a reveal window is open right now.
    fn redactions_revealed(&self) -> bool {
        self.redaction_reveal_until
            .is_some_and(|until| std::time::Instant::now() < until)
    }

    /// Main-loop tick: when the reveal window closes, drop it and ask for
    /// a redraw so the masks come back without waiting for other input.
    pub fn tick_redaction_reveal(&mut self) -> bool {
        if self.redaction_reveal_until.is_some() && !self.redactions_revealed() {
            self.redaction_reveal_until = None;
            self.status = String::from("Redacted secrets masked again");
            return true;
        }
        false
    }

    /// Masks on screen across every pane, as painted last frame.
    fn redacted_on_screen(&self) -> usize {
        self.terminals.iter().map(|t| t.redacted_on_screen).sum()
    }

    /// The current index of the pane a forwarded left press went to (#474),
    /// or `None` once that pane has been closed. Looked up by uid on every
    /// event of the gesture because a close or reorder while the button is
    /// held renumbers the vector under a stored index.
    fn forwarded_pane_index(&self, fp: ForwardedPointer) -> Option<usize> {
        self.terminals.iter().position(|t| t.uid() == fp.pane)
    }

    /// The clipboard's view of terminal text: rules marked `copy: masked`
    /// keep their mask, everything else copies as typed (#360).
    fn terminal_text_for_copy(&self, text: String) -> String {
        crate::triggers::mask_text(&text, &self.triggers, true)
    }

    /// Palette "Terminal: Toggle Timestamps": show / hide the per-row
    /// arrival-clock gutter on every pane.
    pub fn toggle_terminal_timestamps(&mut self) {
        self.show_terminal_timestamps = !self.show_terminal_timestamps;
        for t in self.terminals.iter_mut() {
            t.show_timestamps = self.show_terminal_timestamps;
        }
        self.status = String::from(if self.show_terminal_timestamps {
            "Terminal timestamps on"
        } else {
            "Terminal timestamps off"
        });
    }

    /// Cmd+K I: toggle broadcast input. Turning it ON goes through a confirm
    /// popup (iTerm2 warns the same way); turning it OFF is immediate.
    fn toggle_broadcast_input(&mut self) {
        if self.broadcast_input {
            self.broadcast_input = false;
            self.status = String::from("Broadcast input off");
            return;
        }
        if self.terminals.len() < 2 {
            self.status =
                String::from("Broadcast input needs at least two terminal panes (Cmd+T splits)");
            return;
        }
        self.pending_broadcast_enable = true;
    }

    fn confirm_pending_broadcast(&mut self) {
        self.pending_broadcast_enable = false;
        self.broadcast_input = true;
        let receiving = self
            .terminals
            .iter()
            .filter(|t| !t.broadcast_excluded)
            .count();
        self.status = format!(
            "Broadcast input ON: keystrokes go to {receiving} panes (Cmd+K I to stop, Cmd+K Shift+I excludes a pane)"
        );
    }

    fn cancel_pending_broadcast(&mut self) {
        self.pending_broadcast_enable = false;
        self.status = String::from("Broadcast input cancelled");
    }

    /// Cmd+K Shift+I: toggle whether the active pane receives broadcast
    /// input. The focused pane always gets its own typing; exclusion only
    /// mutes the mirrored copy while it is unfocused.
    fn toggle_broadcast_exclusion(&mut self) {
        let idx = self.active_terminal;
        let Some(t) = self.terminals.get_mut(idx) else {
            return;
        };
        t.broadcast_excluded = !t.broadcast_excluded;
        let label = t.label().to_string();
        self.status = if self.terminals[idx].broadcast_excluded {
            format!("{label} excluded from broadcast input")
        } else {
            format!("{label} receives broadcast input again")
        };
    }

    /// Paste counterpart of [`Self::write_terminal_key`] (bracketed-paste
    /// aware per pane): normally just the active pane, mirrored to every
    /// non-excluded pane while broadcast is on (the focused pane always
    /// receives its own input).
    fn paste_terminal_input(&mut self, payload: &[u8]) {
        if self.broadcast_input {
            let active = self.active_terminal;
            for (i, t) in self.terminals.iter_mut().enumerate() {
                if i == active || !t.broadcast_excluded {
                    t.paste_input(payload);
                }
            }
        } else {
            self.terminal_mut().paste_input(payload);
        }
    }

    /// Cycle the active terminal forward to the next pane the user can
    /// actually see, wrapping at the end.
    ///
    /// Collapsed panes are stepped over (#313). A folded pane is one column
    /// wide and is never rendered, so it paints no cursor and no focus
    /// border: cycling onto one would send every keystroke into a pane the
    /// user cannot see receiving them. `toggle_terminal_collapse` defends
    /// that same invariant on its own path; this is the other way in, and it
    /// predated the flag.
    pub fn cycle_terminal(&mut self) {
        self.step_active_terminal(true);
    }

    /// Cycle the active terminal backward, wrapping at the front. Mirror of
    /// `cycle_terminal` for the Cmd+[ binding, folded panes skipped alike.
    pub fn cycle_terminal_back(&mut self) {
        self.step_active_terminal(false);
    }

    /// Walk `active_terminal` one visible pane in either direction.
    ///
    /// The loop is bounded by the pane count and at least one pane is always
    /// expanded (`toggle_terminal_collapse` refuses to fold the last one and
    /// `ensure_a_terminal_pane_is_expanded` closes the other route), so it
    /// always terminates on a pane that is painted. If that invariant were
    /// ever broken the walk falls through without moving, which is inert
    /// rather than a hang.
    fn step_active_terminal(&mut self, forward: bool) {
        let n = self.terminals.len();
        if n <= 1 {
            return;
        }
        for step in 1..=n {
            let cand = if forward {
                (self.active_terminal + step) % n
            } else {
                (self.active_terminal + n - (step % n)) % n
            };
            if !self.terminals[cand].collapsed {
                self.active_terminal = cand;
                break;
            }
        }
        self.sync_focus_flags();
    }

    /// OR-fold dirty flags across all terminals while clearing each. Use `|`
    /// (not `||`) so every terminal's flag is consumed even after the first
    /// dirty one is found.
    pub fn drain_terminals_dirty(&mut self) -> bool {
        let dirty = self
            .terminals
            .iter()
            .fold(false, |acc, t| acc | t.take_dirty());
        // A recording captures the SCREEN, not the byte stream (#356). The
        // PTY bytes are consumed by the grid before the app sees them, so
        // there is no text stream left to tee — and a cast of screens is
        // what a player replays anyway. Sampled here because this fires
        // exactly when something changed, so an idle session records
        // nothing rather than a frame per tick.
        if dirty && self.recording.is_some() {
            self.record_active_screen();
        }
        dirty
    }

    /// Write a resize event to the open recording (#356).
    fn record_resize(&mut self, cols: u16, rows: u16) {
        use std::io::Write as _;
        let Some((rec, file, started)) = self.recording.as_mut() else {
            return;
        };
        let line = rec.line(&crate::asciicast::Event::Resize {
            at: started.elapsed().as_secs_f64(),
            cols,
            rows,
        });
        if writeln!(file, "{line}").is_err() {
            self.recording = None;
            self.status = String::from("Recording stopped: could not write to the cast file");
        }
    }

    /// Write the active terminal's current screen to the open recording.
    ///
    /// Clear-and-redraw rather than a delta: `\u{1b}[H\u{1b}[2J` then the
    /// rows. A delta would need the previous screen and a diff that agrees
    /// with the terminal's own scroll behaviour, and a cast that drifts a
    /// row from reality is the kind of bug nobody notices until the demo is
    /// published.
    ///
    /// **The recording is monochrome, and the cursor is not restored.**
    /// `grid_lines` returns plain `String`s — the cell attributes are in the
    /// grid but not in that view — so a cast records the TEXT of a session
    /// and not its colour. That is a real limit rather than an oversight:
    /// carrying attributes means re-emitting SGR per run of cells, which is
    /// the byte stream this deliberately does not tap. Named here so nobody
    /// files it as a bug and so the follow-on knows what it costs.
    fn record_active_screen(&mut self) {
        // Read everything the frame needs from the pane in ONE borrow, then
        // write. The two writes below both take `&mut self`, so interleaving
        // them with pane reads would need the pane borrowed twice around
        // them — which compiles but reads as an accident rather than as a
        // decision.
        let Some((size, lines)) = self.terminals.get(self.active_terminal).map(|t| {
            let (mut all, top) = t.grid_lines();
            // The VISIBLE screen only. `grid_lines` starts at
            // `topmost_line()`, which is negative scrollback — up to
            // 5000 rows. Writing all of it after a clear scrolls the
            // live screen straight off the top, so the cast shows the
            // tail of the history rather than what the user was looking
            // at, at ~400 KB per frame.
            let visible = all.split_off((-top).max(0) as usize);
            ((t.last_inner.width, t.last_inner.height), visible)
        }) else {
            return;
        };
        // The resize goes FIRST, so a player has the new geometry before the
        // frame drawn at it — the other order renders one frame wrapped at
        // the old width.
        if size != self.recorded_size && size.0 > 0 && size.1 > 0 {
            self.recorded_size = size;
            self.record_resize(size.0, size.1);
        }
        let mut frame = String::from("\u{1b}[H\u{1b}[2J");
        frame.push_str(&lines.join("\r\n"));
        self.record_terminal_output(&frame);
    }

    /// Like `drain_terminals_dirty` but does not clear the underlying flags.
    /// The main loop uses this to decide whether to coalesce a PTY-only
    /// redraw without losing the signal if it chooses to skip.
    pub fn peek_terminals_dirty(&self) -> bool {
        self.terminals.iter().any(|t| t.peek_dirty())
    }

    /// Total bytes the PTY reader threads have advanced into their grids
    /// since the last redraw. The main loop uses this to bypass the PTY
    /// redraw cap for small interactive echo while keeping bulk streams
    /// capped. Peeks without clearing; `drain_terminals_dirty` resets it.
    pub fn peek_terminals_pending_bytes(&self) -> usize {
        self.terminals.iter().map(|t| t.peek_pending_bytes()).sum()
    }

    fn terminal_at_pos(&self, col: u16, row: u16) -> Option<usize> {
        self.terminals
            .iter()
            .position(|t| rect_contains(t.last_area, col, row))
    }

    /// Run `f` with auto-hide suppressed, for focus moves the user did not
    /// ask for. `focus_pane` cannot tell intent apart on its own: an async
    /// MCP result, a launch-time file open, and Enter on a sidebar row all
    /// look identical to it, and collapsing on those is the flapping #260
    /// set out to prevent.
    fn without_auto_hide<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
        let prev = std::mem::replace(&mut self.sidebar_auto_hide_suspended, true);
        let out = f(self);
        self.sidebar_auto_hide_suspended = prev;
        out
    }

    /// Whether a modal overlay owns the screen right now. The same eleven-way
    /// check was repeated verbatim at three overlay-flush sites; auto-hide
    /// (#260) needs it too, so it lives here once.
    fn modal_overlay_open(&self) -> bool {
        self.shortcuts_modal.is_some()
            || self.file_finder.is_some()
            || self.command_palette.is_some()
            || self.go_to_symbol.is_some()
            || self.workspace_symbols.is_some()
            || self.process_picker.is_some()
            || self.zoxide_jump.is_some()
            || self.command_history_popup.is_some()
            || self.branch_picker.is_some()
            || self.input_prompt.is_some()
            || self.list_picker.is_some()
    }

    /// Whether auto-hide may collapse the sidebar RIGHT NOW. Every reason to
    /// hold it open lives here rather than being scattered through the call
    /// sites, so the interaction rules are one readable list and a new
    /// suppression case has exactly one place to go.
    /// Whether a STRUCTURAL suppression is in force: one that no passage of
    /// time lifts, only a deliberate chrome change by the user.
    ///
    /// Split out from [`Self::sidebar_auto_hide_allowed`] because the tick has
    /// to treat the two kinds differently and the combined predicate cannot
    /// say which it declined for. A transient suppression (seam drag, open
    /// palette, modal) ends in moments, so the dwell stays armed and retries.
    /// A structural one can last the session, and a dwell left armed across it
    /// fires on the frame it lifts — a collapse for a focus move the user made
    /// an hour ago. Cancelling at the ARM site instead would make the retry
    /// unreachable, which is the recovery path for the transient case.
    fn sidebar_structurally_suppressed(&self) -> bool {
        !self.activity_bar_visible || self.zen_mode
    }

    /// Whether auto-hide may collapse the sidebar RIGHT NOW. Every reason to
    /// hold it open lives here rather than being scattered through the call
    /// sites, so the interaction rules are one readable list and a new
    /// suppression case has exactly one place to go.
    fn sidebar_auto_hide_allowed(&self) -> bool {
        if !self.sidebar_auto_hide || !self.show_tree {
            return false;
        }
        // A focus move nobody asked for is not a reason to hide chrome.
        if self.sidebar_auto_hide_suspended {
            return false;
        }
        // NOTE: the one-shot reveal pin is deliberately NOT checked here. It is
        // the caller's concern (`tick_sidebar_auto_hide_at`), because this
        // predicate must stay answerable while a pin is banked: the tick asks
        // "would this collapse otherwise fire?" precisely so it can decide
        // whether spending the pin is warranted. Checking the pin here made
        // that question unanswerable and the pin unspendable.
        // Mid-drag on the sidebar seam: the pointer is over the editor by
        // definition, and collapsing under the cursor is the flapping the
        // issue calls out.
        if self.splitter_drag.is_some() {
            return false;
        }
        // Anything modal may be anchored over sidebar space, and several are
        // sidebar-targeting flows (branch picker, connect dialog) that are
        // their own fields rather than `Prompt`s — checking only `prompt`
        // would have missed exactly those.
        if self.prompt.is_some()
            || self.context_menu.is_some()
            || self.connect_dialog.is_some()
            || self.modal_overlay_open()
        {
            return false;
        }
        // An Explorer drag is a drag over the sidebar the user is dragging
        // FROM; `splitter_drag` does not cover it.
        if self.tree_drag.is_some() {
            return false;
        }
        // With no activity bar there is no on-screen way back to a collapsed
        // sidebar (hover-to-reveal is not implemented yet), so a mouse-only
        // user would be stranded.
        if !self.activity_bar_visible {
            return false;
        }
        // Zen Mode already owns chrome visibility; it wins, as it does today.
        if self.zen_mode {
            return false;
        }
        true
    }

    /// Flip auto-hide and persist it. Both routes (palette command and the
    /// Customize Layout row) funnel here so they cannot drift in what they
    /// set, what they report, or whether the choice survives a restart.
    fn toggle_sidebar_auto_hide(&mut self) {
        self.sidebar_auto_hide = !self.sidebar_auto_hide;
        // Best-effort, like every other pref write: a read-only config must
        // not break the in-session toggle. Skipped under test, mirroring the
        // write-skip in `apply_theme` — `save_*` resolves the developer's real
        // ~/.config/croft/config.json, and a test has no business rewriting
        // it (nor leaving the next test to read what it wrote).
        if !cfg!(test) {
            let _ = crate::prefs::save_sidebar_auto_hide(self.sidebar_auto_hide);
        }
        // Turning it ON with the sidebar open takes effect at the next focus
        // move rather than retroactively yanking it away here — which means
        // dropping any collapse already pending. A dwell armed before the
        // setting was touched belongs to the old state: leaving it armed lets
        // an idle tick collapse the sidebar after the user turns the feature
        // off and on again, with no focus move of their own in between.
        //
        // The pin goes for the same reason, and the fourth boundary to say so.
        // `toggle_side_bar` refuses to bank one while the feature is off,
        // because "a pin set while the feature is off would sit unconsumed and
        // silently eat the first collapse after they turn it on" — and a pin
        // banked BEFORE the user disables auto-hide reaches that same state by
        // the other route. Main cleared it incidentally by taking the pin on
        // every focus move; consuming at fire time is correct but leaves each
        // boundary to say so.
        self.sidebar_dwell.disarm();
        self.sidebar_pinned_open = false;
        self.status = format!(
            "Auto-hide side bar {}",
            if self.sidebar_auto_hide { "on" } else { "off" }
        );
    }

    /// Arm the grace delay before collapsing. Called on focus moves INTO the
    /// editor or a terminal.
    ///
    /// #294 collapsed right here, which meant a click *passing through* the
    /// panel on its way to the editor took the panel out from under the
    /// pointer. The collapse now waits `AUTO_HIDE_DWELL` (#302) and fires from
    /// `tick_sidebar_auto_hide`, so a click that lands back on the sidebar
    /// inside the window cancels it.
    ///
    /// Note what is deliberately NOT done here: the one-shot pin is not
    /// consumed. Arming is no longer the same event as collapsing, and eating
    /// the exemption on an attempt the dwell then cancels would silently strip
    /// a deliberate reveal of the protection it was granted. It is consumed
    /// where the collapse actually happens.
    fn maybe_auto_hide_sidebar(&mut self) {
        // Cheap pre-check only. The real decision is re-made when the timer
        // fires, because every suppression here can change during the window.
        //
        // `sidebar_auto_hide_suspended` is the exception and MUST be read here:
        // it is scoped to a `without_auto_hide` closure and restored the moment
        // that closure returns, so by tick time it is always false. Deferring
        // it would silently un-suppress every programmatic focus move — the
        // async MCP result, the launch-time file open, Enter on a sidebar row —
        // which is the #260 flapping this flag exists to prevent. Arming is
        // what has to be refused; there is nothing left to consult later.
        //
        // The STRUCTURAL suppressions (Zen Mode, hidden activity bar) are NOT
        // checked here, and that is deliberate. Refusing to arm under them
        // looks right and strands the feature: the tick stays armed through a
        // decline and fires once the suppression lifts, so that retry IS the
        // recovery path, and nothing that fails to arm can ever use it. Zen
        // survives such a refusal only because Zen exit restores the pre-Zen
        // snapshot and closes the sidebar, forcing a fresh reveal; a hidden
        // activity bar restores nothing, focus is already on the editor, and
        // production will not call `focus_pane` again for a pane that already
        // has focus — so auto-hide would stay dead for the rest of the session
        // with nothing on screen to explain it.
        //
        // The structural/transient distinction is drawn at FIRE time instead,
        // where the state is actually known and no future suppression needs its
        // own boundary hook. See `tick_sidebar_auto_hide_at`.
        if self.sidebar_auto_hide && self.show_tree && !self.sidebar_auto_hide_suspended {
            self.sidebar_dwell.arm(std::time::Instant::now());
        }
    }

    /// Tear down the popups a click invalidates, for press paths that return
    /// early and so miss the teardown every other path runs.
    ///
    /// A fired binding changes the state underneath these popups, and leaving
    /// them up paints a hover, a tab tooltip or a button hint describing what
    /// was there before the command ran. Shared by the matched-gesture
    /// dispatch and the double-click-prefix swallow: both return early, and
    /// having two copies is how the swallow branch came to skip it entirely.
    fn dismiss_click_overlays(&mut self, m: MouseEvent) {
        if !matches!(m.kind, MouseEventKind::Up(_)) {
            self.hover_popup = None;
            self.hover_diagnostic = None;
        }
        self.tab_tooltip = None;
        self.tab_hover.clear();
        self.tab_hover_idx = None;
        self.ui_tooltip = None;
        self.ui_hover.clear();
        self.ui_tooltip_label = None;
        self.hover.clear();
    }

    /// Fire a pending auto-hide collapse once its grace delay elapses.
    ///
    /// Returns `true` when the sidebar collapsed, so the frame redraws.
    pub fn tick_sidebar_auto_hide(&mut self) -> bool {
        self.tick_sidebar_auto_hide_at(std::time::Instant::now())
    }

    /// `tick_sidebar_auto_hide` with the clock injected, so the grace delay is
    /// testable without sleeping — the same posture as `HoverDwell::due`.
    pub(crate) fn tick_sidebar_auto_hide_at(&mut self, now: std::time::Instant) -> bool {
        if !self.sidebar_dwell.armed() {
            return false;
        }
        // Focus came back to the sidebar, or it is already closed: the pending
        // collapse is moot. Leave the pin alone — it was never spent.
        if self.focus == Pane::Tree || !self.show_tree {
            self.sidebar_dwell.disarm();
            return false;
        }
        if !self.sidebar_dwell.due(now, AUTO_HIDE_DWELL) {
            return false;
        }
        // The window has elapsed and focus stayed away. Before spending
        // anything, ask whether a collapse would fire at all: a tick stopped by
        // a seam drag, an open palette or a modal is not the collapse the pin
        // was banked for, and burning it there loses an exemption the user
        // never saw honoured. Every earlier decline already leaves the pin
        // alone; this makes the late one behave the same way.
        //
        // Stay ARMED on that decline, and disarm only once a collapse is
        // actually due. These suppressions are transient — a drag ends, a
        // palette closes — and nothing re-arms the dwell but a fresh focus
        // move into the editor or terminal. Disarming here would drop the
        // pending collapse for good, so a user whose palette happened to be
        // open during the grace window would keep a sidebar that never
        // auto-hides again. Retrying costs nothing: `main_loop` ticks on an
        // 8ms cadence, so the collapse lands as soon as the suppression lifts.
        // A STRUCTURAL suppression DEFERS and re-stamps. Cancelling here was
        // the round-two defect: `main_loop` ticks every 8ms unconditionally, so
        // a cancel-on-suppressed-tick fires 8ms after arming and is
        // indistinguishable from refusing to arm at all — which strands the
        // feature, because nothing re-arms once a hidden activity bar returns
        // (focus never moved, and production will not re-focus a pane that
        // already has focus).
        //
        // Re-stamping is what makes deferral safe. The complaint against
        // deferral was that Zen can last an hour and the collapse would land on
        // the frame it exits, for a focus move the user has long forgotten.
        // Anchoring to the moment the suppression LIFTS answers that exactly:
        // the user then gets the same AUTO_HIDE_DWELL grace they would get from
        // a fresh focus move, measured from a moment they can actually perceive
        // — the chrome coming back.
        if self.sidebar_structurally_suppressed() {
            self.sidebar_dwell.restamp(now);
            return false;
        }
        if !self.sidebar_auto_hide_allowed() {
            return false;
        }
        self.sidebar_dwell.disarm();
        // A real collapse is now due, so this IS the moment the one-shot
        // exemption is spent — whether or not it is what stops us.
        //
        // Semantics: the pin is spent by the next collapse that would genuinely
        // have fired, not by the next tick — so a tick stopped by a TRANSIENT
        // suppression (seam drag, palette, modal) spends nothing and the pin
        // survives to do its job a moment later.
        //
        // Structural suppressions are decided HERE, above, not at the sites
        // that enter them. Entry hooks cannot see the case where the dwell is
        // armed while the suppression is ALREADY in force — Cmd+B works inside
        // Zen, so no transition occurs and no hook fires. This tick is asked to
        // distinguish a suppression that lasts a moment from one that lasts the
        // session precisely because it is the one place that always runs.
        let exempt = std::mem::take(&mut self.sidebar_pinned_open);
        if !exempt {
            self.show_tree = false;
            return true;
        }
        false
    }

    fn focus_pane(&mut self, p: Pane) {
        // Leaving the terminal closes its find bar so a stale match highlight
        // never lingers on the grid once input goes elsewhere. Quick-select
        // labels are torn down for the same reason.
        if p != Pane::Terminal && self.terminal_find.is_some() {
            self.close_terminal_find();
        }
        if p != Pane::Terminal && self.terminal_quick_select.is_some() {
            self.close_terminal_quick_select();
        }
        if p != Pane::Terminal && self.terminal_copy_mode.is_some() {
            self.close_terminal_copy_mode();
        }
        // A maximized terminal gives the editor zero rows; focusing the
        // editor is always an intent to use it, so restore it (VS Code's
        // convention when a file is revealed over a maximized panel).
        // `terminal_pane_maximized` (width, among terminal panes) is
        // unrelated and stays.
        if p == Pane::Editor && self.terminal_maximized {
            self.terminal_maximized = false;
        }
        // Auto-hide (#260): moving into the editor or a terminal collapses
        // the sidebar; moving INTO the sidebar releases the pin a reveal
        // command took, so the next move out can collapse it again.
        match p {
            Pane::Tree => {
                self.sidebar_pinned_open = false;
                // Focus came back inside the grace window: the click was
                // passing through, or landed here. Cancel the pending
                // collapse (#302) rather than letting it fire under the user.
                self.sidebar_dwell.disarm();
            }
            Pane::Editor | Pane::Terminal => self.maybe_auto_hide_sidebar(),
        }
        self.focus = p;
        self.sync_focus_flags();
        if self.editor.focused {
            self.poke_cursor();
        }
        // Group focus changes the active FILE without opening anything and
        // without a path (#369): `focus_editor_group` and
        // `move_active_editor` swap another group into `self.editor`, so
        // neither the open-based sync nor a path-argument guard sees them.
        // Every focus change lands here, so this is the one place that does.
        self.drop_symbol_tab_if_file_changed();
    }

    fn sync_focus_flags(&mut self) {
        // Focus must never rest on a COLLAPSED pane (#313). A folded pane is
        // one column wide and is never rendered, so it paints no cursor and no
        // focus border: the user would be typing into a pane they cannot see
        // receiving it.
        //
        // Enforced HERE rather than at each gesture. The first attempt guarded
        // `cycle_terminal` alone, which left closing the pane beside a folded
        // one, the maximize rail, and a right-click on a strip - the last of
        // which that same round OPENED, since making a strip right-clickable
        // also made it focusable. A fix at the call site closes the path you
        // were looking at; a fix at the invariant closes the ones you were not.
        //
        // Two things this function does NOT do, contrary to an earlier
        // version of this comment. It is not called per frame - there are
        // eleven call sites, none in a render path - and it is not on every
        // path that moves `active_terminal`: `activate_terminal_pane` and
        // `move_terminal` both assign without calling it. Those two are safe
        // for reasons of their own (the first takes its index from
        // `terminal_at_pos`, which cannot name a folded pane because its
        // `last_area` is cleared; the second keeps the active pane pointed at
        // its own terminal), so the invariant's totality rests on those
        // reasons rather than on this being a universal funnel. A change to
        // what feeds `terminal_at_pos` would break it silently.
        //
        // And this is the rule for focus that DRIFTS. A caller deliberately
        // choosing a pane by index wants it made visible instead, which is
        // `reveal_terminal_pane`.
        //
        // Skipped while a pane is maximized: the flags are deliberately
        // ignored there and the active pane is painted full width whatever it
        // holds, so moving focus would fight the user's own selection. Leaving
        // maximize calls back through here, which is where it is repaired.
        if !self.terminal_pane_maximized
            && self
                .terminals
                .get(self.active_terminal)
                .is_some_and(|t| t.collapsed)
            && let Some(next) = self
                .terminals
                .iter()
                .enumerate()
                .filter(|(_, t)| !t.collapsed)
                .min_by_key(|(candidate, _)| candidate.abs_diff(self.active_terminal))
                .map(|(candidate, _)| candidate)
        {
            self.active_terminal = next;
        }
        // Quick-select is bound to the pane it opened on; this per-frame
        // invariant covers every gesture that can move `active_terminal`
        // (clicks, chords, pane closes shifting indices) in one place, so
        // stale labels never survive a pane switch to hijack the new pane.
        if self
            .terminal_quick_select
            .as_ref()
            .is_some_and(|st| st.pane != self.active_terminal)
        {
            self.close_terminal_quick_select();
        }
        // Terminal find is pane-bound the same way.
        if self.terminal_find.is_some() && self.terminal_find_pane != self.active_terminal {
            self.close_terminal_find();
        }
        self.tree.focused = self.focus == Pane::Tree && self.sidebar_view == SidebarView::Explorer;
        self.search.focused = self.focus == Pane::Tree && self.sidebar_view == SidebarView::Search;
        self.source_control.focused =
            self.focus == Pane::Tree && self.sidebar_view == SidebarView::SourceControl;
        self.remote.focused = self.focus == Pane::Tree && self.sidebar_view == SidebarView::Remote;
        self.run_debug.focused =
            self.focus == Pane::Tree && self.sidebar_view == SidebarView::RunDebug;
        self.extensions.focused =
            self.focus == Pane::Tree && self.sidebar_view == SidebarView::Extensions;
        self.editor.focused = self.focus == Pane::Editor;
        // Inactive groups are by definition NOT the focused editor group, so
        // their borders never light up even while the editor pane holds focus.
        // `editor` (the active group) carries the highlight.
        for group in self.editor_layout.inactive_groups_mut() {
            group.focused = false;
        }
        let focused_pane = self.focus == Pane::Terminal;
        let active = self.active_terminal;
        for (i, t) in self.terminals.iter_mut().enumerate() {
            t.focused = focused_pane && i == active;
        }
        // Only the Black theme dresses the focused pane in the gradient
        // border; Croft Dark keeps the historical solid-blue highlight.
        let gradient = self.theme.gradient();
        // Every editor in both groups, not just the active one (deref would
        // only hit the active editor): a tab switch or the split group must
        // not resurrect the legacy navy active-tab chip between syncs.
        // The bundled PDF / CSV viewers are gated by the Extensions panel:
        // when disabled, the editor opens those file types as plain text.
        let pdf_on = self.is_extension_enabled("pdf");
        let csv_on = self.is_extension_enabled("csv");
        for ed in self.editor.editors.iter_mut() {
            ed.focus_gradient = gradient;
            ed.theme = self.theme;
            ed.pdf_viewer_enabled = pdf_on;
            ed.csv_viewer_enabled = csv_on;
            ed.show_indent_guides = self.indent_guides_enabled;
            ed.show_bracket_colors = self.bracket_colors_enabled;
            ed.provenance_overlay = self.provenance_overlay;
            ed.whitespace_mode = self.whitespace_mode;
            ed.diff_ws_default = self.diff_ws_default;
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in group.editors.iter_mut() {
                ed.focus_gradient = gradient;
                ed.theme = self.theme;
                ed.pdf_viewer_enabled = pdf_on;
                ed.csv_viewer_enabled = csv_on;
                ed.show_indent_guides = self.indent_guides_enabled;
                ed.show_bracket_colors = self.bracket_colors_enabled;
                ed.provenance_overlay = self.provenance_overlay;
                ed.whitespace_mode = self.whitespace_mode;
                ed.diff_ws_default = self.diff_ws_default;
                ed.diff_ws_default = self.diff_ws_default;
            }
        }
        self.tree.focus_gradient = gradient;
        self.tree.theme = self.theme;
        self.search.focus_gradient = gradient;
        self.search.theme = self.theme;
        self.source_control.focus_gradient = gradient;
        self.source_control.theme = self.theme;
        self.refresh_scm_repositories();
        self.run_debug.focus_gradient = gradient;
        self.run_debug.theme = self.theme;
        let explorer_focused =
            self.focus == Pane::Tree && self.sidebar_view == SidebarView::Explorer;
        self.outline.focus_gradient = gradient;
        self.outline.theme = self.theme;
        self.outline.focused = explorer_focused;
        self.open_editors.focus_gradient = gradient;
        self.open_editors.theme = self.theme;
        self.open_editors.focused = explorer_focused;
        self.timeline.focus_gradient = gradient;
        self.timeline.theme = self.theme;
        self.timeline.focused = explorer_focused;
        self.commit_graph.focus_gradient = gradient;
        self.commit_graph.theme = self.theme;
        self.commit_graph.focused =
            self.focus == Pane::Tree && self.sidebar_view == SidebarView::SourceControl;
        self.dependencies.focus_gradient = gradient;
        self.dependencies.theme = self.theme;
        self.dependencies.focused = explorer_focused;
        self.remote.focus_gradient = gradient;
        self.remote.theme = self.theme;
        self.extensions.theme = self.theme;
        self.problems.focus_gradient = gradient;
        self.problems.theme = self.theme;
        self.problems.focused = self.focus == Pane::Terminal;
        self.problems.hover_pointer = self.pointer_cell;
        self.problems.fix_glyph = match self.problems_fix_started {
            Some(t) => update_spinner_frame(t.elapsed().as_millis()),
            None => "",
        };
        self.output.focus_gradient = gradient;
        self.output.theme = self.theme;
        self.output.focused = self.focus == Pane::Terminal;
        self.output.hover_pointer = self.pointer_cell;
        self.output.sync();
        self.ports.focus_gradient = gradient;
        self.ports.theme = self.theme;
        self.ports.focused = self.focus == Pane::Terminal;
        self.ports.hover_pointer = self.pointer_cell;
        for t in self.terminals.iter_mut() {
            t.show_timestamps = self.show_terminal_timestamps;
        }
        self.captures.focus_gradient = gradient;
        self.captures.theme = self.theme;
        self.captures.focused = self.focus == Pane::Terminal;
        self.captures.hover_pointer = self.pointer_cell;
        for t in self.terminals.iter_mut() {
            t.focus_gradient = gradient;
            t.theme = self.theme;
            t.set_palette(self.theme.ansi());
        }
        self.dress_host_accents();
    }

    /// Host accents: each pane's shell-reported OSC 7 host against the prefs
    /// rules (first match wins). Cleared the moment the host stops matching
    /// (an in-pane SSH session ends). Runs from `sync_focus_flags` AND at the
    /// top of `render`: the OSC 7 host arrives on a PTY reader thread with no
    /// input event behind it, so the PTY-dirty redraw is the only wakeup —
    /// dressing must not wait for the next key or click.
    fn dress_host_accents(&mut self) {
        for t in self.terminals.iter_mut() {
            let dress = t.shell_host().and_then(|h| {
                self.host_accents
                    .iter()
                    .find(|(m, _, _)| m.is_match(&h))
                    .map(|(_, c, b)| (*c, b.clone()))
            });
            match dress {
                Some((c, b)) => {
                    t.accent = Some(c);
                    t.accent_badge = b;
                }
                None => {
                    t.accent = None;
                    t.accent_badge = None;
                }
            }
        }
    }

    /// Whether popups/menus/tooltips should wear the orange→green gradient
    /// border and the muted dark-teal selection fill instead of the legacy
    /// bright-blue accent. Gated on the Black theme to mirror the focused-pane
    /// border, so Croft Dark keeps its coherent all-blue look.
    fn popup_gradient(&self) -> bool {
        self.theme.gradient()
    }

    /// Paint the bottom panel group's tab strip (PROBLEMS / TERMINAL) across
    /// `strip` (its top row) and record each tab's hit rect. The active tab is
    /// bright/bold; the inactive one is dim, mirroring VS Code's panel tabs. A
    /// non-zero problem count rides the PROBLEMS label as a badge.
    fn paint_panel_tabs(&mut self, frame: &mut ratatui::Frame, strip: Rect) {
        use ratatui::widgets::Block;
        let strip_bg = self.theme.editor_bg();
        frame.render_widget(Block::default().style(Style::default().bg(strip_bg)), strip);
        let brand = self.theme.gradient();
        let active_fg = if brand {
            crate::gradient::rgb_color(crate::gradient::PANEL_TITLE_FG)
        } else {
            self.theme.ui(Color::White)
        };
        let inactive_fg = self.theme.ui(Color::Rgb(0x80, 0x88, 0x98));
        let right = strip.x + strip.width;
        let count = self.problems.total_count();
        let pointer = self.pointer_cell;
        let orange = crate::gradient::rgb_color(crate::gradient::GRAD_TR);
        let badge_fg = self.theme.ui(Color::Rgb(0x1a, 0x12, 0x0a));
        let active = self.bottom_panel_tab;

        self.problems_tab_rect = Rect::default();
        self.output_tab_rect = Rect::default();
        self.ports_tab_rect = Rect::default();
        self.captures_tab_rect = Rect::default();
        self.terminal_tab_rect = Rect::default();
        // In images mode the count rides as an orange circle (the same raster
        // badge as the activity bar), emitted post-frame; recompute its anchor
        // each paint. Glyph-fallback terminals keep the powerline-cap pill.
        let images = self.overlays.activity.has_images();
        self.problems_badge_cell = None;

        // VS Code panel-group order: PROBLEMS, OUTPUT, TERMINAL, PORTS. PROBLEMS
        // alone carries the orange count badge after its label.
        let tabs = [
            (BottomPanelTab::Problems, " PROBLEMS "),
            (BottomPanelTab::Output, " OUTPUT "),
            (BottomPanelTab::Terminal, " TERMINAL "),
            (BottomPanelTab::Ports, " PORTS "),
            (BottomPanelTab::Captures, " CAPTURES "),
        ];

        // Lay each tab out left to right, recording its hit rect (which, for
        // PROBLEMS, spans the label and the pill together).
        let mut placed: Vec<(BottomPanelTab, &str, Rect, u16)> = Vec::with_capacity(tabs.len());
        let mut x = strip.x + 1;
        for (tab, label) in tabs {
            if x >= right {
                break;
            }
            let badge_w = if tab == BottomPanelTab::Problems && count > 0 {
                if images {
                    crate::iterm2_inline::count_badge_cells_w(count)
                } else {
                    format!("{count}").chars().count() as u16 + 2
                }
            } else {
                0
            };
            let w = label.chars().count() as u16 + badge_w;
            let rect = Rect {
                x,
                y: strip.y,
                width: w.min(right.saturating_sub(x)),
                height: 1,
            };
            match tab {
                BottomPanelTab::Problems => self.problems_tab_rect = rect,
                BottomPanelTab::Output => self.output_tab_rect = rect,
                BottomPanelTab::Ports => self.ports_tab_rect = rect,
                BottomPanelTab::Captures => self.captures_tab_rect = rect,
                BottomPanelTab::Terminal => self.terminal_tab_rect = rect,
            }
            placed.push((tab, label, rect, badge_w));
            x = x.saturating_add(w + 1);
        }

        let buf = frame.buffer_mut();
        for (tab, label, rect, badge_w) in &placed {
            let is_active = *tab == active;
            // Active tab: brand fg + bold (and underlined below). Hover brightens
            // an inactive tab; the rest stay dim.
            let style = if is_active {
                Style::default()
                    .fg(active_fg)
                    .bg(strip_bg)
                    .add_modifier(Modifier::BOLD)
            } else if crate::widgets::hover::row_hover_bg(*rect, pointer, self.theme).is_some() {
                Style::default().fg(active_fg).bg(strip_bg)
            } else {
                Style::default().fg(inactive_fg).bg(strip_bg)
            };
            if rect.x < right {
                buf.set_stringn(
                    rect.x,
                    rect.y,
                    label,
                    right.saturating_sub(rect.x) as usize,
                    style,
                );
            }
            // Orange count badge after PROBLEMS. In images mode it's a raster
            // circle (matching the activity-bar badges) emitted post-frame, so
            // the cells stay blank strip_bg and we just record the anchor.
            // Otherwise the powerline-cap pill is drawn as text.
            if *badge_w > 0 {
                let bx = rect.x + label.chars().count() as u16;
                if images {
                    if bx < right {
                        self.problems_badge_cell = Some((bx, rect.y));
                    }
                } else {
                    let badge_text = format!("{count}");
                    let cap_style = Style::default().fg(orange).bg(strip_bg);
                    if bx < right {
                        buf.set_string(bx, rect.y, "\u{e0b6}", cap_style);
                    }
                    let inner_start = bx + 1;
                    if inner_start < right {
                        buf.set_stringn(
                            inner_start,
                            rect.y,
                            &badge_text,
                            right.saturating_sub(inner_start) as usize,
                            Style::default()
                                .fg(badge_fg)
                                .bg(orange)
                                .add_modifier(Modifier::BOLD),
                        );
                    }
                    let cap_r = inner_start + badge_text.chars().count() as u16;
                    if cap_r < right {
                        buf.set_string(cap_r, rect.y, "\u{e0b4}", cap_style);
                    }
                }
            }
            // The active-tab underline (VS Code's indicator) hugs the word only,
            // stopping before the padding spaces and the pill.
            if is_active {
                let leading = label.chars().take_while(|c| *c == ' ').count() as u16;
                let word_len = label.trim().chars().count() as u16;
                let start = rect.x + leading;
                for ux in start..(start + word_len).min(right) {
                    buf[(ux, rect.y)].modifier.insert(Modifier::UNDERLINED);
                }
            }
        }
    }

    /// Switch the bottom panel group's active tab, ensuring the panel is
    /// visible and the panel pane is focused so the new view is usable at once.
    fn set_bottom_panel_tab(&mut self, tab: BottomPanelTab) {
        self.bottom_panel_tab = tab;
        if !self.show_terminal {
            self.show_terminal = true;
        }
        self.focus_pane(Pane::Terminal);
    }

    /// Split the editor into two side-by-side columns (`Cmd+\`). The new
    /// group duplicates the active file (re-opens its path, copies the
    /// cursor/scroll position) and takes focus, landing in the right
    /// column. No-op if already split or the active tab has no path on
    /// disk (a blank/unsaved buffer has nothing to mirror).
    /// "Split Editor Right": split the active group side by side, the new
    /// focused duplicate to the right. The default split, on `Cmd+\`.
    fn split_editor(&mut self) {
        self.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    }

    /// Split the active group, duplicating its file into a new focused group
    /// placed in the direction the caller asks for. `dir` chooses the seam's
    /// orientation (Horizontal = side by side, Vertical = stacked) and
    /// `new_after` whether the NEW group sits after the existing one (right /
    /// below) or before it (left / above) — the four VS Code Split commands:
    /// Right = (H, after), Left = (H, before), Down = (V, after), Up = (V,
    /// before). Splitting is offered only from an unsplit editor for now.
    fn split_editor_dir(&mut self, dir: editor_layout::SplitDir, new_after: bool) {
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("Cannot split: save the file first");
            return;
        };
        // A fresh EditorTabs starts blank-initial; `open_preview` reuses
        // that placeholder tab so the new group holds exactly the file
        // (not a stray blank tab beside it). Opening it as the PREVIEW
        // slot - not pinned - means the next file the user opens in this
        // column swaps straight into it (clean "left = A, right = B"
        // comparison) rather than stacking a second tab. Editing or
        // double-clicking pins it, as everywhere else.
        let mut group = EditorTabs::default();
        if group.open_preview(&path).is_err() {
            self.status = String::from("Cannot split: failed to open file");
            return;
        }
        // Mirror the source view state (caret + scroll, incl. the wrap
        // sub-line offset) so the duplicate opens exactly where the
        // source was rather than at the top of the file.
        group.copy_view_position_from(&self.editor);
        // The new focused group (now in `self.editor`, always the active leaf)
        // takes the active slot; the existing group settles into the sibling.
        let existing = std::mem::replace(&mut self.editor, group);
        self.editor_layout.split_active(existing, dir, new_after);
        self.focus_pane(Pane::Editor);
    }

    /// VS Code "Move Editor into <dir> Group": relocate the active tab to the
    /// group adjacent in `dir`. If a neighbour exists there the tab moves into
    /// it (the source collapses when its last tab leaves); otherwise a new group
    /// is created in that direction holding the moved tab. Moving the only tab
    /// of a single group with no neighbour is a no-op (nowhere to move to).
    fn move_active_editor(&mut self, dir: editor_layout::Dir) {
        // A nominal area: seam adjacency is scale-invariant, so the exact pane
        // size doesn't matter for finding the directional neighbour.
        let synth = ratatui::layout::Rect::new(0, 0, 10_000, 10_000);
        match self.editor_layout.neighbor_leaf_in_dir(synth, 1, dir) {
            Some(target) => {
                let moved = self.editor.take_active_editor();
                let source_emptied = self.editor.is_blank_initial();
                let reduced = std::mem::take(&mut self.editor);
                self.editor = self.editor_layout.refocus_to_dfs(reduced, target);
                self.editor.push_editor(moved);
                if source_emptied {
                    self.editor_layout
                        .prune_blank_inactive(|t| t.is_blank_initial());
                }
                self.focus_pane(Pane::Editor);
            }
            None => {
                if self.editor.tab_count() <= 1 {
                    self.status = String::from("Move: the editor is already a single group");
                    return;
                }
                let moved = self.editor.take_active_editor();
                let mut group = EditorTabs::default();
                group.push_editor(moved);
                let existing = std::mem::replace(&mut self.editor, group);
                self.editor_layout
                    .split_active(existing, dir.split_dir(), dir.places_new_after());
                self.focus_pane(Pane::Editor);
            }
        }
    }

    /// VS Code "Split in Group": open a second view of the active file beside
    /// it. A TUI has no true in-group sub-view, so the observable equivalent is
    /// a side-by-side split duplicating the active file — the same result as
    /// Split Right.
    fn split_in_group(&mut self) {
        self.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    }

    /// Move keyboard focus to the editor group in the given physical
    /// column (`true` = left, `false` = right). Hoists the active group
    /// through `editor_layout` so the focused group is always `editor`, keeping
    /// the physical columns fixed. No-op when not split or already focused
    /// there.
    fn focus_editor_group(&mut self, want_left: bool) {
        if !self.editor_layout.is_split() {
            return;
        }
        // Physical columns map to depth-first leaf order: leftmost = 0,
        // rightmost = last. Hoist the active group out and pull the target
        // leaf's group into `self.editor` so the invariant holds.
        let target = if want_left {
            0
        } else {
            self.editor_layout.leaf_count() - 1
        };
        if self.editor_layout.active_dfs_index() == target {
            // Already focused there; the chord still doubles as "focus editor".
            if self.focus != Pane::Editor {
                self.focus_pane(Pane::Editor);
            }
            return;
        }
        let current = std::mem::take(&mut self.editor);
        self.editor = self.editor_layout.refocus_to_dfs(current, target);
        self.focus_pane(Pane::Editor);
    }

    /// The seam (if any) the cell `(col, row)` lands on, using the same
    /// two-cell hit-zone as the sidebar/terminal seams. Returns a clone so an
    /// in-flight drag can hold the boundary across frames.
    fn seam_at(&self, col: u16, row: u16) -> Option<editor_layout::Seam> {
        self.editor_seams
            .iter()
            .find(|s| match s.dir {
                editor_layout::SplitDir::Horizontal => {
                    (col == s.pos || col == s.pos.saturating_sub(1))
                        && row >= s.cross_start
                        && row < s.cross_end
                }
                editor_layout::SplitDir::Vertical => {
                    (row == s.pos || row == s.pos.saturating_sub(1))
                        && col >= s.cross_start
                        && col < s.cross_end
                }
            })
            .cloned()
    }

    /// After a tab close, collapse the split if the focused group ran out
    /// of real tabs. The surviving (other) group becomes the sole editor.
    fn collapse_split_if_empty(&mut self) {
        // While a full-screen window is open, `editor` is the window and the
        // grid is parked out of the tree — collapsing here would fold the
        // parked grid into the window. The window's own emptiness is handled by
        if !self.editor_layout.is_split() || !self.editor.is_blank_initial() {
            return;
        }
        // The focused group is empty; drop it and promote a surviving group to
        // become the new active editor. Evict the right slot's image so it
        // can't ghost after the column disappears.
        self.editor = self.editor_layout.collapse_active();
        self.editor_seams.clear();
        self.disable_editor_image(1);
        // Focus stays on the editor pane; just re-light the promoted
        // group's border. (No `focus_pane` so this is safe to call from
        // any close path without re-poking the cursor mid-frame.)
        self.sync_focus_flags();
    }

    /// VS Code "Move into New Window": open the tab at `idx` in a brand-new
    /// window of the host terminal (a real, separate window running croft on the
    /// same workspace with the file open), then close the tab here — the file
    /// has moved to the new window. The current window is otherwise untouched.
    fn move_into_new_window(&mut self, idx: usize) {
        if !self.open_tab_in_new_window(idx) {
            return;
        }
        // The file now lives in the new window; drop it from this one. Mirrors
        // MenuAction::CloseTab so the split collapses if this was its last tab.
        let label = self.editor.tab_display_label(idx);
        if self.editor.close_tab(idx) {
            self.sync_open_file_poll_mtime();
            self.poke_cursor();
            self.collapse_split_if_empty();
        }
        self.status = format!("{label}: moved into a new window");
    }

    /// VS Code "Copy into New Window" (⌘K O): open the tab at `idx` in a
    /// brand-new OS terminal window, leaving the original tab exactly where it
    /// is. The current window is not touched at all.
    fn copy_into_new_window(&mut self, idx: usize) {
        if !self.open_tab_in_new_window(idx) {
            return;
        }
        let label = self.editor.tab_display_label(idx);
        self.status = format!("{label}: copied into a new window");
    }

    /// Spawn a new OS terminal window running croft on the current workspace
    /// with the tab at `idx` opened. Returns false (and sets a status) when the
    /// action can't run: an unsaved/path-less buffer, a remote session (no
    /// local window server on the headless host), or a spawn failure. Shared by
    /// Move and Copy into New Window — the only difference is what the caller
    /// does to the source tab afterwards.
    fn open_tab_in_new_window(&mut self, idx: usize) -> bool {
        // A new croft process opens a file by path, so an untitled buffer has
        // nothing to hand off.
        let Some(path) = self.editor.tab_path(idx) else {
            self.status = String::from("New Window: save the file first");
            return false;
        };
        // A new OS window only exists where croft can talk to a window server:
        // the local machine. Over SSH croft runs on the headless host.
        if self.is_remote {
            self.status = String::from("New Window: not available over SSH");
            return false;
        }
        match spawn_new_window(&self.tree.root, &path) {
            Ok(()) => true,
            Err(e) => {
                self.status = format!("New Window failed: {e}");
                false
            }
        }
    }

    fn render(&mut self, frame: &mut ratatui::Frame) {
        let size = frame.area();
        self.last_frame_area = size;
        // Redaction reveal is app state; each pane paints from its own copy.
        let reveal = self.redactions_revealed();
        for t in self.terminals.iter_mut() {
            t.reveal_redactions = reveal;
        }
        // Hit rects must describe the frame being painted, not the last
        // frame that happened to include a section. A section that stops
        // rendering (Explorer's OPEN EDITORS / TIMELINE / DEPENDENCIES /
        // OUTLINE after a switch to Source Control) otherwise keeps its
        // stale rect, and `handle_mouse`'s containment checks swallow every
        // click the current view paints in those cells — the COMMITS graph
        // sits exactly there and its clicks went dead (#103). Zero them all
        // up front; each section's render re-records the live ones this
        // frame (the OSK does the same for its collapsed band).
        for rect in [
            &mut self.open_editors.last_area,
            &mut self.open_editors.last_scrollbar,
            &mut self.timeline.last_area,
            &mut self.timeline.last_scrollbar,
            &mut self.dependencies.last_area,
            &mut self.dependencies.last_scrollbar,
            &mut self.outline.last_area,
            &mut self.outline.last_scrollbar,
            &mut self.commit_graph.last_area,
            &mut self.commit_graph.last_scrollbar,
        ] {
            *rect = Rect::default();
        }
        self.dress_host_accents();
        self.expire_ssh_offer();
        self.sync_lane_root_badges();
        // Theme background, whole frame. croft's chrome (the sidebar panels,
        // explorer sections, activity bar, gaps) mostly paints `Color::Reset`
        // and leans on the iTerm2 `SetColors` session bg to color it. Ghostty /
        // Kitty / sixel ignore `SetColors`, so those Reset cells fall through to
        // the host terminal's own background (black), leaving only the surfaces
        // that fill an explicit bg (editor, terminal) themed. Prefilling the
        // frame with the theme bg colors every unfilled cell; widgets that set
        // their own bg override it (ratatui patches bg only when `Some`). Gated
        // to exactly the hosts where `SetColors` is NOT emitted (see
        // `apply_theme`): on iTerm2 the session bg already handles this and a
        // full-frame fill would force the OSC-1337 activity images to re-emit
        // every frame.
        if !crate::iterm2_inline::detect_iterm2_inline_support() {
            frame.render_widget(
                ratatui::widgets::Block::default()
                    .style(Style::default().bg(self.theme.editor_bg())),
                size,
            );
        }
        // The on-screen keyboard docks as a band between the panes and the
        // status bar, scaling its keys to thumb size on tall frames; frames
        // too short to host it keep it collapsed so the workspace can't be
        // squeezed into nothing.
        let osk_h = if self.osk.is_some() && size.height >= OSK_MIN_FRAME_HEIGHT {
            crate::widgets::osk::band_height(size.height)
        } else {
            0
        };
        // The bottom status bar can be hidden (Customize Layout / Zen Mode),
        // reclaiming its row for the workspace.
        let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
        let outer = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Min(1),
                Constraint::Length(osk_h),
                Constraint::Length(status_h),
            ])
            .split(size);
        let main_area = outer[0];

        // Reserve the activity bar (when shown) and the secondary side bar,
        // then clamp the primary side bar so the editor keeps RIGHT_PANE_MIN.
        let activity_w = if self.activity_bar_visible {
            ACTIVITY_BAR_WIDTH
        } else {
            0
        };
        let secondary_w = if self.secondary_side_bar_visible {
            SECONDARY_SIDEBAR_WIDTH
        } else {
            0
        };
        let max_sidebar = main_area
            .width
            .saturating_sub(activity_w)
            .saturating_sub(secondary_w)
            .saturating_sub(RIGHT_PANE_MIN);
        let sidebar_w = self
            .sidebar_width
            .clamp(SIDEBAR_WIDTH_MIN, max_sidebar.max(SIDEBAR_WIDTH_MIN));
        // Persist the clamped value so subsequent drags start from where
        // the user can actually see the splitter.
        self.sidebar_width = sidebar_w;

        // Panel Alignment = Justify spans the panel across the full content
        // width (under the side bar): carve it off the bottom of `main` BEFORE
        // the horizontal chrome split, so the side bars sit above it.
        let justify_panel = self.show_terminal
            && !self.terminal_maximized
            && osk_h == 0
            && self.panel_alignment == PanelAlignment::Justify;
        let (chrome_area, justify_terminal) = if justify_panel {
            let total_h = main_area.height;
            let max_h = total_h
                .saturating_sub(EDITOR_HEIGHT_MIN)
                .max(TERMINAL_HEIGHT_MIN);
            let term_h = self
                .terminal_height
                .unwrap_or(total_h / 3)
                .clamp(TERMINAL_HEIGHT_MIN, max_h);
            self.terminal_height = Some(term_h);
            let rows = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Min(EDITOR_HEIGHT_MIN),
                    Constraint::Length(term_h),
                ])
                .split(main_area);
            (rows[0], Some(rows[1]))
        } else {
            (main_area, None)
        };

        // Pure horizontal split of the workspace chrome (honors activity-bar
        // visibility, side bar position, and the secondary side bar).
        let chrome = compute_chrome_layout(
            chrome_area,
            self.activity_bar_visible,
            self.show_tree,
            self.secondary_side_bar_visible,
            self.side_bar_position,
            sidebar_w,
            SECONDARY_SIDEBAR_WIDTH,
        );
        let activity_area = chrome.activity;
        let side_area = chrome.primary_side;
        let secondary_area = chrome.secondary_side;
        let right_area = chrome.right;
        // Remember the Explorer column so the zoxide jump popup can anchor
        // over it instead of centering on the whole frame.
        self.last_sidebar_area = side_area;
        self.sidebar_splitter_x = chrome.sidebar_splitter_x;
        self.last_content_width = right_area.width;
        self.last_content_height = right_area.height;

        // Editor ↔ terminal split within the editor column. `terminal_band` is
        // the full bottom strip; `terminal_area` is where the terminals draw
        // (narrower than the band under Left/Right alignment).
        let (editor_area, terminal_area, terminal_band) = if let Some(jt) = justify_terminal {
            // The panel was already carved full-width from `main`; the editor
            // fills the rest of its column and the splitter sits at the seam.
            self.terminal_splitter_y = Some(jt.y);
            (right_area, Some(jt), Some(jt))
        } else if osk_h > 0 && self.focus == Pane::Terminal && self.show_terminal {
            let zero_editor = Rect {
                x: right_area.x,
                y: right_area.y,
                width: right_area.width,
                height: 0,
            };
            self.terminal_splitter_y = None;
            (zero_editor, Some(right_area), Some(right_area))
        } else if osk_h > 0 {
            self.terminal_splitter_y = None;
            (right_area, None, None)
        } else if self.show_terminal {
            if self.terminal_maximized {
                // Editor / welcome collapses; terminal fills the entire
                // right column next to the Explorer. Splitter is hidden
                // because there is nothing to drag against.
                let zero_editor = Rect {
                    x: right_area.x,
                    y: right_area.y,
                    width: right_area.width,
                    height: 0,
                };
                self.terminal_splitter_y = None;
                (zero_editor, Some(right_area), Some(right_area))
            } else {
                let total_h = right_area.height;
                let pinned = self.terminal_height.map(|h| {
                    h.clamp(
                        TERMINAL_HEIGHT_MIN,
                        total_h
                            .saturating_sub(EDITOR_HEIGHT_MIN)
                            .max(TERMINAL_HEIGHT_MIN),
                    )
                });
                let rows = if let Some(term_h) = pinned {
                    self.terminal_height = Some(term_h);
                    Layout::default()
                        .direction(Direction::Vertical)
                        .constraints([
                            Constraint::Min(EDITOR_HEIGHT_MIN),
                            Constraint::Length(term_h),
                        ])
                        .split(right_area)
                } else {
                    Layout::default()
                        .direction(Direction::Vertical)
                        .constraints([Constraint::Percentage(65), Constraint::Percentage(35)])
                        .split(right_area)
                };
                self.terminal_splitter_y = Some(rows[1].y);
                let band = rows[1];
                // Left/Right alignment hugs the panel to that half of the band.
                let term = panel_band_rect(band, self.panel_alignment);
                (rows[0], Some(term), Some(band))
            }
        } else {
            self.terminal_splitter_y = None;
            (right_area, None, None)
        };

        if let Some(activity_area) = activity_area {
            self.render_activity_bar(frame, activity_area);
        } else {
            // Hidden activity bar: zero the icon hit-rects so clicks and the
            // post-draw OSC image flush both treat it as absent (no ghosting).
            self.sidebar_areas = SidebarAreas::default();
        }

        // Secondary side bar: the active file's Outline, on the edge opposite
        // the primary side bar.
        self.render_secondary_side_bar(frame, secondary_area);

        if let Some(area) = side_area {
            let usable_area = area;
            // Feed the render-time pointer cell to every side panel so the row
            // under the cursor (and the remote header pills) can light up,
            // mirroring the editor tab strip and terminal pane buttons.
            let panel_pointer = self.pointer_cell;
            self.tree.hover_pointer = panel_pointer;
            self.search.hover_pointer = panel_pointer;
            self.source_control.hover_pointer = panel_pointer;
            self.remote.hover_pointer = panel_pointer;
            self.outline.hover_pointer = panel_pointer;
            self.open_editors.hover_pointer = panel_pointer;
            self.timeline.hover_pointer = panel_pointer;
            self.dependencies.hover_pointer = panel_pointer;
            self.extensions.hover_pointer = panel_pointer;
            self.commit_graph.hover_pointer = panel_pointer;
            // Explorer stacks its toggled sub-views (Open Editors / Folders /
            // Outline / Timeline / Dependencies) inside the usable strip.
            // Every other sidebar view fills it with its single activity widget.
            match self.sidebar_view {
                SidebarView::Explorer => self.render_explorer_sections(frame, usable_area),
                SidebarView::Search => frame.render_widget(&mut self.search, usable_area),
                SidebarView::SourceControl => {
                    // The COMMITS graph section docks under the change list,
                    // capped at half the strip (like the Explorer sub-views).
                    // Hidden entirely while the repo empty-state hero shows.
                    let graph_h = if self.source_control.status.in_repo {
                        self.commit_graph
                            .desired_height(usable_area.height)
                            .min(usable_area.height.saturating_sub(6))
                    } else {
                        0
                    };
                    let scm_area = Rect {
                        height: usable_area.height - graph_h,
                        ..usable_area
                    };
                    frame.render_widget(&mut self.source_control, scm_area);
                    if graph_h > 0 {
                        let graph_area = Rect {
                            y: usable_area.y + usable_area.height - graph_h,
                            height: graph_h,
                            ..usable_area
                        };
                        frame.render_widget(&mut self.commit_graph, graph_area);
                    } else {
                        self.commit_graph.last_area = Rect::default();
                    }
                }
                SidebarView::Remote => frame.render_widget(&mut self.remote, usable_area),
                SidebarView::RunDebug => frame.render_widget(&mut self.run_debug, usable_area),
                SidebarView::Extensions => frame.render_widget(&mut self.extensions, usable_area),
                SidebarView::Testing => frame.render_widget(&mut self.testing, usable_area),
            }
        }
        if !self.editor_layout.is_split() && self.editor.is_blank_initial() {
            self.render_welcome(frame, editor_area);
            // The previous frame may have rendered an image-preview tab
            // whose OSC-1337 pixels are still cached in iTerm's image
            // store. Closing that tab brings us here, but ratatui's diff
            // alone doesn't tell iTerm to drop the image — flag it so the
            // main loop wipes the screen on the next pass. Both slots, in
            // case a split was just collapsed back to the welcome screen.
            self.disable_editor_image(0);
            self.disable_editor_image(1);
            // The welcome screen has no minimap (no document to preview).
            self.disable_minimap_image();
            self.editor_seams.clear();
            // Keep the editor's hit-test rectangles fresh so the activity-bar
            // / tree click logic still works even though we skipped the
            // EditorTabs widget this frame.
            self.editor.last_full_area = editor_area;
            self.editor.last_area = Rect {
                x: editor_area.x,
                y: editor_area.y,
                width: editor_area.width,
                height: 0,
            };
        } else {
            // The editor just overdrew whatever cells the welcome image
            // occupied; if the user reopens the welcome screen we'll need
            // to re-emit it.
            self.overlays.welcome.mark_dirty();
            // Feed the render-time pointer cell to every editor group so the
            // tab strip can light the hovered tab body / close-cross pill,
            // mirroring the terminal pane buttons' hover affordance.
            let pointer = self.pointer_cell;
            self.editor.hover_pointer = pointer;
            // Breadcrumb bar: recompute the path + symbol trail for the active
            // file each frame so it tracks caret moves and outline updates.
            self.editor.breadcrumbs = self.build_breadcrumbs();
            // Sticky scroll: recompute the pinned scope headers from the top
            // visible line each frame so they track scrolling.
            self.editor.sticky_lines = self.build_sticky_lines();
            // Multiplayer ghost carets: other participants' parked carets in
            // the active file, in their colors. The current typist's caret is
            // the live cursor, so it never ghosts; departed participants drop
            // out with the roster.
            self.editor.ghost_carets = match self.editor.path.clone() {
                Some(path) if !self.session_carets.is_empty() => self
                    .session_carets
                    .iter()
                    .filter(|(id, parked)| {
                        Some(**id) != self.session_typist
                            && parked.path == path
                            && self.session_participants.iter().any(|p| p.id == **id)
                    })
                    .map(|(id, parked)| (parked.row, parked.col, participant_color(*id)))
                    .collect(),
                _ => Vec::new(),
            };
            // Collab peers' carets (Phase D independent viewports): same
            // ghost rendering, keyed by workspace-relative file, plus a name
            // tag while the caret is inside its fade window. The seated
            // navigator's caret wears its identity accent.
            self.editor.ghost_caret_labels.clear();
            if !self.collab_carets.is_empty()
                && let Some(active) = self
                    .editor
                    .path
                    .as_ref()
                    .and_then(|p| collab_file_key(&self.tree.root, p))
            {
                let navigator_sites = self
                    .pair_host
                    .as_ref()
                    .map(|h| h.caret_sites())
                    .unwrap_or_default();
                let now = std::time::Instant::now();
                for (site, c) in &self.collab_carets {
                    if c.file != active {
                        continue;
                    }
                    let color = collab_caret_color(&navigator_sites, *site);
                    self.editor.ghost_carets.push((c.row, c.col, color));
                    if !c.name.is_empty() && now.duration_since(c.last_moved) < CARET_LABEL_FADE {
                        self.editor
                            .ghost_caret_labels
                            .push((c.row, c.col, c.name.clone(), color));
                    }
                }
            }
            // Gutter stop button for an AI stream into the active file; the
            // hoisted group is the only one that shows it (clear the rest so
            // a group swap never leaves a stale button behind).
            self.editor.stream_stop_line = self.stream_stop_row();
            // The navigator's comment boxes for the active file, same
            // hoisting rule (rows come from poll_pair's per-tick snapshot).
            let author = self
                .pair_host
                .as_ref()
                .map(|h| h.name().to_string())
                .unwrap_or_default();
            self.editor.comment_boxes = self
                .editor
                .path
                .as_ref()
                .and_then(|p| collab_file_key(&self.tree.root, p))
                .and_then(|file| self.navigator_notes.get(&file))
                .map(|notes| {
                    notes
                        .iter()
                        .map(|(id, row, body)| crate::widgets::editor::CommentBox {
                            id: *id,
                            line: *row,
                            author: author.clone(),
                            body: body.clone(),
                        })
                        .collect()
                })
                .unwrap_or_default();
            // Review threads (#366) join the navigator's rather than
            // replacing them: both are comments on the same lines, and a
            // reviewer reading a PR with a navigator session open wants
            // both. Appended after, so a navigator note and a review
            // comment on one line keep a stable order.
            if let Some((path, threads)) = &self.review_boxes
                && self.editor.path.as_deref() == Some(path.as_path())
            {
                let lines = self.editor.lines.len();
                self.editor.comment_boxes.extend(threads.iter().map(|t| {
                    crate::widgets::editor::CommentBox {
                        id: t.id,
                        line: t.box_line(lines),
                        author: t.title_for(lines),
                        body: t.body.clone(),
                    }
                }));
            }
            // A focused box that vanished (ignored elsewhere, cleared, or
            // re-anchored away) releases the keyboard back to the buffer.
            if let Some(focus) = &self.editor.comment_focus
                && !self.editor.comment_boxes.iter().any(|b| b.id == focus.id)
            {
                self.editor.comment_focus = None;
            }
            for group in self.editor_layout.inactive_groups_mut() {
                for ed in &mut group.editors {
                    ed.stream_stop_line = None;
                    ed.comment_boxes.clear();
                    ed.comment_focus = None;
                }
            }
            // Render the editor group layout tree. The active group is hoisted
            // into `self.editor`; every other group lives in `editor_layout`.
            // Lay the leaves out and paint each at its rect (depth-first order),
            // reporting the active group's rect so popups anchor there.
            let rects = self.editor_layout.leaf_rects(editor_area, EDITOR_SPLIT_MIN);
            let active_idx = self.editor_layout.active_dfs_index();
            let focused_area = if self.editor_layout.is_split() {
                let active_area = rects[active_idx];
                frame.render_widget(&mut self.editor, active_area);
                let inactive_rects: Vec<Rect> = rects
                    .iter()
                    .enumerate()
                    .filter(|(i, _)| *i != active_idx)
                    .map(|(_, r)| *r)
                    .collect();
                for (group, rect) in self
                    .editor_layout
                    .inactive_groups_mut()
                    .into_iter()
                    .zip(inactive_rects)
                {
                    group.hover_pointer = pointer;
                    frame.render_widget(group, rect);
                }
                // Every boundary in the grid is a draggable seam (one per
                // internal child edge of every split node, any depth).
                self.editor_seams = self.editor_layout.seams(editor_area, EDITOR_SPLIT_MIN);
                // Image overlays stay keyed by physical column (0 = left).
                if rects.len() == 2 {
                    self.update_editor_image_overlay(0, rects[0]);
                    self.update_editor_image_overlay(1, rects[1]);
                } else {
                    self.update_editor_image_overlay(0, active_area);
                    self.disable_editor_image(1);
                }
                // ponytail: no minimap while the editor is split; per-group
                // minimaps when someone asks for them.
                self.disable_minimap_image();
                active_area
            } else if let Some((ed_rect, full_strip, img_rect)) = self.carve_minimap(editor_area) {
                // Bg-fill the whole strip column so no stale cells show
                // through, then paint the editor into the narrowed rect and
                // bake the minimap raster into the text-aligned sub-rect.
                frame.render_widget(
                    ratatui::widgets::Block::default()
                        .style(Style::default().bg(self.theme.editor_bg())),
                    full_strip,
                );
                frame.render_widget(&mut self.editor, ed_rect);
                self.editor_seams.clear();
                self.update_editor_image_overlay(0, ed_rect);
                self.disable_editor_image(1);
                self.update_minimap_overlay(img_rect);
                ed_rect
            } else {
                frame.render_widget(&mut self.editor, editor_area);
                self.editor_seams.clear();
                self.update_editor_image_overlay(0, editor_area);
                // No right pane: make sure its slot can't ghost an image.
                self.disable_editor_image(1);
                self.disable_minimap_image();
                editor_area
            };
            if self.focus == Pane::Editor
                && self.completion_popup.is_some()
                && let Some((cx, cy)) = self.editor.cursor_screen_pos()
            {
                if let Some(popup) = self.completion_popup.as_mut() {
                    popup.anchor = (cx, cy);
                    popup.theme = self.theme;
                }
                let popup_ref = self.completion_popup.as_ref().unwrap();
                let area = popup_ref.area_for(focused_area);
                if area.width > 0 && area.height > 0 {
                    frame.render_widget(popup_ref, area);
                }
            }
            // Parameter hints sit ABOVE the caret, so they coexist with the
            // completion popup below it.
            if self.focus == Pane::Editor
                && self.signature_help_popup.is_some()
                && let Some((cx, cy)) = self.editor.cursor_screen_pos()
            {
                if let Some(popup) = self.signature_help_popup.as_mut() {
                    popup.anchor = (cx, cy);
                    popup.theme = self.theme;
                }
                let popup_ref = self.signature_help_popup.as_ref().unwrap();
                let area = popup_ref.area_for(focused_area);
                if area.width > 0 && area.height > 0 {
                    frame.render_widget(popup_ref, area);
                }
            }
            if let Some(popup) = self.tab_tooltip.as_mut() {
                popup.theme = self.theme;
                let area = popup.area_for(focused_area);
                if area.width > 0 && area.height > 0 {
                    frame.render_widget(&*popup, area);
                }
            }
            // Layout-control icons at the top-right of the editor tab strip.
            let strip_row = Rect {
                x: editor_area.x,
                y: editor_area.y,
                width: editor_area.width,
                height: 1,
            };
            self.paint_layout_icons(frame, strip_row);
        }
        if let Some(area) = terminal_area {
            // Left/Right panel alignment narrows the terminal to one half of
            // its band; paint the leftover strip with the editor background so
            // the vacated cells don't ghost the previous frame.
            if let Some(band) = terminal_band
                && (band.width != area.width || band.x != area.x)
            {
                frame.render_widget(
                    ratatui::widgets::Block::default()
                        .style(Style::default().bg(self.theme.editor_bg())),
                    band,
                );
            }
            // The panel group's tab strip (PROBLEMS / TERMINAL) takes the top
            // row; the active tab's view fills the rest. Mirrors VS Code's
            // bottom-panel tab bar.
            let strip = Rect {
                x: area.x,
                y: area.y,
                width: area.width,
                height: 1,
            };
            let content = if area.height > 1 {
                Rect {
                    x: area.x,
                    y: area.y + 1,
                    width: area.width,
                    height: area.height - 1,
                }
            } else {
                area
            };
            self.paint_panel_tabs(frame, strip);
            match self.bottom_panel_tab {
                BottomPanelTab::Terminal => {
                    let n = self.terminals.len().max(1);
                    let multi = self.terminals.len() > 1;
                    let maximized = self.terminal_pane_maximized && multi;
                    self.clear_terminal_rail();
                    // Maximize mode: the active pane owns the panel's width
                    // minus a right rail listing every terminal (VS Code's
                    // terminal-tabs list); hidden panes drop their hit rects
                    // so clicks can't phantom-match. Otherwise: even split.
                    let cols: Vec<Rect> = if maximized {
                        // The rail is a fixed, very narrow switcher column:
                        // icon + 4 label characters, nothing adaptive.
                        let rail_w = TERMINAL_RAIL_W.min(content.width.saturating_sub(20));
                        let pane = Rect {
                            x: content.x,
                            y: content.y,
                            width: content.width - rail_w,
                            height: content.height,
                        };
                        let rail = Rect {
                            x: content.x + pane.width,
                            y: content.y,
                            width: rail_w,
                            height: content.height,
                        };
                        self.paint_terminal_rail(frame, rail);
                        (0..n)
                            .map(|i| {
                                if i == self.active_terminal {
                                    pane
                                } else {
                                    Rect::default()
                                }
                            })
                            .collect()
                    } else {
                        // Collapsed panes (#313) keep a one-column strip and
                        // the rest divide what is left. Read off the panes
                        // rather than a list held here, so a reorder or a
                        // close can never leave the flags naming the wrong
                        // terminal.
                        let collapsed: Vec<bool> = (0..n)
                            .map(|i| self.terminals.get(i).is_some_and(|t| t.collapsed))
                            .collect();
                        Layout::default()
                            .direction(Direction::Horizontal)
                            .constraints(terminal_pane_constraints(&collapsed))
                            .split(content)
                            .to_vec()
                    };
                    // Theme the terminal background like VS Code's integrated
                    // terminal: prefill each pane with the theme bg before the
                    // grid paints. Shell-colored cells override it; default-bg
                    // cells (Style bg = None) keep the fill. On iTerm2 this
                    // matches the SetColors session bg; on Ghostty/Kitty (which
                    // ignores SetColors) it's what makes the terminal follow the
                    // theme at all instead of showing the host's own bg.
                    let term_bg = self.theme.editor_bg();
                    for (i, t) in self.terminals.iter_mut().enumerate() {
                        // A collapsed pane is not rendered, and that is what
                        // keeps its shell intact: rendering is what resizes
                        // the PTY, and reflowing a running shell into one
                        // column would mangle everything already on its
                        // screen. It keeps the geometry it had, so expanding
                        // brings the pane back as it was rather than as a
                        // column of broken wrapping. Its `last_area` is
                        // cleared so a click on the strip cannot land in a
                        // grid that is no longer painted there.
                        if cols[i].width == 0 || (t.collapsed && !maximized) {
                            t.last_area = Rect::default();
                            // `last_inner` too (#510): it anchors the image
                            // overlay's raw CUP write, so a stale rect sends
                            // the payload outside the pane with nothing to
                            // catch it. The other terminal-pane clears below
                            // need no counterpart - the overlay returns early
                            // when the panel is hidden or off the Terminal
                            // tab, which is what makes them unreachable for
                            // it. A consumer that drops that guard inherits
                            // this obligation.
                            t.last_inner = Rect::default();
                            t.redacted_on_screen = 0;
                        } else {
                            frame.render_widget(
                                ratatui::widgets::Block::default()
                                    .style(Style::default().bg(term_bg)),
                                cols[i],
                            );
                            frame.render_widget(t, cols[i]);
                        }
                    }
                    let show_close = multi;
                    self.terminal_add_buttons.clear();
                    self.terminal_profile_buttons.clear();
                    self.terminal_close_buttons.clear();
                    self.terminal_max_buttons.clear();
                    self.terminal_label_rects.clear();
                    self.terminal_collapse_buttons.clear();
                    self.terminal_strip_rects.clear();
                    for (i, col) in cols.iter().enumerate().take(self.terminals.len()) {
                        // Hidden panes still push placeholders so a button's
                        // position in each vec names its terminal index.
                        if col.width == 0 {
                            self.terminal_add_buttons.push(Rect::default());
                            self.terminal_profile_buttons.push(Rect::default());
                            self.terminal_close_buttons.push(Rect::default());
                            self.terminal_max_buttons.push(Rect::default());
                            self.terminal_label_rects.push(Rect::default());
                            self.terminal_collapse_buttons.push(Rect::default());
                            self.terminal_strip_rects.push(Rect::default());
                            continue;
                        }
                        // A collapsed pane's whole chrome is its strip: no
                        // header buttons fit in one column, and the only
                        // gesture it offers is the way back out.
                        if self.terminals[i].collapsed && !maximized {
                            let strip = self.paint_terminal_collapsed_strip(frame, *col, i);
                            self.terminal_add_buttons.push(Rect::default());
                            self.terminal_profile_buttons.push(Rect::default());
                            self.terminal_close_buttons.push(Rect::default());
                            self.terminal_max_buttons.push(Rect::default());
                            self.terminal_label_rects.push(Rect::default());
                            self.terminal_collapse_buttons.push(Rect::default());
                            self.terminal_strip_rects.push(strip);
                            continue;
                        }
                        self.terminal_strip_rects.push(Rect::default());
                        let buttons = paint_terminal_pane_buttons(
                            frame,
                            *col,
                            show_close,
                            maximized,
                            self.theme,
                            self.pointer_cell,
                        );
                        self.terminal_add_buttons
                            .push(buttons.add.unwrap_or_default());
                        self.terminal_profile_buttons
                            .push(buttons.profile.unwrap_or_default());
                        self.terminal_close_buttons
                            .push(buttons.close.unwrap_or_default());
                        self.terminal_max_buttons
                            .push(buttons.max.unwrap_or_default());
                        self.terminal_collapse_buttons
                            .push(buttons.collapse.unwrap_or_default());
                        // Auto/manual pane label at top-left, only with 2+ panes
                        // (a lone pane needs no name). Kept clear of the buttons.
                        // The painted pill doubles as the drag-reorder handle,
                        // so its rect is recorded index-aligned with the pane.
                        let mut label_rect = Rect::default();
                        if multi {
                            let label = self.terminals[i].label().to_string();
                            // The pill is painted AFTER the header buttons and
                            // wins the shared cells, so its budget has to
                            // clear the button strip plus the pill's own
                            // widest decoration (a leading `⚠` or `⇶` and the
                            // two spaces every pill carries).
                            let room =
                                col.width.saturating_sub(TERMINAL_BUTTON_STRIP_W + 4) as usize;
                            // While broadcast input is on, every pane that
                            // receives the mirrored keystrokes wears an
                            // unmissable red pill with a ⇶ marker
                            // (Terminator's role colouring); excluded panes
                            // keep the normal pill. The marker paints even
                            // while the pane's auto-label is still empty.
                            let receiving = self.broadcast_input
                                && (i == self.active_terminal
                                    || !self.terminals[i].broadcast_excluded);
                            // An agent pane wears its badge in the pill
                            // (`◆ claude ◐`, #344); the badge takes the room
                            // first and the label is clipped to what is left.
                            let badge = self.terminals[i]
                                .agent()
                                .map(|a| format!("\u{25c6} {} {}", a.name, a.status.glyph()));
                            let label = match &badge {
                                Some(b) if label.is_empty() => b.clone(),
                                Some(b) => format!("{b} {label}"),
                                None => label,
                            };
                            if (!label.is_empty() || receiving) && room >= 3 {
                                let shown: String = label.chars().take(room).collect();
                                let mut text = if receiving && shown.is_empty() {
                                    String::from(" \u{21f6} ")
                                } else if receiving {
                                    format!(" \u{21f6} {shown} ")
                                } else {
                                    format!(" {shown} ")
                                };
                                // A live OSC 9;4 percent joins the pill (the
                                // border gauge is the primary drawing; this
                                // keeps unfocused panes glanceable). The
                                // indeterminate state has no number to show.
                                if let Some((state, pct)) = self.terminals[i].progress()
                                    && state != 3
                                    && text.chars().count() + 6 <= room
                                {
                                    text = format!("{}\u{b7} {pct}% ", text);
                                }
                                let accent = self.terminals[i].accent;
                                let text = if accent.is_some() && !receiving {
                                    format!(" \u{26a0}{text}")
                                } else {
                                    text
                                };
                                let style = if receiving {
                                    Style::default()
                                        .fg(Color::Black)
                                        .bg(self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)))
                                        .add_modifier(Modifier::BOLD)
                                } else if let Some((r, g, b)) = accent {
                                    Style::default()
                                        .fg(Color::Black)
                                        .bg(Color::Rgb(r, g, b))
                                        .add_modifier(Modifier::BOLD)
                                } else {
                                    crate::widgets::header_pill::action_style(self.theme, false)
                                };
                                // `room` bounds how much of the name is worth
                                // showing, but it counts CHARACTERS while the
                                // buffer advances by display CELLS, so a CJK
                                // or emoji name is twice as wide as its budget
                                // and would still reach the buttons. Clip the
                                // paint to the cells before the button strip —
                                // `set_stringn` measures grapheme width, which
                                // is the same clamp the rail rows use — and
                                // take the drag handle's width from what was
                                // actually painted.
                                let budget =
                                    col.width.saturating_sub(TERMINAL_BUTTON_STRIP_W) as usize;
                                let (end_x, _) = frame
                                    .buffer_mut()
                                    .set_stringn(col.x, col.y, text, budget, style);
                                label_rect = Rect {
                                    x: col.x,
                                    y: col.y,
                                    width: end_x.saturating_sub(col.x),
                                    height: 1,
                                };
                            }
                        }
                        self.terminal_label_rects.push(label_rect);
                    }
                }
                BottomPanelTab::Problems => {
                    // The terminals are hidden behind the PROBLEMS view; drop
                    // their hit rects so a click never phantom-matches a pane
                    // that isn't painted (mirrors the hidden-panel reset).
                    self.terminal_add_buttons.clear();
                    self.terminal_profile_buttons.clear();
                    self.terminal_close_buttons.clear();
                    self.terminal_max_buttons.clear();
                    self.terminal_label_rects.clear();
                    self.terminal_collapse_buttons.clear();
                    self.terminal_strip_rects.clear();
                    self.clear_terminal_rail();
                    for t in self.terminals.iter_mut() {
                        t.last_area = Rect::default();
                        t.redacted_on_screen = 0;
                    }
                    frame.render_widget(&mut self.problems, content);
                }
                BottomPanelTab::Output => {
                    // Same hidden-terminal reset as PROBLEMS: the OUTPUT view
                    // covers the panes, so their hit rects must not linger.
                    self.terminal_add_buttons.clear();
                    self.terminal_profile_buttons.clear();
                    self.terminal_close_buttons.clear();
                    self.terminal_max_buttons.clear();
                    self.terminal_label_rects.clear();
                    self.terminal_collapse_buttons.clear();
                    self.terminal_strip_rects.clear();
                    self.clear_terminal_rail();
                    for t in self.terminals.iter_mut() {
                        t.last_area = Rect::default();
                        t.redacted_on_screen = 0;
                    }
                    frame.render_widget(&mut self.output, content);
                }
                BottomPanelTab::Ports => {
                    // Same hidden-terminal reset: the PORTS view covers the
                    // panes, so their hit rects must not linger.
                    self.terminal_add_buttons.clear();
                    self.terminal_profile_buttons.clear();
                    self.terminal_close_buttons.clear();
                    self.terminal_max_buttons.clear();
                    self.terminal_label_rects.clear();
                    self.terminal_collapse_buttons.clear();
                    self.terminal_strip_rects.clear();
                    self.clear_terminal_rail();
                    for t in self.terminals.iter_mut() {
                        t.last_area = Rect::default();
                        t.redacted_on_screen = 0;
                    }
                    frame.render_widget(&mut self.ports, content);
                }
                BottomPanelTab::Captures => {
                    // Same hidden-terminal reset as the PORTS arm above.
                    self.terminal_add_buttons.clear();
                    self.terminal_profile_buttons.clear();
                    self.terminal_close_buttons.clear();
                    self.terminal_max_buttons.clear();
                    self.terminal_label_rects.clear();
                    self.terminal_collapse_buttons.clear();
                    self.terminal_strip_rects.clear();
                    self.clear_terminal_rail();
                    for t in self.terminals.iter_mut() {
                        t.last_area = Rect::default();
                        t.redacted_on_screen = 0;
                    }
                    frame.render_widget(&mut self.captures, content);
                }
            }
        } else {
            self.terminal_add_buttons.clear();
            self.terminal_profile_buttons.clear();
            self.terminal_close_buttons.clear();
            self.terminal_max_buttons.clear();
            self.terminal_label_rects.clear();
            self.terminal_collapse_buttons.clear();
            self.terminal_strip_rects.clear();
            self.clear_terminal_rail();
            self.problems_tab_rect = Rect::default();
            self.output_tab_rect = Rect::default();
            self.ports_tab_rect = Rect::default();
            self.captures_tab_rect = Rect::default();
            self.terminal_tab_rect = Rect::default();
            // A hidden terminal must not keep stale hit rects alive, or
            // `terminal_at_pos` would phantom-match clicks meant for
            // whatever now occupies those cells (mirrors the SYSTEM
            // panel's hidden-state reset).
            for t in self.terminals.iter_mut() {
                t.last_area = Rect::default();
                t.redacted_on_screen = 0;
            }
        }

        // Owned snapshot: the spans borrow the status, and borrowing it
        // through scm_worker() would pin all of &self for the whole render.
        let scm_status = self.scm_worker().status().clone();
        let mut spans: Vec<Span> = Vec::with_capacity(20);
        spans.extend(brand_spans(self.theme));
        let redacted = self.redacted_on_screen();
        if redacted > 0 || self.redactions_revealed() {
            // How much of what is on screen is masked right now (#360): a
            // screen-share host wants to know the count is non-zero, and
            // that a reveal window is open.
            let (label, bg) = if self.redactions_revealed() {
                (
                    format!(" \u{1f441} {redacted} revealed "),
                    Color::Rgb(0xc0, 0x39, 0x2b),
                )
            } else {
                (
                    format!(" \u{2022} {redacted} redacted "),
                    Color::Rgb(0x3a, 0x3f, 0x4b),
                )
            };
            spans.push(Span::styled(
                label,
                Style::default()
                    .bg(self.theme.ui(bg))
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if let Some(span) = self.perf.status_span() {
            spans.push(span);
        }
        if self.any_update_ready() {
            spans.push(Span::styled(
                " ⟳ Update ready - F9 to relaunch ",
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0x1f, 0x7a, 0x33)))
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if let Some(current) = self.local_drift.as_ref()
            && self.update_status == UpdateStatus::Idle
            && self.self_install.is_none()
            // The same latch as `f9_update_armed`: while the staged release
            // builds, F9 is not a rebuild, so the hint must not say so.
            && self.staged_status != UpdateStatus::InProgress
            && self.staged_install.is_none()
        {
            // Amber, persistent: the binary predates its own source tree
            // (#242). One keypress rebuilds it in the background.
            spans.push(Span::styled(
                format!(
                    " ⟳ croft {} < repo {current} - F9 to rebuild ",
                    env!("CROFT_GIT_HASH")
                ),
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0x8a, 0x60, 0x00)))
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if self.any_update_in_progress() {
            // Red + a spinning circular-arrow glyph to draw the eye to the
            // in-progress background update.
            spans.push(Span::styled(
                format!(
                    " {} Updating croft in the background ",
                    self.update_spinner_glyph()
                ),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0xff, 0x45, 0x4d)))
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if let Some(progress) = self.lsp_progress_status() {
            // A busy language server (rust-analyzer priming its crate graph,
            // etc.) is otherwise invisible: hover/completion just return empty
            // until it finishes. Surfacing "rust-analyzer: Indexing " tells
            // the user to wait rather than assume the server is dead.
            spans.push(Span::styled(
                format!(" ⟳ {progress} "),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if let Some(label) = &self.mcp_busy_label {
            // An in-flight extension command (install + tool call on a worker
            // thread) is otherwise invisible; an animated badge says it's working.
            spans.push(Span::styled(
                format!(" {} {label} ", self.mcp_spinner_glyph()),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0x2d, 0xd4, 0xbf)))
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if let Some(rec) = &self.macro_recording {
            // Recording is state a user can forget they left on, so it gets a
            // filled red badge rather than a dim hint (#255). A named register
            // shows which one, since vim users keep several.
            let label = match rec.register {
                Some(r) => format!(" ● REC @{r} "),
                None => String::from(" ● REC "),
            };
            spans.push(Span::styled(
                label,
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0xc0, 0x2b, 0x2b)))
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw(" "));
        }
        if self.vim.enabled {
            let (text, bg) = match self.vim.command_line() {
                Some(cmd) => (
                    format!(" {cmd} "),
                    self.theme.ui(Color::Rgb(0x33, 0x33, 0x33)),
                ),
                None => {
                    let label = self.vim.mode_label().unwrap_or("NORMAL");
                    let bg = match self.vim.mode() {
                        crate::vim::VimMode::Insert => self.theme.ui(Color::Rgb(0x1f, 0x7a, 0x33)),
                        crate::vim::VimMode::Visual | crate::vim::VimMode::VisualLine => {
                            self.theme.ui(Color::Rgb(0x8a, 0x4f, 0xbf))
                        }
                        _ => self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)),
                    };
                    (format!(" {label} "), bg)
                }
            };
            spans.push(Span::styled(
                text,
                Style::default()
                    .bg(bg)
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw(" "));
        }
        // Hairline zone divider (│): fences the brand/git zone, the
        // diagnostics cluster, and the transient message off from each other
        // so the bar reads as segments instead of one run of text. Quiet on
        // both the navy and near-black bars.
        let zone_div = Style::default().fg(self.theme.ui(Color::Rgb(0x3a, 0x41, 0x50)));
        let scm_spans = git_status_spans(&scm_status);
        // The wordmark already ends in a space; the git spans don't, so buy
        // the divider one cell of air only when the branch segment painted.
        let scm_present = !scm_spans.is_empty();
        spans.extend(scm_spans);
        spans.push(Span::styled(
            if scm_present { " \u{2502}" } else { "\u{2502}" },
            zone_div,
        ));
        // Persistent orange badge for a remote session with no dtach: it can't
        // survive a transport drop, so flag it for the whole session (rendered
        // before the transient status so a status update never hides it).
        if let Some(warning) = self.persistence_warning {
            spans.push(Span::styled(
                format!(" \u{26a0} {warning} "),
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
                    .fg(self.theme.ui(Color::Rgb(0x10, 0x13, 0x1a)))
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw("  "));
        }
        // Multiplayer roster badge: how many clients are attached to this
        // persistent session, painted only when someone else is here
        // (manage them via Session: Participants, Cmd+K A).
        if self.session_participants.len() > 1 {
            spans.push(Span::styled(
                format!(" \u{f0c0} {} attached ", self.session_participants.len()),
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0x2f, 0x6f, 0xd0)))
                    .fg(self.theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw("  "));
        }
        // AI-stream badge: a pilot is streaming an edit into a shared file;
        // orange like the persistence warning (attention, not decoration),
        // naming the cancel chord so the stop path is one glance away.
        if let Some(stream) = &self.collab_stream {
            spans.push(Span::styled(
                format!(
                    " \u{23f9} {} streaming into {} (Cmd+K X to stop) ",
                    stream.name, stream.file
                ),
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
                    .fg(self.theme.ui(Color::Rgb(0x10, 0x13, 0x1a)))
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw("  "));
        } else if let Some(host) = &self.pair_host {
            // Resident navigator seated and idle: presence, not attention —
            // the stream badge above takes over whenever it is typing.
            spans.push(Span::styled(
                format!(" \u{25c6} {} seated ", host.title()),
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0x3c, 0x41, 0x4f)))
                    .fg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw("  "));
        }
        // Diagnostics counts (click → PROBLEMS), VS Code-style, after git.
        // Always shown so the bar reads as a health indicator at a glance.
        let err_count = self.problems.error_count();
        let warn_count = self.problems.warning_count();
        let diag_start_col: u16 = spans.iter().map(|s| s.content.chars().count() as u16).sum();
        // One cell between the counts, not three: the errors and warnings
        // read as a single health cluster (they already share one hit rect).
        // diag_len is measured from the very strings that render, so the hit
        // rect can never drift from the visible text.
        let err_text = format!(" \u{ea87} {err_count}");
        let warn_text = format!(" \u{ea6c} {warn_count} ");
        let diag_len = (err_text.chars().count() + warn_text.chars().count()) as u16;
        spans.push(Span::styled(
            err_text,
            Style::default().fg(self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c))),
        ));
        spans.push(Span::styled(
            warn_text,
            Style::default().fg(self.theme.ui(Color::Rgb(0xcc, 0xa7, 0x00))),
        ));
        // Transient status message (e.g. "Saved editor.rs"), no keybinding
        // cheat-sheet — those live in F1 / the Command Palette now. Fenced
        // behind a divider and dimmed so commentary reads apart from the
        // clickable clusters around it.
        if !self.status.is_empty() {
            spans.push(Span::styled("\u{2502} ", zone_div));
            spans.push(Span::styled(
                self.status.clone(),
                Style::default().fg(self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb8))),
            ));
        }

        if let Some(osk) = self.osk.as_mut() {
            if osk_h > 0 {
                crate::widgets::osk::render_osk(osk, outer[1], frame.buffer_mut(), self.theme);
            } else {
                // Collapsed (frame too short): zero the hit rect so the
                // invisible band can't swallow clicks.
                osk.last_area = Rect::default();
            }
        }

        let status_rect = outer[2];
        // The F1 cheat-sheet is gone; F1 / the palette still open Shortcuts.
        self.shortcuts_hit_rect = None;
        // Diagnostics hit rect (left group), for click-to-PROBLEMS.
        self.status_diag_rect = if status_h > 0 {
            Rect {
                x: status_rect.x.saturating_add(diag_start_col),
                y: status_rect.y,
                width: diag_len.min(status_rect.width.saturating_sub(diag_start_col)),
                height: 1,
            }
        } else {
            Rect::default()
        };

        // ---- Right cluster: document facts, right-justified. Indentation /
        // encoding / EOL / language are clickable to change (hit rects recorded
        // below). A hairline │ marks each seam so the segments read as
        // separate controls, one shade brighter than the transient message so
        // controls and commentary stop sharing a costume; the clickable ones
        // take a hover fill under the pointer (spans are built after `rx` is
        // known, below, so hover can be computed against this frame's rects).
        let mut seg_texts: Vec<String> = vec![
            format!(
                " Ln {}, Col {} ",
                self.editor.cursor_row + 1,
                self.editor.cursor_col + 1
            ),
            format!(" {} ", self.editor.indent_style().label()),
            format!(" {} ", self.editor.encoding.name()),
            format!(" {} ", self.editor.eol.label()),
            format!(" {} ", self.editor.language_label()),
        ];
        // `2 agents · 1 waiting` (#344), only while an agent is seated; a
        // click focuses the waiting pane.
        let (seated, waiting) = self.agent_counts();
        // The review queue rides the same chip (#345): a file an agent
        // changed while you were looking elsewhere is the thing you most
        // need to be told about, and it outlives the agent's own pane.
        // The set the Explorer is drawing, not a fresh count off the ledger:
        // this is the per-frame render path, and `unreviewed_files` clones
        // every path to build a set it then throws away. Reading the cache
        // also makes the chip and the dots the SAME number by construction
        // rather than by two code paths agreeing.
        let unreviewed = self.tree.agent_touched.len();
        if seated > 0 || unreviewed > 0 {
            // With nothing seated the agent half would read "0 agents",
            // which is not what the chip is reporting any more: the queue
            // outlives the pane, so the chip becomes the queue's.
            let agents_part = if seated > 0 {
                format!(
                    "{seated} agent{}{}",
                    if seated == 1 { "" } else { "s" },
                    if waiting > 0 {
                        format!(" \u{b7} {waiting} waiting")
                    } else {
                        String::new()
                    }
                )
            } else {
                String::new()
            };
            let review_part = if unreviewed > 0 {
                // A "+" when the watcher dropped events: the count is a
                // floor, and a bare number would read as a total.
                format!(
                    "{unreviewed}{} to review",
                    if self.agent_ledger.may_be_incomplete() {
                        "+"
                    } else {
                        ""
                    }
                )
            } else {
                String::new()
            };
            let joined = match (agents_part.is_empty(), review_part.is_empty()) {
                (false, false) => format!("{agents_part} \u{b7} {review_part}"),
                (false, true) => agents_part,
                _ => review_part,
            };
            seg_texts.push(format!(" \u{25c6} {joined} "));
        }
        let widths: Vec<u16> = seg_texts.iter().map(|s| s.chars().count() as u16).collect();
        let right_total: u16 = widths.iter().sum::<u16>() + (seg_texts.len() as u16 - 1);
        // The right cluster paints OVER the left paragraph, so an over-long
        // transient loses exactly its tail — for "Opened <deep path>" that
        // was the filename, the one informative part (#100). Middle-elide
        // the transient (always the last span) into the room that survives.
        if !self.status.is_empty() {
            let left_fixed: u16 = spans
                .iter()
                .take(spans.len().saturating_sub(1))
                .map(|s| s.content.chars().count() as u16)
                .sum();
            let avail = status_rect
                .width
                .saturating_sub(right_total)
                .saturating_sub(left_fixed)
                .saturating_sub(1);
            if let Some(last) = spans.last_mut()
                && last.content.chars().count() as u16 > avail
            {
                // Keep the message's dim style through the elision so a
                // truncated transient doesn't suddenly brighten.
                *last = Span::styled(elide_middle(&self.status, avail as usize), last.style);
            }
        }

        // Black theme: drop the navy status strip to a near-black seam (a hair
        // lighter than the #000000 editor so the bar still reads as distinct),
        // matching VS Code's OLED themes. Croft Dark keeps the navy band.
        let status_bg = if self.popup_gradient() {
            self.theme.ui(Color::Rgb(0x18, 0x18, 0x18))
        } else {
            self.theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
        };
        // Left fills the whole bar (background + left text); the right cluster
        // overwrites the right portion.
        frame.render_widget(
            Paragraph::new(Line::from(spans)).style(Style::default().bg(status_bg)),
            status_rect,
        );
        // Reset clickable rects; re-record only when the right cluster fits.
        self.status_indent_rect = Rect::default();
        self.status_encoding_rect = Rect::default();
        self.status_eol_rect = Rect::default();
        self.status_language_rect = Rect::default();
        self.status_agents_rect = Rect::default();
        if status_h > 0 && right_total > 0 && right_total <= status_rect.width {
            let rx = status_rect.right() - right_total;
            // The right cluster paints OVER the left paragraph, so the
            // diagnostics hit rect must stop where it starts. Clipped only to
            // the frame edge, it went on answering for cells that now read
            // "Ln 1, Col 1" — opening PROBLEMS from a click on the position
            // readout, with the counts it claimed not even on screen.
            if self.status_diag_rect.x >= rx {
                // Entirely behind the cluster: not on screen, so not a target.
                self.status_diag_rect = Rect::default();
            } else if self.status_diag_rect.right() > rx {
                self.status_diag_rect.width = rx - self.status_diag_rect.x;
            }
            // Build the spans now that x positions are known: segment fg one
            // shade up from the transient's dim gray, │ dividers between, and
            // a hover fill on the clickable segments (indices 1..=5) when the
            // pointer rests on them — same affordance as the activity bar.
            // Ln/Col (index 0) is a readout, not a control, so it never
            // hovers. Hit rects recorded in the same pass.
            let seg_style = Style::default().fg(self.theme.ui(Color::Rgb(0xc9, 0xd2, 0xe3)));
            let hover_style = Style::default()
                .bg(self.theme.ui(Color::Rgb(0x2a, 0x31, 0x40)))
                .fg(self.theme.ui(Color::White));
            let mut right: Vec<Span> = Vec::with_capacity(seg_texts.len() * 2 - 1);
            let mut cx = rx;
            for (i, text) in seg_texts.iter().enumerate() {
                if i > 0 {
                    right.push(Span::styled("\u{2502}", zone_div));
                    cx = cx.saturating_add(1);
                }
                let r = Rect {
                    x: cx,
                    y: status_rect.y,
                    width: widths[i],
                    height: 1,
                };
                let hovered = i > 0
                    && self
                        .pointer_cell
                        .is_some_and(|(pc, pr)| rect_contains(r, pc, pr));
                right.push(Span::styled(
                    text.clone(),
                    if hovered { hover_style } else { seg_style },
                ));
                match i {
                    1 => self.status_indent_rect = r,
                    2 => self.status_encoding_rect = r,
                    3 => self.status_eol_rect = r,
                    4 => self.status_language_rect = r,
                    5 => self.status_agents_rect = r,
                    _ => {}
                }
                cx = cx.saturating_add(widths[i]);
            }
            frame.render_widget(
                Paragraph::new(Line::from(right)).style(Style::default().bg(status_bg)),
                Rect {
                    x: rx,
                    y: status_rect.y,
                    width: right_total,
                    height: status_rect.height,
                },
            );
        }

        // Overlays render last so they sit on top of everything else. The port
        // toast goes first so modals/menus paint above it.
        //
        // The hover note popup (editor symbol hover / terminal annotation
        // note) renders here against the WHOLE frame, not the editor's
        // focused_area: its anchor may sit in the terminal panel, and the
        // welcome screen skips the editor-tabs branch entirely, which used to
        // drop a terminal annotation's note without painting it at all.
        if let Some(popup) = self.peek_popup.as_mut() {
            popup.theme = self.theme;
            let area = popup.area_for(frame.area());
            if area.width > 0 && area.height > 0 {
                frame.render_widget(&*popup, area);
            }
        }
        if let Some(popup) = self.hover_popup.as_mut() {
            popup.theme = self.theme;
            let area = popup.area_for(frame.area());
            if area.width > 0 && area.height > 0 {
                frame.render_widget(&*popup, area);
            }
        }
        self.render_port_toast(frame);
        self.render_update_toast(frame);
        self.render_context_menu(frame);
        self.render_commit_dropdown(frame);
        self.render_prompt(frame);
        self.render_local_open_confirm(frame);
        self.render_discard_confirm(frame);
        self.render_revert_hunk_confirm(frame);
        self.render_discard_all_confirm(frame);
        self.render_replace_all_confirm(frame);
        self.render_broadcast_confirm(frame);
        self.render_run_block_confirm(frame);
        // Terminal-pane inline image: sync after the panes have painted so
        // last_inner and the scroll offset are this frame's (all gating —
        // hidden panel, alt screen, off-screen anchor — is inside).
        self.update_terminal_image_overlay();
        self.update_markdown_image_overlay();
        self.render_editor_find(frame);
        self.render_terminal_find(frame);
        self.render_file_finder(frame);
        self.render_command_palette(frame);
        self.render_go_to_symbol(frame);
        self.render_workspace_symbols(frame);
        self.render_process_picker(frame);
        self.render_zoxide_jump(frame);
        self.render_command_history_popup(frame);
        self.render_branch_picker(frame);
        self.render_scm_menu(frame);
        self.render_input_prompt(frame);
        self.render_list_picker(frame);
        self.render_shortcuts_modal(frame);
        self.render_connect_dialog(frame);
        // The startup unsupported-terminal nudge renders last so it sits above
        // every other overlay until the user dismisses it.
        self.render_terminal_warning(frame);

        // Chrome button-hint tooltip. Rendered at the top level against the
        // whole frame (not the editor's `focused_area`) because the controls it
        // labels live in the activity bar and sidebar, outside the editor pane;
        // clamping it to the editor area would yank it away from the control or,
        // on the welcome screen, drop it entirely.
        let mut tooltip_area = None;
        if let Some(popup) = self.ui_tooltip.as_mut() {
            popup.theme = self.theme;
            let full = frame.area();
            let mut area = popup.area_for(full);
            // Keep the box clear of the activity bar's inline-image column. Those
            // codicon glyphs are a terminal graphics layer that always composites
            // ABOVE text cells, so any overlap would paint over (hide) the left of
            // the tooltip. Shift it to the right of the bar instead, like VS Code
            // floats an activity-icon hint beside the icon.
            if area.x < ACTIVITY_BAR_WIDTH {
                area.x = ACTIVITY_BAR_WIDTH;
                area.width = area.width.min(full.width.saturating_sub(area.x));
            }
            if area.width > 0 && area.height > 0 {
                frame.render_widget(&*popup, area);
                tooltip_area = Some(area);
            }
        }
        // Record the box so the post-draw flush can RE-PAINT it on top of any
        // sidebar OSC-1337 illustration (the no-repo hero / SSH empty-state).
        // Those images are emitted after ratatui's text and would otherwise
        // composite over the tooltip; re-emitting the box last wins the cell.
        self.ui_tooltip_area = tooltip_area;

        // Show the host terminal's hardware caret only when the editor is
        // focused and has no modal overlay. The DECSCUSR style is set to
        // BlinkingBar at startup, so the terminal blinks a thin vertical
        // line over the cursor cell without replacing its character.
        if self.focus == Pane::Editor
            && self.context_menu.is_none()
            && self.prompt.is_none()
            && self.cursor_visible_phase()
        {
            let pos = if self.editor.diff.is_some() {
                self.editor.diff_caret_screen_pos()
            } else {
                self.editor.cursor_screen_pos()
            };
            if let Some((cx, cy)) = pos {
                frame.set_cursor_position((cx, cy));
            }
        }

        // Source-control commit-message caret. Same software-blink rule:
        // the user can't see where they're typing in the message box
        // without a visible caret, since `set_string` just lays the text
        // flat with no native caret cell.
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::SourceControl
            && self.context_menu.is_none()
            && self.prompt.is_none()
            && self.cursor_visible_phase()
            && let Some((cx, cy)) = self.source_control.cursor_screen_pos()
        {
            frame.set_cursor_position((cx, cy));
        }

        // Search-panel field caret and Extensions filter caret. Same software
        // blink as the commit box so all three side-panel inputs share one
        // blinking hardware caret instead of a static block (Search) or no
        // caret at all (Extensions).
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Search
            && self.context_menu.is_none()
            && self.prompt.is_none()
            && self.cursor_visible_phase()
            && let Some((cx, cy)) = self.search.cursor_screen_pos()
        {
            frame.set_cursor_position((cx, cy));
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Extensions
            && self.context_menu.is_none()
            && self.prompt.is_none()
            && self.cursor_visible_phase()
            && let Some((cx, cy)) = self.extensions.cursor_screen_pos()
        {
            frame.set_cursor_position((cx, cy));
        }
    }

    fn render_context_menu(&self, frame: &mut ratatui::Frame) {
        let Some(menu) = &self.context_menu else {
            return;
        };
        // `menu_rect` already clamps against `last_frame_area`, so the
        // rect we draw here is the same rect `menu_item_at` hit-tests
        // against. Keeping the two in lock-step is what prevents the
        // off-by-N row dispatch when the menu has to shift up to fit.
        let Some(clipped) = self.menu_rect() else {
            return;
        };
        let grad = self.popup_gradient();
        // The top-level panel; the open submenu's parent row stays highlighted.
        self.render_menu_panel(frame, clipped, &menu.items, menu.selected, grad);
        // Float the open submenu's panel beside its parent.
        if let Some(sub_rect) = self.submenu_rect()
            && let Some(MenuEntry::Submenu { items, .. }) =
                menu.open_submenu.and_then(|p| menu.items.get(p))
        {
            self.render_menu_panel(frame, sub_rect, items, menu.submenu_selected, grad);
        }
    }

    /// Paint one bordered menu panel of `entries` into `rect`, highlighting row
    /// `selected`. Items show a right-aligned shortcut hint, submenu parents a
    /// `▸`, and separators a divider rule. Shared by the main menu and the
    /// floating submenu.
    fn render_menu_panel(
        &self,
        frame: &mut ratatui::Frame,
        rect: Rect,
        entries: &[MenuEntry],
        selected: usize,
        grad: bool,
    ) {
        // Black theme: orange→green gradient border + muted dark-teal
        // selection. Croft Dark keeps the legacy bright-blue accent so the
        // menu stays coherent with that theme's blue focus border.
        let border_blue = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(border_blue))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        if grad {
            paint_gradient_box(frame.buffer_mut(), rect);
        }
        let sel_bg = if grad {
            rgb_color(POPUP_SEL_BG)
        } else {
            border_blue
        };
        let sel_fg = if grad { Color::White } else { Color::Black };
        let inner = Rect {
            x: rect.x + 1,
            y: rect.y + 1,
            width: rect.width.saturating_sub(2),
            height: rect.height.saturating_sub(2),
        };
        for (i, entry) in entries.iter().enumerate() {
            if i as u16 >= inner.height {
                break;
            }
            let row = Rect {
                x: inner.x,
                y: inner.y + i as u16,
                width: inner.width,
                height: 1,
            };
            if let MenuEntry::Separator = entry {
                let rule = "\u{2500}".repeat(inner.width as usize);
                frame.buffer_mut().set_string(
                    inner.x,
                    row.y,
                    &rule,
                    Style::default().fg(self.theme.ui(Color::Rgb(0x45, 0x45, 0x45))),
                );
                continue;
            }
            if let MenuEntry::Header(label) = entry {
                // Dimmed, non-selectable section label (VS Code's group titles
                // like "Side Bar Position").
                frame.buffer_mut().set_string(
                    inner.x,
                    row.y,
                    format!(" {label}"),
                    Style::default()
                        .fg(self.theme.ui(Color::Rgb(0x7a, 0x82, 0x90)))
                        .add_modifier(Modifier::BOLD),
                );
                continue;
            }
            let is_sel = i == selected;
            let row_style = if is_sel {
                Style::default().fg(sel_fg).bg(sel_bg)
            } else {
                Style::default().fg(self.theme.ui(Color::White))
            };
            let (label, right_hint) = match entry {
                MenuEntry::Item { label, action } => {
                    (label.as_str(), shortcut_for(action).map(str::to_string))
                }
                // A submenu parent shows the ▸ where a shortcut would sit.
                MenuEntry::Submenu { label, .. } => {
                    (label.as_str(), Some(String::from("\u{25b8}")))
                }
                MenuEntry::Separator | MenuEntry::Header(_) => {
                    unreachable!("handled above")
                }
            };
            let line = ratatui::text::Line::from(format!(" {label}"));
            frame.render_widget(ratatui::widgets::Paragraph::new(line).style(row_style), row);
            if let Some(hint) = right_hint {
                let hint_w = hint.chars().count() as u16;
                if hint_w + 2 <= inner.width {
                    let hint_x = inner.x + inner.width - hint_w - 1;
                    let hint_style = if is_sel {
                        Style::default().fg(sel_fg).bg(sel_bg)
                    } else {
                        Style::default().fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)))
                    };
                    frame
                        .buffer_mut()
                        .set_string(hint_x, row.y, &hint, hint_style);
                }
            }
        }
    }

    fn render_commit_dropdown(&mut self, frame: &mut ratatui::Frame) {
        use crate::widgets::source_control::CommitMenuItem;
        // The dropdown belongs to the Source Control view only. Gate on it
        // so a stale `commit_menu_open` flag can never paint the menu over
        // another sidebar view (e.g. Run-Debug) after a view switch.
        if !self.commit_menu_open || self.sidebar_view != SidebarView::SourceControl {
            self.source_control.commit_menu_item_areas.clear();
            return;
        }
        let caret = self.source_control.last_commit_caret_area;
        let main = self.source_control.last_button_area;
        if caret.width == 0 || main.width == 0 {
            return;
        }
        let default_branch = self
            .default_branch_label
            .clone()
            .unwrap_or_else(|| "default".to_string());
        let items: Vec<(CommitMenuItem, String)> = CommitMenuItem::ALL
            .iter()
            .map(|item| (*item, item.label(&default_branch)))
            .collect();
        // Row layout: [pad][icon][gap][label][pad]. The icon occupies one
        // cell at item_x+1; the label starts two cells later at item_x+3.
        const ICON_PAD: u16 = 3;
        let label_w = items
            .iter()
            .map(|(_, l)| l.chars().count() as u16 + ICON_PAD + 1)
            .max()
            .unwrap_or(0);
        let item_w: u16 = label_w.max(caret.width);
        let item_x = (caret.x + caret.width).saturating_sub(item_w).max(main.x);
        let item_y_top = caret.y + caret.height;
        let menu_rect = Rect {
            x: item_x,
            y: item_y_top,
            width: item_w,
            height: items.len() as u16,
        };
        let bg = self.theme.ui(Color::Rgb(0x25, 0x2b, 0x37));
        let fg = self.theme.ui(Color::White);
        let style = Style::default().fg(fg).bg(bg);
        frame.render_widget(ratatui::widgets::Clear, menu_rect);
        self.source_control.commit_menu_item_areas.clear();
        for (i, (item, label)) in items.into_iter().enumerate() {
            let row_y = item_y_top + i as u16;
            let row_rect = Rect {
                x: item_x,
                y: row_y,
                width: item_w,
                height: 1,
            };
            for rx in 0..row_rect.width {
                frame.buffer_mut()[(row_rect.x + rx, row_rect.y)]
                    .set_symbol(" ")
                    .set_style(style);
            }
            // Leading codicon, colored per action: push glyphs in blue,
            // diff/compare glyphs in purple, mirroring VS Code's SCM accents.
            let icon_color = match item {
                CommitMenuItem::CommitAndPush => self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb2)),
                CommitMenuItem::Push | CommitMenuItem::Pull | CommitMenuItem::Sync => {
                    self.theme.ui(Color::Rgb(0x6c, 0xb6, 0xff))
                }
                CommitMenuItem::CheckoutBranch => self.theme.ui(Color::Rgb(0x88, 0xc0, 0xd0)),
                CommitMenuItem::Stash | CommitMenuItem::StashPop => {
                    self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))
                }
                CommitMenuItem::ViewStagedDiff
                | CommitMenuItem::ViewPreviousCommitDiff
                | CommitMenuItem::ViewDefaultBranchDiff => {
                    self.theme.ui(Color::Rgb(0xc0, 0xa4, 0xf5))
                }
            };
            frame.buffer_mut().set_string(
                row_rect.x + 1,
                row_rect.y,
                item.icon().to_string(),
                Style::default().fg(icon_color).bg(bg),
            );
            frame
                .buffer_mut()
                .set_string(row_rect.x + 3, row_rect.y, &label, style);
            self.source_control
                .commit_menu_item_areas
                .push((row_rect, item));
        }
    }

    fn dispatch_commit_menu_item(&mut self, item: crate::widgets::source_control::CommitMenuItem) {
        use crate::widgets::source_control::CommitMenuItem;
        match item {
            CommitMenuItem::CommitAndPush => self.commit_and_push_source_control(),
            CommitMenuItem::Push => self.push_source_control(),
            CommitMenuItem::Pull => self.pull_source_control(),
            CommitMenuItem::Sync => self.sync_source_control(),
            CommitMenuItem::CheckoutBranch => self.open_branch_picker(),
            CommitMenuItem::Stash => self.stash_source_control(),
            CommitMenuItem::StashPop => self.stash_pop_source_control(),
            CommitMenuItem::ViewStagedDiff => self.view_staged_diff_source_control(),
            CommitMenuItem::ViewPreviousCommitDiff => {
                self.view_previous_commit_diff_source_control()
            }
            CommitMenuItem::ViewDefaultBranchDiff => self.view_default_branch_diff_source_control(),
        }
    }

    fn render_discard_confirm(&self, frame: &mut ratatui::Frame) {
        let Some(pd) = self.pending_discard.as_ref() else {
            return;
        };
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let height: u16 = 8;
        let x = (area.width.saturating_sub(width)) / 2 + area.x;
        let y = (area.height.saturating_sub(height)) / 2 + area.y;
        let rect = Rect {
            x,
            y,
            width,
            height,
        };
        let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(warn))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " DISCARD CHANGES? ",
                Style::default()
                    .fg(Color::White)
                    .bg(warn)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let warn_text = if pd.untracked {
            "This will permanently delete the file from disk."
        } else {
            "This will overwrite your local changes from HEAD."
        };
        let body = ratatui::text::Text::from(vec![
            ratatui::text::Line::from(ratatui::text::Span::styled(
                warn_text,
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(ratatui::text::Span::styled(
                truncate_for_display(&pd.rel_path, inner.width as usize),
                Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(vec![
                ratatui::text::Span::styled(
                    "[Y]",
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("es, discard   "),
                ratatui::text::Span::styled(
                    "[N]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("o / Esc"),
            ]),
        ]);
        frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
    }

    /// Confirmation modal for Revert Hunk: destroys the uncommitted edit
    /// under the diff caret, so it gets the same red Y/N gate as discard.
    fn render_revert_hunk_confirm(&self, frame: &mut ratatui::Frame) {
        let Some(pr) = self.pending_revert_hunk.as_ref() else {
            return;
        };
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let height: u16 = 8;
        let x = (area.width.saturating_sub(width)) / 2 + area.x;
        let y = (area.height.saturating_sub(height)) / 2 + area.y;
        let rect = Rect {
            x,
            y,
            width,
            height,
        };
        let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(warn))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " REVERT HUNK? ",
                Style::default()
                    .fg(Color::White)
                    .bg(warn)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let body = ratatui::text::Text::from(vec![
            ratatui::text::Line::from(ratatui::text::Span::styled(
                "This will undo the change hunk under the cursor on disk.",
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(ratatui::text::Span::styled(
                truncate_for_display(&pr.rel_path, inner.width as usize),
                Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(vec![
                ratatui::text::Span::styled(
                    "[Y]",
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("es, revert   "),
                ratatui::text::Span::styled(
                    "[N]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("o / Esc"),
            ]),
        ]);
        frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
    }

    /// The Replace All confirmation modal (#123): counts up front, commits
    /// on Enter/Y, cancels on Esc/N — the discard-all popup's shape.
    fn render_replace_all_confirm(&self, frame: &mut ratatui::Frame) {
        let Some((occurrences, files, skipped)) = self.pending_replace_all else {
            return;
        };
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let prompt = format!(
            "Replace {occurrences} occurrence(s) across {files} file(s) with \"{}\"?",
            self.search.replace
        );
        // The prompt interpolates arbitrary user text: derive the height
        // from its wrapped row count so the Enter/Esc hint can never fall
        // below the border (#124 review).
        let inner_w = width.saturating_sub(2);
        let prompt_rows = wrap_cells_variable_width(&prompt, inner_w, inner_w).len() as u16;
        let skipped_rows = u16::from(skipped > 0);
        let height: u16 = 6 + prompt_rows + skipped_rows;
        let rect = Rect {
            x: (area.width.saturating_sub(width)) / 2 + area.x,
            y: (area.height.saturating_sub(height)) / 2 + area.y,
            width,
            height,
        };
        let warn = self.theme.ui(Color::Rgb(0xe7, 0xa7, 0x3c));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(warn))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " REPLACE ALL? ",
                Style::default()
                    .fg(Color::Black)
                    .bg(warn)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        let inner = block.inner(rect);
        frame.render_widget(block, rect);
        let mut lines = vec![
            Line::from(prompt),
            Line::from(""),
            Line::from("Files are rewritten on disk."),
        ];
        if skipped > 0 {
            lines.push(Line::from(format!(
                "{skipped} open file(s) with unsaved changes will be skipped."
            )));
        }
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Enter / Y replaces \u{00b7} Esc cancels",
            Style::default().fg(self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb8))),
        )));
        frame.render_widget(
            Paragraph::new(lines).wrap(ratatui::widgets::Wrap { trim: false }),
            inner,
        );
    }

    /// Confirmation modal for "Discard All Changes" — reverts every tracked
    /// edit to HEAD, so it gets the same red Y/N gate as a single discard.
    fn render_discard_all_confirm(&self, frame: &mut ratatui::Frame) {
        if !self.pending_discard_all {
            return;
        }
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let height: u16 = 7;
        let rect = Rect {
            x: (area.width.saturating_sub(width)) / 2 + area.x,
            y: (area.height.saturating_sub(height)) / 2 + area.y,
            width,
            height,
        };
        let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(warn))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " DISCARD ALL CHANGES? ",
                Style::default()
                    .fg(Color::White)
                    .bg(warn)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let body = ratatui::text::Text::from(vec![
            ratatui::text::Line::from(ratatui::text::Span::styled(
                "This reverts every tracked file to HEAD. Untracked files are kept.",
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(vec![
                ratatui::text::Span::styled(
                    "[Y]",
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("es, discard all   "),
                ratatui::text::Span::styled(
                    "[N]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("o / Esc"),
            ]),
        ]);
        frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
    }

    /// Confirmation modal for enabling broadcast input: the classic footgun
    /// is typing a destructive command into panes you forgot were listening,
    /// so switching it on gets the same red Y/N gate iTerm2 shows.
    fn render_broadcast_confirm(&self, frame: &mut ratatui::Frame) {
        if !self.pending_broadcast_enable {
            return;
        }
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let height: u16 = 7;
        let rect = Rect {
            x: (area.width.saturating_sub(width)) / 2 + area.x,
            y: (area.height.saturating_sub(height)) / 2 + area.y,
            width,
            height,
        };
        let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(warn))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " BROADCAST INPUT TO ALL PANES? ",
                Style::default()
                    .fg(Color::White)
                    .bg(warn)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let receiving = self
            .terminals
            .iter()
            .filter(|t| !t.broadcast_excluded)
            .count()
            .max(1);
        let body = ratatui::text::Text::from(vec![
            ratatui::text::Line::from(ratatui::text::Span::styled(
                format!(
                    "Every keystroke and paste will go to {receiving} terminal panes at once (red \u{21f6} pills mark them). Cmd+K I stops it; Cmd+K Shift+I excludes a pane."
                ),
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(vec![
                ratatui::text::Span::styled(
                    "[Y]",
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("es, broadcast   "),
                ratatui::text::Span::styled(
                    "[N]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("o / Esc"),
            ]),
        ]);
        frame.render_widget(
            ratatui::widgets::Paragraph::new(body).wrap(ratatui::widgets::Wrap { trim: true }),
            inner,
        );
    }

    /// The confirm popup for a runnable fence (#353): the whole block, the
    /// pane and directory it would run in, red when it looks destructive.
    fn render_run_block_confirm(&self, frame: &mut ratatui::Frame) {
        let Some(block) = self.pending_run_block.as_ref() else {
            return;
        };
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let inner_w = width.saturating_sub(4) as usize;
        let shown: Vec<String> = block
            .code
            .lines()
            .take(8)
            // A line wider than the popup is cut with a visible mark: what
            // the popup hides must never look complete.
            .map(|l| {
                if l.chars().count() > inner_w {
                    let mut cut: String = l.chars().take(inner_w.saturating_sub(1)).collect();
                    cut.push('\u{2026}');
                    cut
                } else {
                    l.to_string()
                }
            })
            .collect();
        let more = block.code.lines().count().saturating_sub(shown.len());
        let height =
            (shown.len() as u16 + 6 + u16::from(more > 0)).min(area.height.saturating_sub(2));
        let rect = Rect {
            x: (area.width.saturating_sub(width)) / 2 + area.x,
            y: (area.height.saturating_sub(height)) / 2 + area.y,
            width,
            height,
        };
        let (title, accent) = if block.destructive {
            (
                " RUN THIS BLOCK? IT LOOKS DESTRUCTIVE ",
                self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)),
            )
        } else {
            (" RUN THIS BLOCK? ", self.theme.accent())
        };
        let popup = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(accent))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                title,
                Style::default()
                    .fg(Color::White)
                    .bg(accent)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(popup, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let mut lines: Vec<ratatui::text::Line> =
            vec![ratatui::text::Line::from(ratatui::text::Span::styled(
                format!("in pane {} at {}", block.pane_name, block.cwd.display()),
                Style::default().fg(self.theme.ui(Color::Rgb(0xCC, 0xCC, 0xCC))),
            ))];
        for l in &shown {
            lines.push(ratatui::text::Line::from(ratatui::text::Span::styled(
                l.clone(),
                Style::default().fg(self.theme.ui(Color::White)),
            )));
        }
        if more > 0 {
            lines.push(ratatui::text::Line::from(ratatui::text::Span::styled(
                format!("… {more} more line(s)"),
                Style::default().fg(self.theme.ui(Color::Rgb(0x88, 0x88, 0x88))),
            )));
        }
        lines.push(ratatui::text::Line::from(""));
        lines.push(ratatui::text::Line::from(vec![
            ratatui::text::Span::styled(
                "[Y]",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
            ratatui::text::Span::raw("es, run   "),
            ratatui::text::Span::styled(
                "[N]",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            ),
            ratatui::text::Span::raw("o / Esc"),
        ]));
        frame.render_widget(
            ratatui::widgets::Paragraph::new(ratatui::text::Text::from(lines)),
            inner,
        );
    }

    fn render_terminal_warning(&self, frame: &mut ratatui::Frame) {
        if !self.pending_terminal_warning {
            return;
        }
        let area = frame.area();
        // The lower clamp bound must never beat the frame itself: on a
        // terminal narrower than 50 columns the modal used to come out
        // WIDER than the buffer and the paint panicked at launch (#192).
        let width = area.width.saturating_sub(8).clamp(50, 96).min(area.width);
        let height: u16 = 11u16.min(area.height);
        let x = (area.width.saturating_sub(width)) / 2 + area.x;
        let y = (area.height.saturating_sub(height)) / 2 + area.y;
        let rect = Rect {
            x,
            y,
            width,
            height,
        };
        let warn = self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00));
        let accent = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(warn))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " UNSUPPORTED TERMINAL ",
                Style::default()
                    .fg(Color::Black)
                    .bg(warn)
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let current = std::env::var("TERM_PROGRAM")
            .ok()
            .filter(|s| !s.is_empty())
            .or_else(|| std::env::var("TERM").ok().filter(|s| !s.is_empty()))
            .unwrap_or_else(|| String::from("this terminal"));
        let body = ratatui::text::Text::from(vec![
            Line::from(Span::styled(
                "Croft draws its icons and images with inline-image protocols",
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            Line::from(Span::styled(
                format!("that {current} does not support, so the activity bar and"),
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            Line::from(Span::styled(
                "file icons stay blank. Croft still runs; for the full UI use:",
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            Line::from(""),
            Line::from(vec![
                Span::raw("  macOS:  "),
                Span::styled(
                    "iTerm2",
                    Style::default().fg(accent).add_modifier(Modifier::BOLD),
                ),
                Span::raw("  or  "),
                Span::styled(
                    "Ghostty",
                    Style::default().fg(accent).add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw("  Linux:  "),
                Span::styled(
                    "Ghostty",
                    Style::default().fg(accent).add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::styled(
                    "[any key]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw(" dismiss    "),
                Span::styled(
                    "[D]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw("on't show again"),
            ]),
        ]);
        frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
    }

    fn render_local_open_confirm(&self, frame: &mut ratatui::Frame) {
        let Some(url) = &self.pending_local_open else {
            return;
        };
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(50, 96);
        let height: u16 = 8;
        let x = (area.width.saturating_sub(width)) / 2 + area.x;
        let y = (area.height.saturating_sub(height)) / 2 + area.y;
        let rect = Rect {
            x,
            y,
            width,
            height,
        };
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00))))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(ratatui::text::Span::styled(
                " OPEN ON LOCAL MAC? ",
                Style::default()
                    .fg(Color::Black)
                    .bg(self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00)))
                    .add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let body = ratatui::text::Text::from(vec![
            ratatui::text::Line::from(ratatui::text::Span::styled(
                "This URL will open in YOUR LOCAL MAC's browser via the croft relay.",
                Style::default().fg(self.theme.ui(Color::White)),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(ratatui::text::Span::styled(
                truncate_for_display(url, inner.width as usize),
                Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))),
            )),
            ratatui::text::Line::from(""),
            ratatui::text::Line::from(vec![
                ratatui::text::Span::styled(
                    "[Y]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("es once   "),
                ratatui::text::Span::styled(
                    "[A]",
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("lways for this session   "),
                ratatui::text::Span::styled(
                    "[N]",
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ),
                ratatui::text::Span::raw("o / Esc"),
            ]),
        ]);
        frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
    }

    /// Paint the transient port-detection toast in the bottom-right corner and
    /// record its clickable action-button rects. Click-only: it never captures
    /// keystrokes, so it can't interfere with terminal typing.
    fn render_port_toast(&mut self, frame: &mut ratatui::Frame) {
        let Some(toast) = self.port_toast.as_ref() else {
            return;
        };
        let port = toast.port;
        let origin_remote = toast.origin_remote;
        let proc = toast.process.clone().unwrap_or_default();

        let accent = self.theme.accent();
        let btn_bg = self.theme.button();
        let actions: Vec<(String, PortToastAction)> = if origin_remote {
            vec![
                (
                    " Forward & Open ".to_string(),
                    PortToastAction::ForwardAndOpen,
                ),
                (" Forward ".to_string(), PortToastAction::ForwardOnly),
                (" \u{2715} ".to_string(), PortToastAction::Dismiss),
            ]
        } else {
            vec![
                (" Open ".to_string(), PortToastAction::Open),
                (" \u{2715} ".to_string(), PortToastAction::Dismiss),
            ]
        };
        let buttons_w: u16 = actions
            .iter()
            .map(|(l, _)| l.chars().count() as u16 + 1)
            .sum::<u16>()
            + 1;
        let title_line = format!("\u{25cf} port {port}  {proc}");
        let inner_w = buttons_w.max(title_line.chars().count() as u16);

        let area = frame.area();
        let width = (inner_w + 4).min(area.width.saturating_sub(2));
        let height: u16 = 4;
        let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
        if area.width < width + 2 || area.height < height + status_h + 1 {
            return;
        }
        let rect = Rect {
            x: area.x + area.width - width - 2,
            y: area.y + area.height - height - status_h - 1,
            width,
            height,
        };
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(accent))
            .style(Style::default().bg(self.theme.editor_bg()))
            .title(ratatui::text::Span::styled(
                " PORT DETECTED ",
                Style::default().fg(accent).add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };

        let buf = frame.buffer_mut();
        buf.set_stringn(
            inner.x,
            inner.y,
            &title_line,
            inner.width as usize,
            Style::default().fg(self.theme.ui(Color::Rgb(0xCC, 0xCC, 0xCC))),
        );
        let mut bx = inner.x;
        let by = inner.y + 1;
        let mut rects: Vec<(Rect, PortToastAction)> = Vec::new();
        for (label, action) in &actions {
            let w = label.chars().count() as u16;
            if bx + w > inner.x + inner.width {
                break;
            }
            buf.set_stringn(
                bx,
                by,
                label,
                w as usize,
                Style::default()
                    .fg(Color::White)
                    .bg(btn_bg)
                    .add_modifier(Modifier::BOLD),
            );
            rects.push((
                Rect {
                    x: bx,
                    y: by,
                    width: w,
                    height: 1,
                },
                *action,
            ));
            bx += w + 1;
        }
        if let Some(t) = self.port_toast.as_mut() {
            t.buttons = rects;
        }
    }

    /// Paint the update-available popup in the bottom-LEFT corner (the
    /// port toast owns the right) and record its button rects. Click-only,
    /// like the port toast: it never captures keystrokes (#333).
    fn render_update_toast(&mut self, frame: &mut ratatui::Frame) {
        let Some(toast) = self.update_toast.as_ref() else {
            return;
        };
        let version = toast.version.clone();
        let ready = toast.ready;
        let staging = self.staged_status == UpdateStatus::InProgress && !ready;
        let accent = self.theme.accent();
        let btn_bg = self.theme.button();
        let actions: Vec<(String, UpdateToastAction)> = if ready {
            vec![(" Relaunch ".to_string(), UpdateToastAction::Relaunch)]
        } else if staging {
            Vec::new()
        } else {
            vec![
                (" Update ".to_string(), UpdateToastAction::Update),
                (" Later ".to_string(), UpdateToastAction::Later),
            ]
        };
        let title_line = if ready {
            format!("\u{27f3} croft v{version} is ready - relaunch to update")
        } else if staging {
            format!(
                "{} building croft v{version} in the background",
                self.update_spinner_glyph()
            )
        } else {
            format!(
                "\u{27f3} croft v{version} is available (you have v{})",
                env!("CARGO_PKG_VERSION")
            )
        };
        let buttons_w: u16 = actions
            .iter()
            .map(|(l, _)| l.chars().count() as u16 + 1)
            .sum::<u16>()
            + 1;
        let inner_w = buttons_w.max(title_line.chars().count() as u16);
        let area = frame.area();
        let width = (inner_w + 4).min(area.width.saturating_sub(2));
        let height: u16 = 4;
        let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
        // The port toast owns the bottom-right band; at ordinary widths
        // this popup's title reaches into it, so stack above it instead.
        let stack: u16 = if self.port_toast.is_some() { height } else { 0 };
        if area.width < width + 2 || area.height < height + status_h + 1 + stack {
            return;
        }
        let rect = Rect {
            x: area.x + 1,
            y: area.y + area.height - height - status_h - 1 - stack,
            width,
            height,
        };
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(accent))
            .style(Style::default().bg(self.theme.editor_bg()))
            .title(ratatui::text::Span::styled(
                " UPDATE ",
                Style::default().fg(accent).add_modifier(Modifier::BOLD),
            ));
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let buf = frame.buffer_mut();
        buf.set_stringn(
            inner.x,
            inner.y,
            &title_line,
            inner.width as usize,
            Style::default().fg(self.theme.ui(Color::Rgb(0xCC, 0xCC, 0xCC))),
        );
        let mut bx = inner.x;
        let by = inner.y + 1;
        let mut rects: Vec<(Rect, UpdateToastAction)> = Vec::new();
        for (label, action) in &actions {
            let w = label.chars().count() as u16;
            if bx + w > inner.x + inner.width {
                break;
            }
            buf.set_stringn(
                bx,
                by,
                label,
                w as usize,
                Style::default()
                    .fg(Color::White)
                    .bg(btn_bg)
                    .add_modifier(Modifier::BOLD),
            );
            rects.push((
                Rect {
                    x: bx,
                    y: by,
                    width: w,
                    height: 1,
                },
                *action,
            ));
            bx += w + 1;
        }
        if let Some(t) = self.update_toast.as_mut() {
            t.buttons = rects;
        }
    }

    fn render_prompt(&self, frame: &mut ratatui::Frame) {
        let Some(p) = &self.prompt else { return };
        let area = frame.area();
        let width = area.width.saturating_sub(8).clamp(40, 80);
        let height = if p.error.is_some() { 6 } else { 5 };
        let x = (area.width.saturating_sub(width)) / 2 + area.x;
        let y = (area.height.saturating_sub(height)) / 2 + area.y;
        let rect = Rect {
            x,
            y,
            width,
            height,
        };
        let grad = self.popup_gradient();
        let cursor_fg = if grad {
            rgb_color(GRAD_TL)
        } else {
            self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))
        };
        let title_bg = if grad {
            rgb_color(POPUP_SEL_BG)
        } else {
            self.theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
        };
        let title = ratatui::text::Span::styled(
            format!(" {} ", p.label),
            Style::default()
                .fg(self.theme.ui(Color::White))
                .bg(title_bg)
                .add_modifier(Modifier::BOLD),
        );
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))))
            .style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
            .title(title.clone());
        frame.render_widget(ratatui::widgets::Clear, rect);
        frame.render_widget(block, rect);
        // Black theme: overpaint the solid border with the gradient, then
        // re-stamp the title the gradient top edge just covered.
        if grad {
            paint_gradient_box(frame.buffer_mut(), rect);
            frame
                .buffer_mut()
                .set_span(rect.x + 1, rect.y, &title, title.width() as u16);
        }
        let inner = Rect {
            x: rect.x + 2,
            y: rect.y + 1,
            width: rect.width.saturating_sub(4),
            height: rect.height.saturating_sub(2),
        };
        let (top_line, hint_text) = match &p.kind {
            PromptKind::Create(_) => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                "Enter to create, Esc to cancel",
            ),
            PromptKind::Rename(_) => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                "Enter to rename, Esc to cancel",
            ),
            PromptKind::RenameSymbol { .. } => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                "Enter to rename symbol, Esc to cancel",
            ),
            PromptKind::RenameTerminal(_) => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                "Enter to rename, Esc to cancel (blank clears the name)",
            ),
            PromptKind::AnnotateTerminal { existing, .. } => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                if existing.is_some() {
                    "Enter to update the note, Esc to cancel (blank deletes it)"
                } else {
                    "Enter to pin the note to the selection, Esc to cancel"
                },
            ),
            PromptKind::BreakpointCondition { .. } => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                "Enter to set condition (blank for a plain breakpoint), Esc to cancel",
            ),
            PromptKind::Logpoint { .. } => (
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw("> "),
                    ratatui::text::Span::styled(
                        p.buffer.as_str(),
                        Style::default().fg(self.theme.ui(Color::White)),
                    ),
                    ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
                ]),
                "Enter to set the log message, {expr} interpolates (blank for a plain breakpoint), Esc to cancel",
            ),
        };
        frame.render_widget(
            ratatui::widgets::Paragraph::new(top_line),
            Rect {
                x: inner.x,
                y: inner.y,
                width: inner.width,
                height: 1,
            },
        );
        let hint = ratatui::widgets::Paragraph::new(ratatui::text::Line::from(hint_text))
            .style(Style::default().fg(Color::DarkGray));
        frame.render_widget(
            hint,
            Rect {
                x: inner.x,
                y: inner.y + 2,
                width: inner.width,
                height: 1,
            },
        );
        if let Some(err) = &p.error {
            let line = ratatui::widgets::Paragraph::new(ratatui::text::Line::from(format!(
                "Error: {err}"
            )))
            .style(Style::default().fg(self.theme.ui(Color::Rgb(0xe8, 0x27, 0x4b))));
            frame.render_widget(
                line,
                Rect {
                    x: inner.x,
                    y: inner.y + 3,
                    width: inner.width,
                    height: 1,
                },
            );
        }
    }

    /// Dispatch the second key of a `Cmd+K`-prefixed chord (VS Code's two-key
    /// model). Returns `true` if the key completed a chord and was consumed,
    /// `false` if it matched nothing (the caller then processes it normally).
    /// The second key reaches us as ordinary input, so `Cmd` on the trailing
    /// key (e.g. `Cmd+K Cmd+T`) is accepted but not required.
    fn handle_cmd_k_chord(&mut self, key: KeyEvent) -> bool {
        let plain = !key.modifiers.contains(KeyModifiers::ALT);
        let shifted = key.modifiers.contains(KeyModifiers::SHIFT);
        match key.code {
            // Cmd+K ⇧C / ⇧S / ⇧R with the terminal focused: the keyboard
            // forms of the decoration-menu actions, applied to the LAST
            // finished command (VS Code's copyLastCommandOutput family).
            // Must precede the case-insensitive C/S/R editor arms below.
            KeyCode::Char('C' | 'S' | 'R') if shifted && plain && self.focus == Pane::Terminal => {
                let KeyCode::Char(c) = key.code else {
                    return false;
                };
                let Some(d) = self.last_command_decoration() else {
                    self.status = String::from("No finished commands yet");
                    return true;
                };
                let idx = self.active_terminal;
                match c {
                    'C' => self.copy_command_output(idx, d),
                    'S' => self.select_command_output(idx, d),
                    _ => self.rerun_command(idx, d),
                }
                true
            }
            // Cmd+K Shift+T: reopen the most recently closed terminal pane
            // (the browser reopen-tab convention under the Cmd+K leader).
            // Must precede the case-insensitive T theme arm below.
            KeyCode::Char('T') if shifted && plain => {
                self.undo_close_terminal();
                true
            }
            // Cmd+K Shift+W: reopen the most recently closed editor tab
            // (VS Code "Reopen Closed Editor"; ⇧W pairs with Cmd+W the way
            // ⇧T pairs with the terminal close). Matched case-insensitively
            // because CSI-u hosts report Shift+W as `Char('w') + SHIFT`
            // while iTerm2's forwarder delivers `Char('W')`. Must precede
            // any case-insensitive W arm.
            KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'w') => {
                self.reopen_closed_tab();
                true
            }
            // Cmd+K Shift+N with the terminal focused: delete the
            // annotation(s) under the selection. Must precede any
            // case-insensitive N arm.
            KeyCode::Char('N') if shifted && plain && self.focus == Pane::Terminal => {
                self.delete_terminal_annotations_in_selection();
                true
            }
            // Cmd+K N with the terminal focused: pin a note to the selected
            // output span (iTerm2's annotations); over an existing note it
            // edits in place.
            KeyCode::Char(c)
                if plain && c.eq_ignore_ascii_case(&'n') && self.focus == Pane::Terminal =>
            {
                self.begin_annotate_terminal();
                true
            }
            // Cmd+K Cmd+T / Cmd+K T: open the Color Theme picker.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'t') => {
                self.open_theme_picker();
                true
            }
            // Cmd+K A: who is attached to this multiplayer session
            // (Session: Participants).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'a') => {
                self.open_participants_picker();
                true
            }
            // Cmd+K X: cancel the AI stream (croft pair) — the keyboard
            // form of the gutter stop button; the pilot reverts the
            // streamed text.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'x') => {
                self.collab_cancel_stream();
                true
            }
            // Cmd+K Cmd+Q: Go to Last Edit Location (VS Code's chord; the
            // second key carries Cmd, which keeps it distinct from the
            // navigator's plain Cmd+K Q below).
            KeyCode::Char(c)
                if c.eq_ignore_ascii_case(&'q') && key.modifiers.contains(KeyModifiers::SUPER) =>
            {
                self.goto_last_edit_location();
                true
            }
            // Cmd+K Q: ask the navigator about the caret line, or the
            // selected lines when a selection is active (Q for question).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'q') => {
                let (range, selection) = match self.editor.selection_rows() {
                    Some(rows) => (rows, self.editor.selection_text()),
                    None => {
                        let row = self.editor.cursor_row;
                        ((row, row), String::new())
                    }
                };
                self.open_ask_navigator(range, selection);
                true
            }
            // Cmd+K Y: yield the turn — the navigator reviews the active
            // file comment-only; its say lands as gutter diamonds and
            // OUTPUT commentary, never as edits.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'y') => {
                self.yield_to_navigator();
                true
            }
            // Cmd+K Shift+Cmd+\: open a second view of the active file beside it
            // ("Split in Group"). Must precede the plain Cmd+\ (Split Up) arm,
            // which ignores Shift. Shift+\ may arrive as '|' on some layouts.
            KeyCode::Char('\\' | '|') if key.modifiers.contains(KeyModifiers::SHIFT) => {
                self.split_in_group();
                true
            }
            // Cmd+K Cmd+\ (or Cmd+K \): split the active group UP (stacked, the
            // new group above). Plain Cmd+\ already splits Right.
            KeyCode::Char('\\') if plain => {
                self.split_editor_dir(editor_layout::SplitDir::Vertical, false);
                true
            }
            // Cmd+K →: close the editors to the right of the active tab.
            KeyCode::Right if plain => {
                let from = self.editor.active_index();
                self.record_closed_tabs_where(|i, ed| i > from && !ed.pinned);
                let removed = self.editor.close_to_right(from);
                if removed > 0 {
                    self.sync_open_file_poll_mtime();
                    self.status = if removed == 1 {
                        String::from("Closed 1 tab to the right")
                    } else {
                        format!("Closed {removed} tabs to the right")
                    };
                    self.poke_cursor();
                }
                true
            }
            // Cmd+K S: mark the active file as the compare anchor.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'s') => {
                if let Some(path) = self.editor.path.clone() {
                    let label = path
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| path.display().to_string());
                    self.compare_anchor = Some(path);
                    self.status = format!("Selected {label} for compare");
                } else {
                    self.status = String::from("Select for Compare: no active file");
                }
                true
            }
            // Cmd+K C: diff the active file against the compare anchor.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'c') => {
                match (self.compare_anchor.clone(), self.editor.path.clone()) {
                    (Some(anchor), Some(other)) => match self.editor.open_diff(&anchor, &other) {
                        Ok(()) => {
                            self.focus_pane(Pane::Editor);
                            self.compare_anchor = None;
                            self.sync_open_file_poll_mtime();
                            let l = anchor
                                .file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_else(|| anchor.display().to_string());
                            let r = other
                                .file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_else(|| other.display().to_string());
                            self.status = format!("Diff: {l} \u{2194} {r}");
                        }
                        Err(e) => self.status = format!("Diff failed: {e}"),
                    },
                    (None, _) => {
                        self.status = String::from("Compare with Selected: nothing selected yet")
                    }
                    (_, None) => {
                        self.status = String::from("Compare with Selected: no active file")
                    }
                }
                true
            }
            // Cmd+K W: close all editor tabs.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'w') => {
                self.close_all_tabs();
                true
            }
            // Cmd+K U: close all saved (non-dirty) editor tabs.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'u') => {
                self.close_saved_tabs();
                true
            }
            // Cmd+K E: reveal the active file in the Explorer tree.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'e') => {
                if let Some(path) = self.editor.path.clone() {
                    self.reveal_in_explorer(path);
                } else {
                    self.status = String::from("Reveal in Explorer View: no active file");
                }
                true
            }
            // Cmd+K Shift+H: outgoing calls (what does this call?). Must
            // precede the case-insensitive H arm below.
            KeyCode::Char('H') if shifted && plain => {
                self.request_call_hierarchy_at_cursor(false);
                true
            }
            // Cmd+K G: accept the ssh-pane workspace offer (#364) — "go to
            // the host". The same remote flow the palette command runs; the
            // offer only saves the reaching.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'g') => {
                match self.accept_ssh_offer() {
                    Some(host) => self.request_remote_launch(host, None),
                    None => {
                        self.status = String::from(
                            "No ssh workspace offer is open (it appears when a pane connects to a host in ~/.ssh/config)",
                        );
                    }
                }
                true
            }
            // Cmd+K H: incoming calls — who calls the symbol at the caret
            // (VS Code's call Hierarchy, peek replaced by croft's picker).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'h') => {
                self.request_call_hierarchy_at_cursor(true);
                true
            }
            // Cmd+K P: pin / unpin the active tab. This chord was Cmd+K
            // Shift+Enter (and Keep Open bare Cmd+K Enter) — both silently
            // SHADOWED the later, documented Cmd+K Enter run-test-at-cursor
            // arms below, so the Enter family now belongs to Testing alone.
            // Cmd+K ⇧P: keep the active preview tab open (sibling of the pin
            // chord below). Must precede the case-insensitive 'p' arm, which
            // would swallow the shifted press.
            KeyCode::Char('P') if shifted && plain => {
                if self.editor.keep_open(self.editor.active_index()) {
                    self.status = String::from("Kept tab open");
                    self.poke_cursor();
                }
                true
            }
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'p') => {
                let idx = self.editor.active_index();
                let pinned = self.editor.toggle_pin(idx);
                self.status = String::from(if pinned { "Pinned tab" } else { "Unpinned tab" });
                self.poke_cursor();
                true
            }
            // Cmd+K Shift+O: move the active tab into a new window. Must precede
            // the plain Cmd+K O (Copy) arm, which ignores Shift.
            KeyCode::Char(c)
                if c.eq_ignore_ascii_case(&'o') && key.modifiers.contains(KeyModifiers::SHIFT) =>
            {
                self.move_into_new_window(self.editor.active_index());
                true
            }
            // Cmd+K O: copy the active tab into a new window (VS Code's binding).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'o') => {
                self.copy_into_new_window(self.editor.active_index());
                true
            }
            // Cmd+K Z: toggle Zen Mode (VS Code's binding).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'z') => {
                self.toggle_zen_mode();
                true
            }
            // Cmd+K Cmd+F (SUPER/CTRL held on the second key): Format
            // Selection, VS Code's binding (#254). Must precede the plain
            // Cmd+K F arm, which keeps croft's format-on-save toggle.
            KeyCode::Char(c)
                if plain
                    && c.eq_ignore_ascii_case(&'f')
                    && (key.modifiers.contains(KeyModifiers::SUPER)
                        || key.modifiers.contains(KeyModifiers::CONTROL)) =>
            {
                self.format_selection();
                true
            }
            // Cmd+K F: toggle Format on Save (croft binding; VS Code leaves this
            // preference unbound, but every croft action carries an accelerator).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'f') => {
                self.toggle_format_on_save();
                true
            }
            // Cmd+K K: clear the active terminal (VS Code clears with Cmd+K).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'k') => {
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.clear_terminal_at(self.active_terminal);
                true
            }
            // Cmd+K R: rename the active terminal pane.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'r') => {
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.begin_rename_terminal(self.active_terminal);
                true
            }
            // Cmd+K M: maximize the active terminal pane / restore the even
            // split (croft binding; VS Code leaves its panel-maximize
            // relative unbound, and every croft action carries an
            // accelerator).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'m') => {
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.toggle_terminal_pane_maximize();
                true
            }
            // Cmd+K [ / Cmd+K ]: fold the active terminal pane to a strip,
            // and give every folded pane its width back (#313). VS Code binds
            // its own fold / unfold pair to ⌘K ⌘[ and ⌘K ⌘], so the gesture
            // keeps the keys it already has elsewhere.
            //
            // NOT ⌘K E, which the design proposal had picked as "even": that
            // is croft's reveal-in-Explorer and the arm would never have been
            // reached, since an earlier `e` arm in this same match wins.
            // NOT ⌘K -, either: `-` is close, on the button and here.
            //
            // Cmd+K M (pane-maximize) is untouched: maximize and collapse are
            // orthogonal and compose.
            KeyCode::Char('[') if plain => {
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.collapse_active_terminal_pane();
                true
            }
            KeyCode::Char(']') if plain => {
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.restore_all_terminal_panes();
                true
            }
            // Cmd+K D: dump the active terminal's scrollback into a scratch
            // editor tab (kitty's show_scrollback, with the editor as the
            // pager: find, vim mode, save, and path:line jumps come free).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'d') => {
                self.open_scrollback_in_editor();
                true
            }
            // Cmd+K B: show the Testing view (B for the beaker icon). Cmd+Shift+T
            // — VS Code's Testing-ish chord — is already croft's focus-Terminal
            // chord, so the Cmd+K leader hosts this the way it hosts Zen (Cmd+K Z).
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'b') => {
                self.open_testing_view();
                true
            }
            // Cmd+K Shift+I: toggle whether the active pane receives
            // broadcast input (iTerm2's per-session broadcast-domain
            // toggle). Must precede the case-insensitive I arm below.
            KeyCode::Char('I') if shifted && plain => {
                self.toggle_broadcast_exclusion();
                true
            }
            // Cmd+K I: toggle broadcast input — type into every terminal
            // pane at once (iTerm2's Cmd+Opt+I; I for Input). Enabling is
            // gated on a confirm popup.
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'i') => {
                self.toggle_broadcast_input();
                true
            }
            // Cmd+K Shift+Enter: debug the test the caret sits in (checked
            // before the plain-Enter run arm, which also matches this chord).
            KeyCode::Enter if key.modifiers.contains(KeyModifiers::SHIFT) => {
                self.debug_test_at_cursor();
                true
            }
            // Cmd+K Enter: run the test the editor caret sits in. Enter already
            // means "run" in the Testing view (runs all), so it carries over as
            // the run verb under the Cmd+K leader (no new terminal registration).
            KeyCode::Enter => {
                self.run_test_at_cursor();
                true
            }
            // Cmd+K Cmd+0 / Cmd+K 0: collapse every fold (VS Code "Fold All").
            KeyCode::Char('0') if plain => {
                self.editor.fold_all();
                self.poke_cursor();
                true
            }
            // Cmd+K Cmd+J / Cmd+K J: expand every fold (VS Code "Unfold All").
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'j') => {
                self.editor.unfold_all();
                self.poke_cursor();
                true
            }
            // Cmd+K Shift+L: Agent: New Worktree Lane (#348). Matched
            // case-insensitively for the same CSI-u / iTerm2 split as ⇧W,
            // and so it must precede the case-insensitive L arm below.
            KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'l') => {
                self.open_new_lane_prompt();
                true
            }
            // Cmd+K Cmd+L / Cmd+K L: toggle the fold at the cursor line
            // (VS Code "Toggle Fold").
            KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'l') => {
                let row = self.editor.cursor_row;
                self.editor.toggle_fold(row);
                self.poke_cursor();
                true
            }
            // Cmd+K Cmd+/ : collapse every comment block (VS Code
            // "Fold All Block Comments", #254).
            KeyCode::Char('/') if plain => {
                self.editor
                    .fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Comment);
                self.poke_cursor();
                true
            }
            // Cmd+K Cmd+8 / Cmd+K Cmd+9: fold / unfold every #region
            // (VS Code "Fold/Unfold All Regions", #254).
            KeyCode::Char('8') if plain => {
                self.editor
                    .fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region);
                self.poke_cursor();
                true
            }
            KeyCode::Char('9') if plain => {
                self.editor
                    .unfold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region);
                self.poke_cursor();
                true
            }
            _ => false,
        }
    }

    /// Dispatch one key, capturing it into a live macro recording (#255).
    ///
    /// The capture happens AFTER dispatch and only if recording was already
    /// on both before and after: that is what keeps the gesture that ENDS a
    /// recording (vim's closing `q`, the palette's stop command) out of the
    /// macro it ends, and the gesture that STARTS one out of the macro it
    /// opens. Keys are recorded rather than resolved commands because only
    /// palette selections and user-rebound chords reach `run_command` — the
    /// built-in defaults call their app methods directly, so a command-level
    /// recorder would miss most of what a user does.
    fn handle_key(&mut self, key: KeyEvent) -> Result<()> {
        // Esc dismisses an open ssh-pane offer (#364) without being consumed:
        // the offer is a status-bar hint, not a modal, so whatever Esc meant
        // to the focused pane still happens.
        if key.code == KeyCode::Esc
            && matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
        {
            self.dismiss_ssh_offer();
        }
        let capture =
            self.macro_recording.is_some() && !self.macro_replaying && self.focus == Pane::Editor;
        let result = self.handle_key_inner(key);
        // Focus is re-checked after dispatch too: a key that hands focus to
        // the terminal would otherwise be recorded while everything after it
        // is dropped, producing a macro that replays a focus change and then
        // silently loses its payload.
        if capture && self.macro_recording.is_some() {
            if self.focus == Pane::Editor {
                self.record_macro_key(key);
            } else {
                // The issue asks for skipped keys to be logged rather than
                // vanishing: a macro that quietly stopped recording halfway
                // is otherwise indistinguishable from one that recorded
                // everything.
                crate::output::push(
                    "Macros",
                    crate::output::OutputLevel::Info,
                    &format!("skipped {key:?}: recording captures the editor pane only"),
                );
            }
        }
        result
    }

    fn handle_key_inner(&mut self, key: KeyEvent) -> Result<()> {
        // Peek Definition popup: Enter converts to the real jump, Esc
        // closes, and any other key closes it and keeps its normal
        // meaning — the popup is a glance, never a mode (#115). Gated on
        // Press/Repeat like every other modal (the app-wide filter runs
        // just below), so a key RELEASE never dismisses or jumps.
        if self.peek_popup.is_some()
            && matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
        {
            match key.code {
                KeyCode::Enter => {
                    if let Some((path, line, col)) = self.peek_target.take() {
                        self.close_peek_popup();
                        self.go_to_definition(path, line, col);
                    }
                    return Ok(());
                }
                KeyCode::Esc => {
                    self.close_peek_popup();
                    return Ok(());
                }
                _ => self.close_peek_popup(),
            }
        }
        if key.kind != KeyEventKind::Press && key.kind != KeyEventKind::Repeat {
            return Ok(());
        }
        self.hover_popup = None;
        self.hover_diagnostic = None;
        self.hover_request_id = None;
        // `Cmd+K` leader: if armed, this keystroke is the second half of a
        // `Cmd+K`-prefixed chord. Consume the leader regardless; dispatch the
        // chord if it matches and the window has not lapsed, otherwise fall
        // through so the key keeps its normal meaning (e.g. Esc cancels).
        if let Some(started) = self.cmd_k_leader.take() {
            const CMD_K_LEADER_TIMEOUT: std::time::Duration =
                std::time::Duration::from_millis(1500);
            if started.elapsed() <= CMD_K_LEADER_TIMEOUT && self.handle_cmd_k_chord(key) {
                return Ok(());
            }
        }
        // Modal layer: the unsupported-terminal nudge sits on top of everything
        // at startup. Any key dismisses it for this session; D also persists the
        // dismissal so it never shows again. All keys are swallowed so the user
        // can't accidentally type through into the UI below.
        if self.pending_terminal_warning {
            match key.code {
                KeyCode::Char('d') | KeyCode::Char('D') => self.dismiss_terminal_warning(true),
                _ => self.dismiss_terminal_warning(false),
            }
            return Ok(());
        }
        if self.connect_dialog.is_some() {
            self.handle_connect_dialog_key(key);
            return Ok(());
        }
        if self.shortcuts_modal.is_some() {
            self.handle_shortcuts_modal_key(key);
            return Ok(());
        }
        if self.file_finder.is_some() {
            self.handle_file_finder_key(key);
            return Ok(());
        }
        if self.command_palette.is_some() {
            self.handle_command_palette_key(key);
            return Ok(());
        }
        if self.workspace_symbols.is_some() {
            self.handle_workspace_symbols_key(key);
            return Ok(());
        }
        if self.go_to_symbol.is_some() {
            self.handle_go_to_symbol_key(key);
            return Ok(());
        }
        if self.process_picker.is_some() {
            self.handle_process_picker_key(key);
            return Ok(());
        }
        if self.zoxide_jump.is_some() {
            self.handle_zoxide_jump_key(key);
            return Ok(());
        }
        if self.command_history_popup.is_some() {
            self.handle_command_history_key(key);
            return Ok(());
        }
        if self.branch_picker.is_some() {
            self.handle_branch_picker_key(key);
            return Ok(());
        }
        if self.input_prompt.is_some() {
            self.handle_input_prompt_key(key);
            return Ok(());
        }
        if self.list_picker.is_some() {
            self.handle_list_picker_key(key);
            return Ok(());
        }
        if self.pending_replace_all.is_some() {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.confirm_pending_replace_all();
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.cancel_pending_replace_all();
                }
                _ => {}
            }
            return Ok(());
        }
        if self.pending_discard_all {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.confirm_pending_discard_all();
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.cancel_pending_discard_all();
                }
                _ => {}
            }
            return Ok(());
        }
        if self.pending_broadcast_enable {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.confirm_pending_broadcast();
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.cancel_pending_broadcast();
                }
                _ => {}
            }
            return Ok(());
        }
        if self.pending_run_block.is_some() {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.confirm_pending_run_block();
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.cancel_pending_run_block();
                }
                _ => {}
            }
            return Ok(());
        }
        // History scrubber (#371): arrows step, Home returns to the working
        // tree, Esc closes.
        //
        // BELOW every modal guard above, deliberately. The scrubber is a view
        // of the editor, not a mode over the window, so a palette, prompt or
        // picker opened while scrubbing keeps its own arrows. Placing it here
        // gets that by construction — each of those guards returns
        // unconditionally, so a key only reaches this line when none of them
        // wanted it. The alternative, a list of "overlays that take
        // precedence", silently rots the next time someone adds a modal.
        if self.scrubber.is_some()
            && matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
            && self.handle_scrubber_key(key.code)
        {
            return Ok(());
        }
        if self.scm_menu.open && matches!(key.code, KeyCode::Esc) {
            self.scm_menu.close();
            return Ok(());
        }
        // Macro recording (#255) taps the key here: every modal above has
        // already returned, so what reaches this point is editor work — the
        // thing a macro is for. Capturing keys rather than resolved commands
        // is deliberate: only palette selections and user-rebound chords
        // reach `run_command`, while the built-in defaults (Cmd+S, Alt+Up,
        // the debugger keys) call their app methods straight from here, so a
        // command-level recorder would miss most of what a user does.
        //
        // Replay feeds keys back through `handle_key`, so it is re-entrant by
        // construction — `replaying` keeps a replayed key from being recorded
        // into the macro that is producing it.
        // User keybindings (keybindings.json) win over the built-in chords, but
        // only when the terminal is not focused (its raw control keys must pass
        // through) and the chord carries a real modifier or is a function key
        // (so plain typing and bare Enter/Tab/Esc keep their contextual meaning).
        // This stands in for VS Code's `when: editorTextFocus` without a full
        // context engine.
        if self.focus != Pane::Terminal
            && !self.keymap.is_empty()
            && is_rebindable_chord(key)
            && let Some(cmd) = self.keymap.command_for(key)
        {
            self.run_command(cmd);
            return Ok(());
        }
        // A focused comment-box reply field owns the keyboard: typing edits
        // the draft, Enter sends, Esc leaves, F4 hops on. Sits below the
        // real modals (palette, prompts) and above every editor key.
        if self.editor.comment_focus.is_some() && self.focus == Pane::Editor {
            self.handle_comment_focus_key(key);
            return Ok(());
        }
        if matches!(key.code, KeyCode::F(1)) {
            self.open_shortcuts_modal();
            return Ok(());
        }
        if matches!(key.code, KeyCode::F(8)) {
            self.perf.toggle();
            return Ok(());
        }
        // Debugger chords (VS Code defaults). F5 start/continue, Shift+F5 stop,
        // Shift+Cmd+F5 restart, Ctrl+F5 attach to a Python process, F9 toggle
        // breakpoint, F10 step over, F11/Shift+F11 step in/out. Cmd is SUPER on
        // macOS, Ctrl on Linux/Termux.
        //
        // A bare F5/F9/F10/F11 pressed while the terminal pane is focused and
        // no debug session is live belongs to the app running in the shell
        // (process-compose's F10 Quit, htop's F9 kill), so it falls through to
        // the PTY instead of dying as a debugger no-op. Modified chords and a
        // ready update's F9 re-exec keep their croft meaning everywhere.
        let terminal_owns_fkeys = self.focus == Pane::Terminal
            && matches!(self.bottom_panel_tab, BottomPanelTab::Terminal)
            && self.dap_session.is_none()
            && key.modifiers.is_empty();
        if matches!(key.code, KeyCode::F(5)) && !terminal_owns_fkeys {
            let shift = key.modifiers.contains(KeyModifiers::SHIFT);
            let cmd = key.modifiers.contains(KeyModifiers::SUPER)
                || key.modifiers.contains(KeyModifiers::CONTROL);
            if shift && cmd {
                self.debug_restart();
            } else if key.modifiers.contains(KeyModifiers::CONTROL)
                && !shift
                && !key.modifiers.contains(KeyModifiers::SUPER)
                && !key.modifiers.contains(KeyModifiers::ALT)
            {
                self.open_attach_python_picker();
            } else if shift {
                self.debug_stop();
            } else {
                self.debug_start_or_continue();
            }
            return Ok(());
        }
        // F6 pauses a running program (VS Code's Pause key) ONLY while a debug
        // session is live; with no session it falls through to its long-standing
        // role as croft's cycle-focus key.
        if matches!(key.code, KeyCode::F(6)) && self.dap_session.is_some() {
            self.debug_pause();
            return Ok(());
        }
        if matches!(key.code, KeyCode::F(9)) && !(terminal_owns_fkeys && !self.f9_update_armed()) {
            if key.modifiers.contains(KeyModifiers::SHIFT)
                && key.modifiers.contains(KeyModifiers::ALT)
            {
                // Shift+Alt+F9: add or edit a logpoint at the cursor. Must
                // precede the bare-Shift arm, which also matches this chord.
                self.debug_edit_logpoint();
            } else if key.modifiers.contains(KeyModifiers::SHIFT) {
                // Shift+F9: add or edit a conditional breakpoint at the cursor.
                self.debug_edit_condition();
            } else if key.modifiers.contains(KeyModifiers::ALT) {
                // Alt+F9: toggle break-on-raised-exceptions.
                self.debug_toggle_raised_exceptions();
            } else if self.any_update_ready() {
                // A background update has landed (a staged release, the
                // drift rebuild, or a remote install): bare F9 re-execs
                // into it. `run()` swaps the staged binary in first when
                // that is the one that landed.
                self.pending_reexec = true;
                self.quit = true;
            } else if self.f9_update_armed() && self.update_status == UpdateStatus::Idle {
                // The drift hint is armed (#242): bare F9 rebuilds and
                // reinstalls the local croft in the background.
                self.start_local_reinstall();
            } else if self.self_install.is_some() {
                // A rebuild is already in flight (second F9 of an input
                // batch, or pressed again mid-install): swallow it -
                // toggling a breakpoint here is never what was meant.
            } else {
                self.debug_toggle_breakpoint();
            }
            return Ok(());
        }
        if matches!(key.code, KeyCode::F(10)) && !terminal_owns_fkeys {
            self.debug_step("next");
            return Ok(());
        }
        if matches!(key.code, KeyCode::F(11)) && !terminal_owns_fkeys {
            let cmd = if key.modifiers.contains(KeyModifiers::SHIFT) {
                "stepOut"
            } else {
                "stepIn"
            };
            self.debug_step(cmd);
            return Ok(());
        }
        // Arm the `Cmd+K` leader (VS Code's two-key chord prefix). The next
        // keystroke is interpreted by `handle_cmd_k_chord`, checked at the top
        // of this fn. Cmd is SUPER everywhere; Ctrl doubles as Cmd only on
        // Termux — on desktop Linux a bare Ctrl+K stays the editor's
        // kill-to-end-of-line (see `is_cmd_k_leader_key`).
        if is_cmd_k_leader_key(key) {
            self.cmd_k_leader = Some(std::time::Instant::now());
            return Ok(());
        }
        if is_file_finder_key(key) {
            self.open_file_finder();
            return Ok(());
        }
        if is_command_palette_key(key) {
            self.open_command_palette();
            return Ok(());
        }
        if is_go_to_symbol_key(key) {
            self.open_go_to_symbol();
            return Ok(());
        }
        // Modal layer: prompt eats every key while it's open.
        if self.prompt.is_some() {
            self.handle_prompt_key(key);
            return Ok(());
        }
        // Modal layer: local-browser confirmation eats every key.
        if self.pending_local_open.is_some() {
            self.handle_local_open_confirm_key(key);
            return Ok(());
        }
        // Modal layer: discard-changes confirmation eats every key. Y/Enter
        // discards; N/Esc cancels. Anything else is swallowed so the user
        // can't accidentally type-through into the editor below.
        if self.pending_discard.is_some() {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.confirm_pending_discard();
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.cancel_pending_discard();
                }
                _ => {}
            }
            return Ok(());
        }
        // Modal layer: revert-hunk confirmation, same contract as the
        // discard modal above.
        if self.pending_revert_hunk.is_some() {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                    self.confirm_pending_revert_hunk();
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.cancel_pending_revert_hunk();
                }
                _ => {}
            }
            return Ok(());
        }
        // Modal layer: open context menu eats keyboard navigation.
        if self.context_menu.is_some() {
            self.handle_menu_key(key);
            return Ok(());
        }
        // Cmd+E toggles native modal (vim) editing. Global (above the focus
        // dispatch) so it works from any pane and even with no file open: the
        // mode is a single app-wide flag that only affects the editor, but it
        // can be pre-armed from the tree or terminal and stays on as you open
        // and switch between files.
        if is_vim_toggle_key(key) {
            self.toggle_vim_mode();
            return Ok(());
        }
        // App-wide shortcuts (priority). Skip Cmd+S when the Source
        // Control pane is focused so the SC handler can use it as the
        // stage shortcut — saving an editor file with no editor focus
        // doesn't make sense anyway, and globally swallowing Cmd+S here
        // is what made the user's first attempt feel inert.
        let sc_focused =
            self.focus == Pane::Tree && self.sidebar_view == SidebarView::SourceControl;
        if is_save_key(key) && !sc_focused {
            self.save();
            return Ok(());
        }
        if is_terminal_toggle_key(key) {
            self.toggle_terminal();
            return Ok(());
        }
        if is_terminal_maximize_key(key) {
            self.toggle_terminal_maximize();
            return Ok(());
        }
        if is_editor_split_key(key) {
            self.split_editor();
            return Ok(());
        }
        if is_focus_group_left_key(key) {
            self.focus_editor_group(true);
            return Ok(());
        }
        if is_focus_group_right_key(key) {
            self.focus_editor_group(false);
            return Ok(());
        }
        if is_terminal_split_key(key) {
            match self.split_terminal() {
                Ok(()) => {
                    self.terminal_status(format!(
                        "Split terminal: {} active",
                        self.terminals.len()
                    ));
                }
                Err(e) => {
                    self.status = format!("Split terminal failed: {e}");
                }
            }
            return Ok(());
        }
        if is_terminal_focus_key(key) {
            if !self.show_terminal {
                self.show_terminal = true;
            }
            self.focus_pane(Pane::Terminal);
            return Ok(());
        }
        if is_run_build_task_key(key) {
            self.run_build_task();
            return Ok(());
        }
        // Explorer-pane shortcuts get first refusal so Cmd+Shift+F creates
        // a folder when the user is browsing the tree, rather than always
        // jumping to Search. Outside Explorer the global Search-jump wins.
        if self.is_explorer_focused() && self.handle_explorer_shortcut(key) {
            return Ok(());
        }
        if is_search_jump_key(key) {
            // Jumping to global Search supersedes the in-file find: tear the
            // local find bar down first, otherwise its overlay keeps painting
            // over the editor (render_editor_find only gates on editor_find
            // being Some, not on focus) and shadows the global search input.
            self.close_editor_find();
            self.set_sidebar_view(SidebarView::Search);
            return Ok(());
        }
        // Cmd+Shift+S jumps to Source Control from any pane — croft's Source
        // Control gesture. There is no editor Save-As to collide with (Cmd+S
        // alone saves), so it fires even while the editor is focused.
        if is_source_control_jump_key(key) {
            self.set_sidebar_view(SidebarView::SourceControl);
            return Ok(());
        }
        if is_explorer_jump_key(key) {
            self.show_tree = true;
            self.set_sidebar_view(SidebarView::Explorer);
            return Ok(());
        }
        if is_run_debug_jump_key(key) {
            self.show_tree = true;
            self.set_sidebar_view(SidebarView::RunDebug);
            return Ok(());
        }
        if is_remote_jump_key(key) {
            self.show_tree = true;
            self.set_sidebar_view(SidebarView::Remote);
            return Ok(());
        }
        if is_extensions_jump_key(key) {
            self.show_tree = true;
            self.set_sidebar_view(SidebarView::Extensions);
            return Ok(());
        }
        if self.is_remote && is_drop_to_local_key(key) {
            self.drop_to_local = true;
            self.quit = true;
            return Ok(());
        }
        if self.sidebar_view == SidebarView::Search
            && self.focus == Pane::Tree
            && is_search_editing_shortcut(key)
        {
            self.handle_search_key(key);
            return Ok(());
        }
        if is_secondary_sidebar_toggle_key(key) {
            self.toggle_secondary_side_bar();
            return Ok(());
        }
        if is_minimap_toggle_key(key) {
            self.toggle_minimap();
            return Ok(());
        }
        // Ctrl+B while the terminal pane is focused belongs to the app in
        // the shell, not to croft (#304). Claude Code backgrounds a running
        // command with it and has no other route to that; croft's sidebar
        // toggle has three (Cmd+B, the palette, the menu). The asymmetry is
        // the argument: releasing costs a chord that is reachable three
        // other ways, holding costs a chord that is reachable no other way.
        //
        // Same conditional shape as the bare F5/F9/F10/F11 rule above, and
        // for the same reason -- it is a rule about when the chord is
        // UNAMBIGUOUS, not a user preference, so it needs no setting and
        // cannot drift out of step with a config. Cmd+B is untouched
        // everywhere, which is what keeps the sidebar reachable from the
        // terminal; only the Ctrl form is released, matching iTerm2 and
        // Ghostty, which reserve Cmd and pass Ctrl through.
        let terminal_owns_ctrl_b = self.focus == Pane::Terminal
            && matches!(self.bottom_panel_tab, BottomPanelTab::Terminal)
            && key.modifiers == KeyModifiers::CONTROL;
        if is_sidebar_toggle_key(key) && !terminal_owns_ctrl_b {
            self.toggle_side_bar();
            return Ok(());
        }
        match (key.code, key.modifiers) {
            (KeyCode::Char('q'), KeyModifiers::CONTROL) => {
                self.quit = true;
                return Ok(());
            }
            (KeyCode::F(6), _) => {
                self.cycle_focus();
                return Ok(());
            }
            _ => {}
        }

        match self.focus {
            Pane::Tree => match self.sidebar_view {
                SidebarView::Explorer => self.handle_tree_key(key),
                SidebarView::Search => self.handle_search_key(key),
                SidebarView::SourceControl => self.handle_source_control_key(key),
                SidebarView::Remote => self.handle_remote_key(key),
                SidebarView::RunDebug => self.handle_run_debug_key(key),
                SidebarView::Extensions => self.handle_extensions_key(key),
                SidebarView::Testing => self.handle_testing_key(key),
            },
            Pane::Editor => {
                // A shared file is read-only until its bootstrap snapshot
                // lands (a keystroke now would race the owner's canonical
                // text). One gate at the dispatch covers every editor edit
                // path; the window is the bootstrap round-trip.
                if let Some(session) = self.collab.as_ref()
                    && let Some(file) = self
                        .editor
                        .path
                        .as_ref()
                        .and_then(|p| collab_file_key(&self.tree.root, p))
                {
                    if session.is_bootstrapping(&file) {
                        self.status = format!("{file}: joining the shared session, one moment");
                        return Ok(());
                    }
                    // Same gate for a not-yet-attached pane of a LIVE file
                    // (a fresh split or reopen holding stale disk text): a
                    // keystroke absorbed now would be silently wiped when
                    // the attach pass seeds the pane one tick later.
                    if session.is_live(&file) && self.editor.collab_doc_gen == 0 {
                        self.status = format!("{file}: syncing this pane, one moment");
                        return Ok(());
                    }
                }
                self.handle_editor_key(key);
                self.poke_cursor();
            }
            Pane::Terminal => match self.bottom_panel_tab {
                // The PROBLEMS / OUTPUT views own the panel pane while their tab
                // is active, so keystrokes scroll the list instead of leaking
                // into the hidden shell.
                BottomPanelTab::Problems => self.handle_problems_key(key),
                BottomPanelTab::Output => self.handle_output_key(key),
                BottomPanelTab::Ports => self.handle_ports_key(key),
                BottomPanelTab::Captures => self.handle_captures_key(key),
                BottomPanelTab::Terminal => self.handle_terminal_key(key),
            },
        }
        Ok(())
    }

    fn handle_search_key(&mut self, key: KeyEvent) {
        use crate::widgets::search::SearchField;
        // Reset the blink so the caret is solidly visible right after any key,
        // matching the commit box; the panel is focused whenever this fires.
        self.poke_cursor();
        if is_search_paste_key(key) {
            let text = (self.clipboard_reader)();
            self.paste_clipboard_into_search(text.as_deref());
            return;
        }
        if is_editor_select_all_key(key) {
            self.search.select_all_active();
            return;
        }
        if is_editor_copy_key(key) {
            let text = self.search.active_selection_text();
            if !text.is_empty() {
                copy_to_clipboard(&text);
                self.status = format!("Copied {} chars to clipboard", text.chars().count());
            }
            return;
        }
        if is_editor_cut_key(key) {
            let text = self.search.active_selection_text();
            if !text.is_empty() {
                copy_to_clipboard(&text);
                let n = text.chars().count();
                self.search.backspace();
                self.refresh_search_if_filtering();
                self.status = format!("Cut {n} chars to clipboard");
            }
            return;
        }
        // Tab cycles through the visible inputs (Query → Replace → include →
        // exclude → Query), mirroring VS Code. Shift+Tab is left to fall
        // through to default since BackTab arrives as its own key code.
        if key.code == KeyCode::Tab && key.modifiers.is_empty() {
            self.search.focus_next_field();
            return;
        }
        match key.code {
            KeyCode::Esc => {
                if self.search.active_text().is_empty() {
                    if self.search.field == SearchField::Query {
                        self.set_sidebar_view(SidebarView::Explorer);
                    } else {
                        self.search.focus_field(SearchField::Query);
                    }
                } else {
                    let was_query = self.search.field == SearchField::Query;
                    self.search.active_text_mut_clear();
                    self.search.clear_active_selection();
                    if was_query {
                        self.search.hits.clear();
                    }
                    self.refresh_search_if_filtering();
                }
            }
            KeyCode::Enter => {
                // On the Replace field, Enter runs Replace All across the
                // current results; elsewhere it opens the selected hit.
                if self.search.field == SearchField::Replace {
                    self.run_search_replace_all();
                } else if let Some(hit) = self.search.selected_hit().cloned() {
                    self.open_search_hit(&hit);
                }
            }
            KeyCode::Backspace if self.search.backspace() => {
                self.refresh_search_if_filtering();
            }
            KeyCode::Up => self.search.move_up(),
            KeyCode::Down => self.search.move_down(),
            KeyCode::Char(c) => {
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !key.modifiers.contains(KeyModifiers::SUPER)
                {
                    self.search.type_char(c);
                    self.refresh_search_if_filtering();
                } else if key.modifiers.contains(KeyModifiers::SUPER) {
                    self.status = format!("Search: unhandled Cmd+{c}");
                } else if key.modifiers.contains(KeyModifiers::CONTROL) {
                    self.status = format!("Search: unhandled Ctrl+{c}");
                }
            }
            _ => {}
        }
    }

    /// Re-run the search after a field edit, but only when the edited field
    /// actually affects the result set. Editing the Replace text changes
    /// nothing about which files match, so it must not clear / re-scan.
    fn refresh_search_if_filtering(&mut self) {
        if self.search.field != crate::widgets::search::SearchField::Replace {
            self.submit_search_query();
        }
    }

    /// Replace every match in the current results with the Replace text, then
    /// re-run the query so the (now stale) hit list refreshes.
    fn run_search_replace_all(&mut self) {
        if self.is_collab_guest() {
            // Replace All writes hit files on disk directly; in a collab
            // session only the owner writes (their croft offers the same
            // action, and open shared files converge through the reload
            // diff).
            self.status = String::from("Replace All is owner-only in a shared session");
            return;
        }
        if self.search.query.trim().is_empty() {
            self.status = String::from("Replace All: enter a search term first");
            return;
        }
        if !self.search.complete {
            // Hits stream in batches; replacing before Done would silently
            // miss files found after confirmation (#124 review).
            self.status =
                String::from("Replace All: search still running — retry when it finishes");
            return;
        }
        // Count first, write only after the modal confirms: a workspace-wide
        // disk rewrite is exactly what the confirm-destructive rule is for
        // (#123 — Enter used to commit instantly). Dirty-open files are
        // excluded from the count too: the confirmed action skips them, and
        // counting them made the modal overpromise.
        let dirty = self.dirty_open_paths();
        let (occurrences, files) = self.search.count_replacements(&dirty);
        let skipped = self
            .search
            .hits
            .iter()
            .map(|h| &h.path)
            .filter(|p| dirty.contains(*p))
            .collect::<std::collections::HashSet<_>>()
            .len();
        if occurrences == 0 && skipped == 0 {
            self.status = String::from("Replace All: nothing to replace");
            return;
        }
        self.pending_replace_all = Some((occurrences, files, skipped));
    }

    /// Every path open with unsaved edits, across the active group and all
    /// inactive split leaves.
    fn dirty_open_paths(&self) -> std::collections::HashSet<PathBuf> {
        self.editor
            .editors
            .iter()
            .chain(
                self.editor_layout
                    .inactive_leaf_tabs()
                    .into_iter()
                    .flat_map(|tabs| tabs.editors.iter()),
            )
            .filter(|e| e.dirty)
            .filter_map(|e| e.path.clone())
            .collect()
    }

    /// The confirmed Replace All: writes every hit file EXCEPT ones open
    /// with unsaved edits — a disk write under a dirty buffer forces that
    /// tab into conflict divergence, so those are skipped and named.
    fn confirm_pending_replace_all(&mut self) {
        self.pending_replace_all = None;
        let dirty = self.dirty_open_paths();
        let (n, skipped) = self.search.replace_all_skipping(&dirty);
        self.status = if skipped.is_empty() {
            format!("Replace All: replaced {n} occurrence(s)")
        } else {
            let names: Vec<String> = skipped
                .iter()
                .take(2)
                .map(|p| self.status_path(p))
                .collect();
            let more = skipped.len().saturating_sub(names.len());
            let list = if more > 0 {
                format!("{} and {more} more", names.join(", "))
            } else {
                names.join(", ")
            };
            format!(
                "Replace All: replaced {n} occurrence(s); skipped {list} (unsaved changes — save first)"
            )
        };
        self.submit_search_query();
    }

    fn cancel_pending_replace_all(&mut self) {
        self.pending_replace_all = None;
        self.status = String::from("Replace All cancelled");
    }

    fn handle_remote_key(&mut self, key: KeyEvent) {
        let has_mod = key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
        match key.code {
            KeyCode::Up => self.remote.move_up(),
            KeyCode::Down => self.remote.move_down(),
            KeyCode::PageUp => self.remote.scroll_up(10),
            KeyCode::PageDown => self.remote.scroll_down(10),
            KeyCode::Backspace if !self.remote.filter.is_empty() => {
                self.remote.pop_filter_char();
            }
            KeyCode::Char(' ') if has_mod => {}
            KeyCode::Char(c) if !has_mod => {
                self.remote.push_filter_char(c);
            }
            KeyCode::Enter => {
                if let Some(target) = self.remote.selected_target().cloned() {
                    self.request_remote_launch(target.alias, None);
                }
            }
            KeyCode::Esc if !self.remote.clear_filter() => {
                self.set_sidebar_view(SidebarView::Explorer);
            }
            _ => {}
        }
    }

    fn handle_source_control_key(&mut self, key: KeyEvent) {
        if matches!(key.code, KeyCode::Esc) {
            self.set_sidebar_view(SidebarView::Explorer);
            return;
        }
        let cmd_or_ctrl = key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL);
        // Ctrl+Enter: commit & push. We deliberately match ONLY Control
        // here (not Super). iTerm2's default keymap binds Cmd+Enter to
        // "Toggle Fullscreen" and never delivers the chord to the TUI,
        // which made the original Cmd+Enter wiring feel inert; Ctrl is
        // unintercepted across every terminal we target.
        if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Enter) {
            self.commit_and_push_source_control();
            return;
        }
        // Cmd+A: select every entry row in the panel so a follow-up Cmd+S
        // stages them all in one go. Distinct from the editor's Cmd+A
        // (select-all text) which the user kept hitting in the SC pane
        // and getting the wrong scope.
        if cmd_or_ctrl && matches!(key.code, KeyCode::Char('a') | KeyCode::Char('A')) {
            let n = self.source_control.select_all_changes();
            self.status = format!("Selected {n} change(s)");
            return;
        }
        // Cmd+S: stage the selected entry, or every entry in the
        // multi-selection. Mirrors clicking the inline "+" icon but
        // sweeps across the whole selection.
        if cmd_or_ctrl && matches!(key.code, KeyCode::Char('s') | KeyCode::Char('S')) {
            self.stage_selected_source_control_entries();
            return;
        }
        if is_clipboard_paste_key(key) {
            if let Some(text) = (self.clipboard_reader)() {
                self.source_control.insert_str(&text);
                self.poke_cursor();
            }
            return;
        }
        match key.code {
            KeyCode::Backspace => {
                self.source_control.backspace();
                self.poke_cursor();
            }
            KeyCode::Delete => {
                self.source_control.delete_char();
                self.poke_cursor();
            }
            KeyCode::Left => {
                self.source_control.move_cursor_left();
                self.poke_cursor();
            }
            KeyCode::Right => {
                self.source_control.move_cursor_right();
                self.poke_cursor();
            }
            KeyCode::Home => {
                self.source_control.home();
                self.poke_cursor();
            }
            KeyCode::End => {
                self.source_control.end();
                self.poke_cursor();
            }
            KeyCode::Up => self.source_control.scroll_up(1),
            KeyCode::Down => self.source_control.scroll_down(1),
            KeyCode::Enter => self.commit_source_control(),
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !key.modifiers.contains(KeyModifiers::SUPER) =>
            {
                self.source_control.insert_char(c);
                self.poke_cursor();
            }
            _ => {}
        }
    }

    fn refresh_source_control(&mut self) {
        // Non-blocking: post a StatusAndChanges request and let the worker
        // reply via `git_response_rx`. The panel paints immediately from
        // whatever entries the last drain installed (typically <400 ms
        // old via the FS-watcher tick); the fresh state lands within one or
        // two frames after the click. StatusAndChanges (not just Changes) so
        // the branch sync counts (`↑1` / `↓N`) and dirty flag refresh too —
        // a commit changes those without changing the file list. Still off
        // the UI thread, so no synchronous `git status` stall.
        let ws = self.active_scm_root.clone();
        self.git_worker_for_root_mut(&ws)
            .request_status_and_changes();
        self.refresh_commit_graph();
    }

    /// Refetch the COMMITS graph off-thread: `git log --topo-order` plus the
    /// pure lane layout both run on the fetch thread, and the finished rows
    /// land in [`graph_rx`] tagged with the root they describe. The inflight
    /// latch collapses a burst of triggers into one shell-out plus one
    /// queued refetch: a trigger during flight is answering a question the
    /// in-flight fetch predates (a Make Root, a newer HEAD), so it must
    /// re-fire when the reply drains rather than be dropped — a root change
    /// racing the fetch otherwise left the panel on "Loading" until HEAD
    /// next moved.
    fn refresh_commit_graph(&mut self) {
        if self.graph_fetch_inflight {
            self.graph_refetch_queued = true;
            return;
        }
        self.graph_fetch_inflight = true;
        // The COMMITS section follows the active repo (#149).
        let root = self.active_scm_root.clone();
        let revspec = self.graph_revspec.clone();
        let tx = self.graph_tx.clone();
        std::thread::spawn(move || {
            let commits = match revspec.as_deref() {
                Some(spec) => crate::git::branch_history_range(&root, spec, 400),
                None => crate::git::commit_graph(&root, 400),
            };
            let rows = crate::widgets::commit_graph::layout_graph(commits);
            let _ = tx.send((root, revspec, rows));
        });
    }

    /// Open a commit's full patch (header, message, diffstat, diff) in a
    /// read-only scratch tab — the graph's click-through, tig's enter key.
    fn open_commit_patch(&mut self, hash: &str, short_hash: &str) {
        match crate::git::show_commit(&self.scm_root(), hash) {
            Ok(text) => {
                let label = format!("commit {short_hash}");
                match self.editor.open_text_buffer(Path::new(&label), &text) {
                    Ok(()) => {
                        self.focus_pane(Pane::Editor);
                        self.sync_open_file_poll_mtime();
                        self.status = format!("Opened commit {short_hash}");
                    }
                    Err(e) => self.status = format!("Open commit failed: {e}"),
                }
            }
            Err(e) => self.status = format!("Show commit failed: {e}"),
        }
    }

    fn handle_extensions_key(&mut self, key: KeyEvent) {
        let has_mod = key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
        // Keep the filter caret solid right after a key, like the commit box.
        self.poke_cursor();
        match key.code {
            KeyCode::Up => self.extensions.move_up(),
            KeyCode::Down => self.extensions.move_down(),
            KeyCode::PageUp => self.extensions.scroll_up(10),
            KeyCode::PageDown => self.extensions.scroll_down(10),
            // Space / Enter flip the selected extension's toggle switch. Space is
            // reserved for the toggle (per the panel's design), so the filter box
            // takes every other printable character but never a space.
            KeyCode::Char(' ') if !has_mod => self.toggle_selected_extension(),
            KeyCode::Enter => self.toggle_selected_extension(),
            // Delete uninstalls the selected installed extension (distinct from
            // Backspace, which edits the filter). Reaches the app on both iTerm2
            // and Ghostty as a plain key, so no chord forwarder is needed.
            KeyCode::Delete => self.uninstall_selected_extension(),
            KeyCode::Backspace if !self.extensions.filter_is_empty() => {
                self.extensions.pop_filter_char()
            }
            KeyCode::Char(c) if !has_mod => self.extensions.push_filter_char(c),
            // Esc clears an active filter first; a second Esc leaves the view.
            KeyCode::Esc if !self.extensions.clear_filter() => {
                self.set_sidebar_view(SidebarView::Explorer)
            }
            _ => {}
        }
    }

    /// Flip the enabled state of the Extensions panel's selected row: update the
    /// in-memory disabled set, persist it, rebuild the list (so the row's state
    /// label and dim styling refresh), and apply any immediate feature gating
    /// (e.g. closing a now-disabled viewer). LSP extensions only re-evaluate on
    /// the next launch; the others gate live.
    fn toggle_selected_extension(&mut self) {
        let Some(id) = self.extensions.selected_id().map(str::to_string) else {
            return;
        };
        // A FROM VS CODE row with nothing to install is an answer, not a
        // control: say what croft has for it and stop.
        if let Some(item) = self.extensions.selected_item()
            && item.vscode
            && item.install.is_none()
        {
            self.status = format!("{}: {}", item.id, item.description);
            return;
        }
        // AVAILABLE catalog rows: the toggle "adds" (installs) rather than
        // enables. Materialize the manifest into the user extensions dir, then
        // refresh so it moves into INSTALLED (enabled by default). A FROM VS
        // CODE row installs its croft equivalent, not its own (VS Code) id.
        if self.extensions.selected_available() {
            let id = self
                .extensions
                .selected_install_target()
                .map(str::to_string)
                .unwrap_or(id);
            match crate::mcp::catalog::install(&id) {
                Ok(_) => {
                    self.refresh_extensions();
                    self.status = format!(
                        "Added '{id}' — invoke it from the Command Palette (its server installs on first use)"
                    );
                }
                Err(e) => self.status = format!("Could not add '{id}': {e}"),
            }
            return;
        }
        let now_enabled = self.disabled_extensions.contains(&id);
        if now_enabled {
            self.disabled_extensions.remove(&id);
        } else {
            self.disabled_extensions.insert(id.clone());
        }
        let _ =
            crate::prefs::save_disabled_extensions_in(&self.config_dir, &self.disabled_extensions);
        self.refresh_extensions();
        self.status = format!(
            "{} extension '{id}'",
            if now_enabled { "Enabled" } else { "Disabled" }
        );
    }

    /// Uninstall the selected INSTALLED extension: delete its manifest from the
    /// user extensions dir so it drops back to AVAILABLE on refresh. Restricted
    /// to catalog-sourced ids — croft only removes what it added, never a
    /// hand-dropped user manifest (which it can only disable). Reversible by
    /// re-adding from the catalog with one keystroke, so no confirmation modal.
    fn uninstall_selected_extension(&mut self) {
        if !self.extensions.selected_removable() {
            return;
        }
        let Some(id) = self.extensions.selected_id().map(str::to_string) else {
            return;
        };
        if !crate::mcp::catalog::is_removable(&id) {
            self.status =
                format!("'{id}' is your own extension — croft won't delete it; disable it instead");
            return;
        }
        // Confirm before removing: uninstall is destructive and must never fire
        // from a single Delete keypress (or trash click) without asking. Enter in
        // the popup performs it; Esc keeps the extension. (Seed a sentinel value
        // so Enter on the empty field still submits — submit_value() ignores blanks.)
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        self.open_input_prompt(
            InputPrompt::new(
                InputPurpose::ExtensionUninstall { id: id.clone() },
                format!("Uninstall '{id}'?  It returns to Available."),
                "Enter to uninstall · Esc to keep",
            )
            .with_value("uninstall"),
        );
    }

    /// Perform the confirmed uninstall (the popup's Enter path). Removes the
    /// catalog/index-installed manifest and refreshes the panel.
    fn perform_extension_uninstall(&mut self, id: &str) {
        match crate::mcp::catalog::uninstall_in(&self.config_dir.join("extensions"), id) {
            Ok(()) => {
                // Drop any stale disabled-state for the removed id so a later
                // re-add starts enabled, matching a fresh install.
                if self.disabled_extensions.remove(id) {
                    let _ = crate::prefs::save_disabled_extensions_in(
                        &self.config_dir,
                        &self.disabled_extensions,
                    );
                }
                // And its consent: a re-add is a program the user has not
                // approved this time, so the first-run gate asks again.
                self.forget_extension_consent(id);
                self.refresh_extensions();
                self.status = format!("Uninstalled '{id}' — it's back under AVAILABLE to re-add");
            }
            Err(e) => self.status = format!("Could not uninstall '{id}': {e}"),
        }
    }

    /// Write a first-run consent for `ext_id` to prefs, after the caller has
    /// put it in the session set both gates read. The session grant holds
    /// either way; a prefs write that fails is said in the status rather
    /// than swallowed, since the user would otherwise be asked again next
    /// launch with no idea why.
    fn persist_extension_consent(&mut self, ext_id: &str) {
        if let Err(e) = crate::prefs::save_mcp_consent_in(&self.config_dir, ext_id) {
            self.status = format!("Allowed {ext_id}, but the consent could not be saved: {e}");
        }
    }

    /// Forget `id`'s first-run consent in the session set and in prefs.
    fn forget_extension_consent(&mut self, id: &str) {
        self.consented_extensions.remove(id);
        let _ = crate::prefs::forget_mcp_consent_in(&self.config_dir, id);
    }

    /// Whether the extension `id` is currently enabled (not in the disabled set).
    /// The single gate the bundled features consult before activating.
    fn is_extension_enabled(&self, id: &str) -> bool {
        !self.disabled_extensions.contains(id)
    }

    fn handle_run_debug_key(&mut self, key: KeyEvent) {
        // While a session is live the panel is a REPL: text edits the prompt and
        // Enter evaluates it. Esc always leaves the view.
        if self.run_debug.debug_active {
            match key.code {
                KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
                KeyCode::Enter => {
                    self.debug_repl_submit();
                    self.refresh_debug_panel();
                }
                KeyCode::Backspace => {
                    self.run_debug.repl_input.pop();
                }
                KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                    self.run_debug.repl_input.push(c);
                }
                _ => {}
            }
            return;
        }
        match key.code {
            KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
            KeyCode::Enter => self.run_debug_button_action(),
            _ => {}
        }
    }

    /// Testing view keys: Enter runs all tests, `r` re-discovers, arrows scroll
    /// the tree, Esc returns to the Explorer (mirrors the Run-and-Debug view).
    fn handle_testing_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
            KeyCode::Enter => self.run_all_tests(),
            KeyCode::Char('r' | 'R') => self.discover_tests(),
            KeyCode::Up => self.testing.scroll_up(1),
            KeyCode::Down => self.testing.scroll_down(1),
            _ => {}
        }
    }

    /// Whether an enabled runner extension claims this workspace. When none
    /// does — no recognised project, or its runner toggled off in the
    /// Extensions panel — every run gesture must refuse here: the worker's
    /// fallback used to shell `cargo test` regardless, so a disabled Rust
    /// runner still ran (and rebuilt) the workspace, and a disabled Python
    /// runner ran cargo in a directory with no Cargo.toml.
    fn testing_runner_available(&mut self) -> bool {
        if crate::testing::worker::runner_for(&self.active_test_root).is_some() {
            return true;
        }
        self.status = String::from(crate::testing::NO_RUNNER_STATUS);
        false
    }

    /// Rebind the Testing stack to `root` — the focused file's workspace
    /// folder (#151). Exactly the re-root rebind: the worker's epoch drops
    /// in-flight results for the old root, the panel resets (its tree
    /// described another project), a pending debug build is dropped, and
    /// the front-of-view panel re-discovers immediately.
    fn rebind_test_root(&mut self, root: PathBuf) {
        self.active_test_root = root.clone();
        self.test_worker.set_root(root);
        self.testing.reset();
        // The build this armed for is being dropped (#373).
        self.disarm_failure_breakpoint();
        self.pending_test_debug = None;
        if self.sidebar_view == SidebarView::Testing {
            self.discover_tests();
        }
    }

    /// Kick off a full test run on the worker (no-op if a run/discovery is
    /// already in flight) and reveal the Testing view so results stream in.
    fn run_all_tests(&mut self) {
        if self.testing.is_busy() || !self.testing_runner_available() {
            return;
        }
        self.test_worker.run_all();
        self.set_sidebar_view(SidebarView::Testing);
    }

    /// Run a single test by exact name (click-to-run from the tree). Marks just
    /// that case Running and keeps the rest of the discovered list intact.
    fn run_test(&mut self, name: String) {
        if self.testing.is_busy() || !self.testing_runner_available() {
            return;
        }
        self.testing.start_single(&name);
        self.test_worker.run_one(name);
        self.set_sidebar_view(SidebarView::Testing);
    }

    /// Jump the editor to a test's `fn` definition (Cmd/Opt+click in the tree).
    /// `--list` carries no location, so we grep the source for the function —
    /// a whole-workspace walk, so it runs on a background thread and the jump
    /// lands via the drain in [`Self::sync_explorer_panels`].
    fn jump_to_test_source(&mut self, name: String) {
        let root = self.active_test_root.clone();
        let tx = self.test_jump_tx.clone();
        self.status = format!("Locating test {name}");
        std::thread::spawn(move || {
            let hit = crate::testing::locate::find_test_source(&root, &name);
            let _ = tx.send((root, name, hit));
        });
    }

    /// Run every test in a suite (click on its header in the tree). cargo's
    /// filter and the panel's marking are substring matches, so the pattern is
    /// anchored (`parse::`) to keep `parse` from sweeping `parse_utils::b`.
    fn run_suite(&mut self, suite: String) {
        if self.testing.is_busy() || !self.testing_runner_available() {
            return;
        }
        self.testing
            .start_filter(&crate::testing::suite_pattern(&suite));
        self.test_worker.run_suite(suite);
        self.set_sidebar_view(SidebarView::Testing);
    }

    /// Run the test the editor caret sits in (Cmd+K Enter / palette). Finds the
    /// enclosing `fn` and runs it by name; results stream into the
    /// Testing view like any other run.
    fn run_test_at_cursor(&mut self) {
        let Some(name) =
            crate::testing::locate::enclosing_fn_name(&self.editor.lines, self.editor.cursor_row)
        else {
            self.status = String::from("Run Test at Cursor: no function at the caret");
            return;
        };
        self.run_named_test(name);
    }

    /// Start the test `name` through the worker and reveal the Testing view —
    /// the shared tail of run-at-cursor and the editor's gutter play glyph.
    /// A leaf unique in the discovered tree resolves to its full name for an
    /// exact run; otherwise cargo's substring filter is the best available.
    fn run_named_test(&mut self, name: String) {
        if self.testing.is_busy() || !self.testing_runner_available() {
            return;
        }
        let (run, exact) = match self.testing.sole_case_with_leaf(&name) {
            Some(full) => (full, true),
            None => (name, false),
        };
        if exact {
            self.testing.start_single(&run);
            self.test_worker.run_one(run.clone());
        } else {
            self.testing.start_filter(&run);
            self.test_worker.run_filter(run.clone());
        }
        self.set_sidebar_view(SidebarView::Testing);
        self.status = format!("Running test {run}");
    }

    /// Debug the test the editor caret sits in (Cmd+K Shift+Enter, palette).
    fn debug_test_at_cursor(&mut self) {
        let Some(name) =
            crate::testing::locate::enclosing_fn_name(&self.editor.lines, self.editor.cursor_row)
        else {
            self.status = String::from("Debug Test at Cursor: no function at the caret");
            return;
        };
        self.debug_named_test(name);
    }

    /// Hand the test `name` to the debugger — the M6 wedge: pytest runs as a
    /// debugpy module launch under the PROJECT's interpreter, a cargo test
    /// binary launches under lldb-dap with the name as its libtest filter.
    /// Shared by debug-at-cursor and Alt+click on the gutter play glyph.
    fn debug_named_test(&mut self, name: String) {
        use std::collections::BTreeMap;
        if self.dap_session.is_some() {
            self.status = String::from("A debug session is already running (Shift+F5 stops it)");
            return;
        }
        let root = self.tree.root.clone();
        // #373: if the last run of this test failed and named a place in
        // the user's own code, break there — the whole point of "debug this
        // test" is landing on the assertion without being asked to find it
        // first. Set BEFORE the launch set is collected so it travels with
        // the user's own breakpoints, and recorded so it can be taken back
        // out when the session ends.
        self.arm_failure_breakpoint(&name, &root);
        let breakpoints: BTreeMap<PathBuf, Vec<crate::dap::session::SourceBreakpoint>> = self
            .editor
            .breakpoints
            .iter()
            .map(|(p, lines)| (p.clone(), self.editor.source_breakpoints(p, lines)))
            .collect();
        match crate::testing::worker::runner_for(&root) {
            Some(crate::testing::worker::Runner::Pytest) => {
                let adapter_py = match crate::dap::install::ensure_debug_venv() {
                    Ok(py) => py,
                    Err(e) => {
                        self.debug_error(format!("Debugger setup failed: {e}"));
                        return;
                    }
                };
                let project_py = project_python(&root);
                let request =
                    crate::dap::session::pytest_debug_launch_request(&project_py, &root, &name);
                let adapter_args = vec![String::from("-m"), String::from("debugpy.adapter")];
                match crate::dap::session::DapSession::launch_with(
                    &adapter_py.to_string_lossy(),
                    &adapter_args,
                    &root,
                    request,
                    breakpoints,
                ) {
                    Ok(session) => {
                        self.dap_session = Some(session);
                        self.run_debug.feedback = Some(format!("Debugging test {name}"));
                        self.run_debug.feedback_is_error = false;
                        self.status = self.with_failure_note(format!(
                            "Debugging test {name} — F5 continue · F10 step over · Shift+F5 stop"
                        ));
                        self.reveal_debug_view();
                    }
                    Err(e) => self.debug_error(format!("Failed to start debugger: {e}")),
                }
            }
            Some(crate::testing::worker::Runner::Cargo) => {
                if lldb_dap_path().is_none() {
                    self.debug_error(lldb_dap_missing_message());
                    return;
                }
                // The file the gesture happened in narrows the harness: a
                // lib test and an integration test can share a bare fn name.
                let source = self.editor.path.clone();
                self.start_test_binary_build(root, name, source);
            }
            Some(crate::testing::worker::Runner::Vitest | crate::testing::worker::Runner::Jest) => {
                // No session will start, so the armed breakpoint has nothing
                // to be cleaned up by (#373).
                self.disarm_failure_breakpoint();
                self.status =
                    String::from("Debugging JS tests is not wired yet — the play glyph runs them");
            }
            None => {
                self.disarm_failure_breakpoint();
                self.status = String::from("No test runner detected in this workspace");
            }
        }
    }

    /// Kick off `cargo test --no-run` on a background thread and remember the
    /// receiver: a cold build takes minutes, and running it on the UI thread
    /// froze every pane — no keys, no redraw, no PTY pumping — while the
    /// "Building…" status could never even paint before the launch overwrote
    /// it. The drain launches the debugger when the binary arrives.
    fn start_test_binary_build(&mut self, root: PathBuf, name: String, source: Option<PathBuf>) {
        if self.pending_test_debug.is_some() {
            // The launch this armed for is not happening (#373).
            self.disarm_failure_breakpoint();
            self.status = String::from("A test binary is already building");
            return;
        }
        self.status = self.with_failure_note(format!("Building test binary for {name}"));
        let (tx, rx) = std::sync::mpsc::channel();
        {
            let name = name.clone();
            let root = root.clone();
            std::thread::spawn(move || {
                let _ = tx.send(
                    crate::testing::worker::build_test_binary(&root, &name, source.as_deref())
                        .map_err(|e| e.to_string()),
                );
            });
        }
        self.pending_test_debug = Some((rx, name, root));
    }

    /// Drain the background test-binary build: on success launch lldb-dap
    /// (with the editor's breakpoints as they are NOW — the user may have set
    /// more while the build ran), on failure surface the error. Returns true
    /// when anything landed, for the redraw aggregate.
    fn drain_pending_test_debug(&mut self) -> bool {
        use std::sync::mpsc::TryRecvError;
        let Some((rx, _, _)) = self.pending_test_debug.as_ref() else {
            return false;
        };
        let result = match rx.try_recv() {
            Ok(r) => r,
            Err(TryRecvError::Empty) => return false,
            Err(TryRecvError::Disconnected) => Err(String::from("the build thread died")),
        };
        let (_, name, build_root) = self.pending_test_debug.take().expect("checked above");
        // Re-rooting the Explorer mid-build would otherwise launch the old
        // workspace's binary with the new workspace's cwd and breakpoints.
        if build_root != self.tree.root {
            // No launch, so nothing will clean up after it (#373).
            self.disarm_failure_breakpoint();
            self.status = format!(
                "Test binary for {name} finished, but the workspace changed — debug it again from its workspace"
            );
            return true;
        }
        match result {
            Ok(binary) => self.launch_lldb_test_debug(&binary, &name),
            Err(e) => self.debug_error(format!("Test build failed: {e}")),
        }
        true
    }

    /// The launch tail of debug-a-cargo-test, run from the drain once the
    /// background build hands over the binary.
    fn launch_lldb_test_debug(&mut self, binary: &Path, name: &str) {
        use std::collections::BTreeMap;
        if self.dap_session.is_some() {
            // The build took minutes and the user started another session
            // meanwhile: this launch is abandoned, so the breakpoint it
            // armed has nothing to clean up after it (#373).
            self.disarm_failure_breakpoint();
            self.status = String::from("A debug session is already running (Shift+F5 stops it)");
            return;
        }
        let Some(adapter) = lldb_dap_path() else {
            self.debug_error(lldb_dap_missing_message());
            return;
        };
        let root = self.tree.root.clone();
        let breakpoints: BTreeMap<PathBuf, Vec<crate::dap::session::SourceBreakpoint>> = self
            .editor
            .breakpoints
            .iter()
            .map(|(p, lines)| (p.clone(), self.editor.source_breakpoints(p, lines)))
            .collect();
        // The bare name is libtest's substring filter (run-at-cursor has no
        // full module path); --nocapture keeps output visible.
        let args = vec![name.to_string(), String::from("--nocapture")];
        let request = crate::dap::session::lldb_test_launch_request(binary, &args);
        match crate::dap::session::DapSession::launch_with(
            &adapter,
            &[],
            &root,
            request,
            breakpoints,
        ) {
            Ok(session) => {
                self.dap_session = Some(session);
                self.run_debug.feedback = Some(format!("Debugging test {name} (lldb)"));
                self.run_debug.feedback_is_error = false;
                self.status = self.with_failure_note(format!(
                    "Debugging test {name} via lldb-dap — F5 continue · Shift+F5 stop"
                ));
                self.reveal_debug_view();
            }
            Err(e) => self.debug_error(format!("Failed to start lldb-dap: {e}")),
        }
    }

    /// List tests without running them (populate the tree). No-op while busy or
    /// outside a recognised test project (Cargo or pytest) — the tool would
    /// error with no manifest, and `cargo test -- --list` compiles the test
    /// binary so we never auto-fire it per-keystroke.
    fn discover_tests(&mut self) {
        if self.testing.is_busy()
            || crate::testing::worker::runner_for(&self.active_test_root).is_none()
        {
            return;
        }
        self.test_worker.discover();
    }

    /// Reveal the Testing view (the user-open gesture: activity icon, Cmd+K B,
    /// palette). Auto-discovers once when the tree is still empty so it
    /// populates like VS Code, without recompiling on every subsequent open.
    fn open_testing_view(&mut self) {
        self.show_tree = true;
        self.set_sidebar_view(SidebarView::Testing);
        if self.testing.is_empty() {
            self.discover_tests();
        }
    }

    fn refresh_run_debug(&mut self) {
        let path = self.editor.path.clone();
        // Decide the button: scripts and executables are "Run" (terminal);
        // compiled source (no script runner, but a debug adapter) is "Debug"
        // (build + lldb). Files that are neither (e.g. `.git/config`) get no
        // button. run_spec_for already covers executables (the +x bit), so a
        // compiled binary is "Run" — run it directly.
        let (runnable, is_debug) = match path.as_deref() {
            Some(p) => {
                let ext = p
                    .extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("")
                    .to_ascii_lowercase();
                if Self::run_spec_for(
                    p,
                    self.roots
                        .owning_root(p)
                        .unwrap_or_else(|| self.roots.primary()),
                )
                .is_some()
                {
                    (true, false)
                } else if crate::dap::registry::adapter_for_extension(&ext).is_some() {
                    (true, true)
                } else {
                    (false, false)
                }
            }
            None => (false, false),
        };
        self.run_debug.runnable = runnable;
        self.run_debug.run_is_debug = is_debug;
        self.run_debug.set_active_file(path);
        self.run_debug.feedback = None;
        self.run_debug.feedback_is_error = false;
        // The launch.json config row (#250): count + F5 selection. Discovery
        // re-reads the same two small files once per helper — four reads — and
        // this only runs on active-file changes.
        // Compounds count too — the row is the documented route to the picker,
        // and the picker lists them, so counting only configurations makes the
        // row vanish for a compounds-only workspace and undercount otherwise.
        //
        // A HIDDEN compound is not listed (#318), so it must not be counted
        // either: the row and the picker have to agree, or a workspace whose
        // only entry is hidden advertises "1 debug entry" over a picker that
        // offers nothing. Same filter as `open_debug_config_picker`.
        let root = self.active_workspace_root();
        // The same filter the picker applies, so the badge and the picker
        // cannot disagree: a `presentation.hidden` entry of EITHER kind is
        // absent from both (#318).
        self.run_debug.config_count = crate::dap::configs::discover_configs(&root)
            .iter()
            .filter(|c| !c.hidden())
            .count()
            + crate::dap::configs::discover_compounds(&root)
                .iter()
                .filter(|c| !c.hidden())
                .count();
        self.run_debug.selected_config = self.selected_debug_config.clone();
    }

    /// Resolve how to run `file`: which command line to feed the PTY and
    /// which directory the PTY should `chdir` to. Returns `None` for
    /// extensions we don't know how to run.
    ///
    /// For Python files the resolver walks from the file's directory up to
    /// (and including) `workspace_root`, picking the first `.venv/bin/python`,
    /// `venv/bin/python`, or `.env/bin/python` it finds. The cwd is set to
    /// the directory that owns the venv so relative imports, `.env` reads,
    /// and any path-relative work the script does line up with how the user
    /// would run it from their own shell. With no venv anywhere on the
    /// path the resolver falls back to the system `python3` and the file's
    /// own directory.
    fn run_spec_for(file: &Path, workspace_root: &Path) -> Option<RunSpec> {
        let ext = file
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        let file_str = file.to_string_lossy().into_owned();
        let file_dir = file.parent().unwrap_or(Path::new(".")).to_path_buf();
        if matches!(ext.as_str(), "py" | "pyi" | "pyw") {
            if let Some((py, venv_dir)) = find_python_venv(&file_dir, workspace_root) {
                return Some(RunSpec {
                    program: py.to_string_lossy().into_owned(),
                    args: vec![file_str],
                    cwd: venv_dir,
                });
            }
            return Some(RunSpec {
                program: String::from("python3"),
                args: vec![file_str],
                cwd: file_dir,
            });
        }
        let runner: &str = match ext.as_str() {
            "js" | "mjs" | "cjs" => "node",
            "ts" | "tsx" => "tsx",
            "rb" => "ruby",
            "lua" => "lua",
            "php" => "php",
            "pl" => "perl",
            "sh" | "bash" => "bash",
            "zsh" => "zsh",
            "fish" => "fish",
            _ => {
                // No known script runner. If the file is itself an executable
                // (a compiled binary, usually extensionless), run it directly.
                if is_executable_file(file) {
                    return Some(RunSpec {
                        program: file_str,
                        args: vec![],
                        cwd: file_dir,
                    });
                }
                return None;
            }
        };
        Some(RunSpec {
            program: String::from(runner),
            args: vec![file_str],
            cwd: file_dir,
        })
    }

    /// Spawn a fresh PTY at the resolved working directory, seed it with the
    /// runner command for the active editor tab's file, and focus the
    /// terminal pane so the user sees output immediately.
    /// Drain the debug session each frame. Returns true if anything changed
    /// (so the frame loop redraws). Mirrors the paused location into the
    /// editor's stop-line, surfaces program output + stop reasons, and tears
    /// the session down when the debuggee exits.
    pub fn poll_dap(&mut self) -> bool {
        use crate::dap::session::{DapEvent, SessionPhase};
        if self.dap_session.is_none() {
            return false;
        }
        let events = self
            .dap_session
            .as_mut()
            .map(|s| s.poll())
            .unwrap_or_default();
        let mut changed = !events.is_empty();
        for ev in events {
            match ev {
                // Route program output to the debug console (each embedded
                // newline becomes its own line), but drop debugpy's own
                // `telemetry` banner (the `ptvsd` / `debugpy` noise).
                DapEvent::Output { category, text }
                    if crate::dap::session::output_is_user_visible(&category) =>
                {
                    for line in text.split('\n') {
                        if !line.is_empty() {
                            self.debug_console_push(line.to_string());
                        }
                    }
                }
                // REPL submissions echo "❯ expr" then the result; watch/hover
                // results are consumed elsewhere.
                DapEvent::Evaluated {
                    context,
                    expression,
                    result,
                    ..
                } if context == "repl" => {
                    self.debug_console_push(format!("❯ {expression}"));
                    self.debug_console_push(result);
                }
                DapEvent::Evaluated {
                    context,
                    expression,
                    result,
                    success,
                } if context == "watch" => {
                    self.watch_vals.insert(expression, (result, success));
                }
                // Fresh stack + frame selection just landed: this is the
                // moment each watch expression re-evaluates against the new
                // top frame (#112).
                DapEvent::InspectionUpdated => {
                    self.refresh_watches();
                    self.refresh_inline_values();
                    changed = true;
                }
                DapEvent::Stopped { reason, .. } => {
                    self.run_debug.feedback = Some(format!("Paused ({reason})"));
                    self.run_debug.feedback_is_error = false;
                    self.watch_baseline_pending = true;
                }
                DapEvent::BreakpointsUpdated => {
                    // Mirror the adapter's unverified set into the editor so the
                    // gutter can hollow out inert breakpoints, and warn once if
                    // any failed to bind (the "I set a breakpoint and it just
                    // ran" case).
                    let unverified: std::collections::HashMap<
                        PathBuf,
                        std::collections::BTreeSet<usize>,
                    > = self
                        .dap_session
                        .as_ref()
                        .map(|s| s.unverified_breakpoints.clone().into_iter().collect())
                        .unwrap_or_default();
                    let total: usize = unverified.values().map(|s| s.len()).sum();
                    self.editor.unverified_breakpoints = unverified;
                    if total > 0 {
                        self.status = format!(
                            "{total} breakpoint(s) could not bind (no executable code on that line)"
                        );
                    }
                }
                _ => {}
            }
        }
        let phase = self.dap_session.as_ref().map(|s| s.phase);
        match phase {
            Some(SessionPhase::Stopped) => {
                self.debug_ever_stopped = true;
                let loc = self
                    .dap_session
                    .as_ref()
                    .and_then(|s| s.current_location.clone());
                if let Some(loc) = loc
                    && self.editor.stop_line.as_ref() != Some(&loc)
                {
                    self.editor.stop_line = Some(loc);
                    // A re-stop at the same location can re-arm the arrow
                    // without a fresh InspectionUpdated on this tick; rebuild
                    // the trailers here too so arrow and values never split
                    // (#136 review). Idempotent over already-fetched data.
                    self.refresh_inline_values();
                    changed = true;
                }
            }
            Some(SessionPhase::Terminated) => {
                self.editor.stop_line = None;
                self.editor.unverified_breakpoints.clear();
                // A session that ends on its own must take croft's own
                // breakpoint with it, exactly as Shift+F5 does (#373):
                // this is the path a passing test takes, so it is the
                // common one, not the exceptional one.
                self.disarm_failure_breakpoint();
                self.reset_watch_runtime();
                self.clear_inline_values();
                // Reply to the adapter's own `terminated`/`exited` with the
                // graceful `disconnect` handshake before dropping it. js-debug
                // only retires its detached watchdog on this handshake, never on
                // a SIGKILL of the server, so the natural-exit path used to leak
                // the watchdog by dropping straight to a kill.
                if let Some(session) = self.dap_session.as_mut() {
                    session.disconnect();
                }
                self.dap_session = None;
                // The watchdog reparents to init the moment the server dies;
                // sweep it (and any tree a crashed prior croft left behind)
                // after a short grace so it has settled into the orphan state.
                crate::dap::reaper::reap_orphaned_js_debug_async(std::time::Duration::from_millis(
                    REAPER_TEARDOWN_GRACE_MS,
                ));
                let had_breakpoints = !self.editor.breakpoints.is_empty();
                self.run_debug.feedback =
                    Some(debug_end_message(had_breakpoints, self.debug_ever_stopped).to_string());
                self.run_debug.feedback_is_error = false;
                // Keep `debug_console` so its output stays visible after the run;
                // the panel renders it until the next session starts.
                self.run_debug.session_ended = true;
                changed = true;
            }
            _ => {
                if self.editor.stop_line.take().is_some() {
                    // The trailers clear wherever the stop arrow clears
                    // (#136 review): this arm catches every phase change the
                    // four explicit resume sites don't, guarded the same way
                    // so ordinary Running ticks pay nothing.
                    self.clear_inline_values();
                    changed = true;
                }
            }
        }
        // Rebuild the Call Stack / Variables panel from the (now-updated) session.
        self.refresh_debug_panel();
        changed
    }

    /// Rebuild the Run & Debug panel's paused-state tree from the session, or
    /// deactivate it when not paused. Cheap; called after each `poll_dap`.
    fn refresh_debug_panel(&mut self) {
        let (active, status, rows) = self.build_debug_view();
        self.run_debug.debug_active = active;
        if active {
            self.run_debug.debug_status = status;
            self.run_debug.debug_rows = rows;
            let max_scroll = self.run_debug.debug_rows.len().saturating_sub(1);
            if self.run_debug.debug_scroll > max_scroll {
                self.run_debug.debug_scroll = max_scroll;
            }
            // Show the console tail (most recent output / REPL lines).
            let n = self.debug_console.len();
            self.run_debug.console_tail = self.debug_console[n.saturating_sub(50)..].to_vec();
        } else {
            self.run_debug.debug_rows.clear();
            self.run_debug.debug_scroll = 0;
            self.run_debug.repl_input.clear();
            // Retain the just-ended session's console output until the next run;
            // otherwise the idle Run panel shows nothing.
            if self.run_debug.session_ended && !self.debug_console.is_empty() {
                let n = self.debug_console.len();
                self.run_debug.console_tail = self.debug_console[n.saturating_sub(50)..].to_vec();
            } else {
                self.run_debug.console_tail.clear();
            }
        }
    }

    /// Build the (active, status, rows) tuple for the debug panel from the
    /// session. `&self` so it can borrow the session and expansion set without
    /// conflicting with the `&mut self` assignment in `refresh_debug_panel`.
    fn build_debug_view(&self) -> (bool, String, Vec<crate::widgets::run_debug::DebugRow>) {
        use crate::dap::session::SessionPhase;
        use crate::widgets::run_debug::{DebugRow, DebugRowKind};
        let Some(session) = self.dap_session.as_ref() else {
            return (false, String::new(), Vec::new());
        };
        // Active for any live session: while Running the tree is empty but the
        // console still shows output; while Stopped the full tree is built.
        if session.phase == SessionPhase::Terminated {
            return (false, String::new(), Vec::new());
        }
        if session.phase != SessionPhase::Stopped {
            let status = self
                .run_debug
                .feedback
                .clone()
                .unwrap_or_else(|| String::from("Running"));
            return (true, status, Vec::new());
        }
        let mut rows = Vec::new();
        rows.push(DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("CALL STACK"),
            },
        });
        for f in &session.stack_frames {
            let loc = f
                .path
                .as_ref()
                .and_then(|p| p.file_name())
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            rows.push(DebugRow {
                indent: 1,
                kind: DebugRowKind::Frame {
                    id: f.id,
                    selected: Some(f.id) == session.selected_frame,
                    name: f.name.clone(),
                    location: format!("{loc}:{}", f.line),
                },
            });
        }
        rows.push(DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("VARIABLES"),
            },
        });
        for scope in &session.scopes {
            rows.push(DebugRow {
                indent: 1,
                kind: DebugRowKind::Scope {
                    name: scope.name.clone(),
                },
            });
            if let Some(vars) = session.variables.get(&scope.variables_ref) {
                push_variable_rows(&mut rows, session, &self.debug_expanded, vars, 2);
            }
        }
        rows.push(DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("WATCH"),
            },
        });
        for (widx, expr) in self.watch_exprs.iter().enumerate() {
            let (value, available, pending) = match self.watch_vals.get(expr) {
                Some((v, ok)) => (v.clone(), *ok, false),
                None => (String::new(), true, true),
            };
            let changed = available
                && !pending
                && self.watch_prev.get(expr).is_some_and(|prev| prev != &value);
            rows.push(DebugRow {
                indent: 1,
                kind: DebugRowKind::Watch {
                    index: widx,
                    expression: expr.clone(),
                    value,
                    available,
                    changed,
                    pending,
                },
            });
        }
        rows.push(DebugRow {
            indent: 1,
            kind: DebugRowKind::WatchAdd,
        });
        let status = self
            .run_debug
            .feedback
            .clone()
            .unwrap_or_else(|| String::from("Paused"));
        (true, status, rows)
    }

    /// Re-evaluate every watch expression against the current stop. The
    /// current values become the previous stop's baseline first, so the
    /// changed-value highlight compares stop-to-stop (#112).
    fn refresh_watches(&mut self) {
        if self.watch_exprs.is_empty() {
            return;
        }
        if std::mem::take(&mut self.watch_baseline_pending) {
            self.watch_prev = self
                .watch_vals
                .drain()
                .filter(|(_, (_, ok))| *ok)
                .map(|(k, (v, _))| (k, v))
                .collect();
        }
        if let Some(session) = self
            .dap_session
            .as_mut()
            .filter(|s| s.phase == crate::dap::session::SessionPhase::Stopped)
        {
            for expr in &self.watch_exprs {
                session.evaluate(expr, "watch");
            }
        }
    }

    /// Append a watch expression (palette or the panel's add row) and
    /// evaluate it immediately when a session is paused.
    fn add_watch_expression(&mut self, expr: String) {
        let expr = expr.trim().to_string();
        if expr.is_empty() {
            self.status = String::from("Enter an expression to watch");
            return;
        }
        if self.watch_exprs.contains(&expr) {
            self.status = format!("Already watching {expr}");
            return;
        }
        self.watch_exprs.push(expr.clone());
        if let Some(session) = self
            .dap_session
            .as_mut()
            .filter(|s| s.phase == crate::dap::session::SessionPhase::Stopped)
        {
            session.evaluate(&expr, "watch");
        }
        self.status = format!("Watching {expr}");
    }

    fn remove_watch_expression(&mut self, idx: usize) {
        if idx < self.watch_exprs.len() {
            let expr = self.watch_exprs.remove(idx);
            self.watch_vals.remove(&expr);
            self.watch_prev.remove(&expr);
            self.status = format!("Stopped watching {expr}");
        }
    }

    /// Append a line to the debug console, capping the backlog so a chatty
    /// program can't grow it without bound.
    fn debug_console_push(&mut self, line: String) {
        const CAP: usize = 1000;
        self.debug_console.push(line);
        if self.debug_console.len() > CAP {
            let overflow = self.debug_console.len() - CAP;
            self.debug_console.drain(..overflow);
        }
    }

    /// Submit the Run & Debug panel's REPL input: echo + evaluate it at the
    /// selected frame. No-op on empty input or with no session.
    fn debug_repl_submit(&mut self) {
        let expr = self.run_debug.repl_input.trim().to_string();
        self.run_debug.repl_input.clear();
        if expr.is_empty() {
            return;
        }
        match self.dap_session.as_mut() {
            Some(session) => session.evaluate(&expr, "repl"),
            None => self.debug_console_push(String::from("(no debug session)")),
        }
    }

    /// Hover-to-evaluate: while a debug session is paused, return a popup string
    /// for the identifier at `(line, c)` if it's a loaded local/global, else
    /// None (so the normal LSP hover proceeds).
    fn debug_hover_value(&self, line: usize, c: usize) -> Option<String> {
        use crate::dap::session::SessionPhase;
        let session = self.dap_session.as_ref()?;
        if session.phase != SessionPhase::Stopped {
            return None;
        }
        let word = self.editor.word_string_at(line, c)?;
        let var = session.lookup_local(&word)?;
        let ty = if var.type_name.is_empty() {
            String::new()
        } else {
            format!(": {}", var.type_name)
        };
        Some(format!("{} = {}{ty}", var.name, var.value))
    }

    /// Act on a click of debug-panel row `idx`: select a call-stack frame (load
    /// its scopes/variables) or toggle an expandable variable open/closed.
    fn debug_panel_click(&mut self, idx: usize) {
        use crate::widgets::run_debug::DebugRowKind;
        let Some(row) = self.run_debug.debug_rows.get(idx) else {
            return;
        };
        match row.kind.clone() {
            DebugRowKind::Frame { id, .. } => {
                if let Some(session) = self.dap_session.as_mut() {
                    session.load_frame(id);
                }
                // Collapse expansions: variable refs are frame-scoped.
                self.debug_expanded.clear();
            }
            DebugRowKind::Variable {
                reference,
                expandable: true,
                ..
            } => {
                if self.debug_expanded.contains(&reference) {
                    self.debug_expanded.remove(&reference);
                } else {
                    self.debug_expanded.insert(reference);
                    if let Some(session) = self.dap_session.as_mut() {
                        session.expand_variable(reference);
                    }
                }
            }
            DebugRowKind::WatchAdd => {
                self.open_add_watch_prompt();
            }
            _ => {}
        }
        self.refresh_debug_panel();
    }

    /// Cmd+F on a hex tab (#172): a single-line input popup, per croft's
    /// inputs-in-popups rule. Hex byte pairs or literal ASCII.
    fn open_hex_find_prompt(&mut self) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        if self.editor.hex.is_none() {
            return;
        }
        self.open_input_prompt(InputPrompt::new(
            InputPurpose::HexFind,
            "Find in Hex",
            "hex bytes (de ad be ef) or text",
        ));
    }

    /// The "+ Add Expression" affordance (panel row or palette): a single-line
    /// input popup, per croft's inputs-in-popups rule.
    fn open_add_watch_prompt(&mut self) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        self.open_input_prompt(InputPrompt::new(
            InputPurpose::AddWatch,
            "Add Watch Expression",
            "expression",
        ));
    }

    /// The Run/Debug panel button action: debug compiled source (build + lldb),
    /// or run scripts/executables in a terminal — matching the button's verb.
    fn run_debug_button_action(&mut self) {
        if self.run_debug.run_is_debug {
            self.debug_start_or_continue();
        } else {
            self.run_active_file();
        }
    }

    /// Open and focus the Run and Debug view so the call stack, variables,
    /// console, and REPL are visible the instant a session starts (VS Code
    /// reveals its debug view on launch the same way).
    fn reveal_debug_view(&mut self) {
        // A fresh session: drop the previous run's retained console + stop
        // tracking so the "exited without hitting a breakpoint" hint and the
        // console reflect only this run.
        self.debug_console.clear();
        self.debug_ever_stopped = false;
        self.run_debug.session_ended = false;
        self.show_tree = true;
        self.set_sidebar_view(SidebarView::RunDebug);
        self.focus_pane(Pane::Tree);
    }

    /// Surface a debug-start failure on BOTH the styled Run/Debug panel
    /// feedback line AND the always-visible status bar. The panel line only
    /// renders while the Run/Debug sidebar is the active view (`reveal_debug_view`
    /// is reached only on success), so without the status-bar mirror F5 fails
    /// silently whenever the user is looking at any other sidebar — which read
    /// as "F5 does nothing" on a remote with no debug adapter installed.
    fn debug_error(&mut self, msg: String) {
        // A launch that never happened leaves no session to clean up after,
        // so any breakpoint croft armed for it comes out here (#373) —
        // otherwise it survives in the editor as if the user had set it.
        self.disarm_failure_breakpoint();
        self.run_debug.feedback = Some(msg.clone());
        self.run_debug.feedback_is_error = true;
        self.status = msg;
    }

    /// F5: start debugging the active file, or resume if already paused.
    pub fn debug_start_or_continue(&mut self) {
        use crate::dap::session::SessionPhase;
        if let Some(session) = self.dap_session.as_mut() {
            if session.phase == SessionPhase::Stopped {
                session.continue_execution();
                self.editor.stop_line = None;
                self.clear_inline_values();
            }
            return;
        }
        self.start_selected_debug();
    }

    /// Start whatever F5 is pointed at: the selected launch.json
    /// configuration when one is chosen, else the zero-config active file.
    /// Configs are re-read here so an edited launch.json applies on the next
    /// F5 without reopening the picker.
    fn start_selected_debug(&mut self) {
        if let Some(name) = self.selected_debug_config.clone() {
            let root = self.active_workspace_root();
            self.debug_configs = crate::dap::configs::discover_configs(&root);
            if let Some(cfg) = self.debug_configs.iter().find(|c| c.name == name).cloned() {
                self.launch_debug_config(&cfg);
                return;
            }
            // The selection outlived its config (file edited/deleted): fall
            // back to zero-config and say so rather than failing silently.
            self.selected_debug_config = None;
            self.run_debug.selected_config = None;
            self.status = format!(
                "Debug configuration \"{name}\" no longer exists — debugging the active file"
            );
        }
        self.start_debug_session();
    }

    /// Debug: Select and Start Debugging — the launch.json configurations
    /// plus the synthesized zero-config entry.
    pub fn open_debug_config_picker(&mut self) {
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let root = self.active_workspace_root();
        self.debug_configs = crate::dap::configs::discover_configs(&root);
        self.debug_compounds = crate::dap::configs::discover_compounds(&root);
        let mut rows = vec![ListRow {
            id: String::from("active"),
            label: String::from("Debug active file — no configuration"),
        }];
        // Configurations and compounds are ONE list to sort, which is what
        // VS Code does: a config and a compound can name the same
        // `presentation.group`, and sorting them separately would split that
        // group in two no matter what the file asked for (#318).
        //
        // Every id is built BEFORE the sort, from `enumerate` over the full
        // unsorted list, so `compound:{i}` and `{i}` keep naming the same
        // entries however the rows move. Indexing the sorted sequence would
        // launch a different configuration than the row says as soon as any
        // entry declares a `presentation`.
        let entries: Vec<(ListRow, Option<crate::dap::configs::Presentation>)> = self
            .debug_configs
            .iter()
            .enumerate()
            .map(|(i, c)| {
                (
                    ListRow {
                        id: i.to_string(),
                        label: format!("{} — {} · {}", c.name, c.type_name, c.source),
                    },
                    c.presentation.clone(),
                )
            })
            // Compounds are listed so a workspace's own launch.json is
            // reflected honestly. Selecting one LAUNCHES it when it names a
            // single configuration and carries no key croft cannot honour;
            // otherwise it reports what is missing (#310) rather than
            // launching a subset, which would debug something other than what
            // was asked for.
            .chain(self.debug_compounds.iter().enumerate().map(|(i, c)| {
                (
                    ListRow {
                        id: format!("compound:{i}"),
                        label: format!(
                            "{} — compound of {}",
                            c.name,
                            c.configurations.join(", ")
                        ),
                    },
                    c.presentation.clone(),
                )
            }))
            .collect();
        rows.extend(
            crate::dap::configs::visible_and_sorted(entries, |(_, p)| p.as_ref())
                .into_iter()
                .map(|(row, _)| row),
        );
        self.open_list_picker(
            ListPicker::new(ListPurpose::DebugConfig, "Debug Configuration", rows),
            "No debug configurations (.croft/launch.json or .vscode/launch.json)",
        );
    }

    /// Continue a parked launch whose `preLaunchTask` has finished.
    ///
    /// Split from the terminal sweep so it can be driven directly: reaching it
    /// through the sweep needs a pane emitting OSC 133 marks, and the branch
    /// that matters most - a compound's task completing, then its MEMBER
    /// starting (#318) - is invisible to every test that only checks the
    /// launch parked.
    fn resume_pending_launch(&mut self, exit: Option<i32>, step: PendingLaunchStep) {
        if exit != Some(0) {
            let code = exit.map_or_else(|| String::from("?"), |c| c.to_string());
            self.debug_error(format!(
                "preLaunchTask exited {code} — debug launch aborted (its pane has the output)"
            ));
            return;
        }
        match step {
            PendingLaunchStep::Resolved(rc) => self.launch_resolved_config(*rc),
            // Back through the front door: the member may have a
            // `preLaunchTask` of its own, and VS Code runs the compound's AND
            // the member's. Calling the resolved-launch path here would
            // silently skip the member's.
            PendingLaunchStep::Member(cfg) => self.launch_debug_config(&cfg),
        }
    }

    /// Run a COMPOUND's own `preLaunchTask`, then launch its single member
    /// (#318).
    ///
    /// Deliberately not folded into [`Self::launch_debug_config`]: that runs
    /// the *config's* task as the last step before the adapter, while this one
    /// runs before the member is even resolved. Keeping them separate is what
    /// lets both fire for a compound whose member also declares a task, which
    /// is what VS Code does.
    ///
    /// Same failure contract as a config's task, because a user cannot tell
    /// the two apart from the outside: a task the workspace does not declare
    /// is an error rather than a silent skip, and a non-zero exit aborts the
    /// launch instead of debugging whatever the build left behind.
    fn launch_after_compound_task(
        &mut self,
        task_label: &str,
        member: crate::dap::configs::DebugConfig,
    ) {
        if self.dap_session.is_some() {
            self.debug_stop();
        }
        self.pending_debug_launch = None;
        let root = self.active_workspace_root();
        let tasks = crate::tasks::discover_tasks(&root);
        let Some(task) = tasks.into_iter().find(|t| t.label == task_label) else {
            self.debug_error(format!(
                "compound preLaunchTask \"{task_label}\" not found — Tasks: Run Task lists what the workspace declares"
            ));
            return;
        };
        let command = task.command.clone();
        let Some(pane) = self.run_project_task(task) else {
            // run_project_task already reported why the pane failed.
            return;
        };
        self.pending_debug_launch = Some(PendingDebugLaunch {
            pane,
            command,
            step: PendingLaunchStep::Member(Box::new(member)),
            started: std::time::Instant::now(),
        });
        self.run_debug.feedback = Some(format!("compound preLaunchTask \"{task_label}\" running…"));
        self.run_debug.feedback_is_error = false;
        self.status = format!(
            "compound preLaunchTask \"{task_label}\" running — debug starts when it exits 0"
        );
    }

    /// Resolve and launch one launch.json configuration: substitution against
    /// the active editor state, then either straight to the adapter or parked
    /// behind its `preLaunchTask`.
    fn launch_debug_config(&mut self, cfg: &crate::dap::configs::DebugConfig) {
        use crate::dap::configs;
        if self.dap_session.is_some() {
            self.debug_stop();
        }
        self.pending_debug_launch = None;
        let root = self.active_workspace_root();
        let ctx = configs::SubstCtx {
            workspace_folder: root.clone(),
            file: self.editor.path.clone(),
        };
        let rc = match configs::resolve(cfg, &ctx) {
            Ok(rc) => rc,
            Err(e) => {
                self.debug_error(e);
                return;
            }
        };
        if let Some(task_label) = rc.pre_launch_task.clone() {
            let tasks = crate::tasks::discover_tasks(&root);
            let Some(task) = tasks.into_iter().find(|t| t.label == task_label) else {
                self.debug_error(format!(
                    "preLaunchTask \"{task_label}\" not found — Tasks: Run Task lists what the workspace declares"
                ));
                return;
            };
            let command = task.command.clone();
            let Some(pane) = self.run_project_task(task) else {
                // run_project_task already reported why the pane failed.
                return;
            };
            self.pending_debug_launch = Some(PendingDebugLaunch {
                pane,
                command,
                step: PendingLaunchStep::Resolved(Box::new(rc)),
                started: std::time::Instant::now(),
            });
            self.run_debug.feedback = Some(format!("preLaunchTask \"{task_label}\" running…"));
            self.run_debug.feedback_is_error = false;
            self.status =
                format!("preLaunchTask \"{task_label}\" running — debug starts when it exits 0");
            return;
        }
        self.launch_resolved_config(rc);
    }

    /// Where the last run of `name` failed, if the runner named a place in
    /// the user's own code (#373). Read back from the Test Runner output
    /// channel, which already holds every line the run printed.
    ///
    /// Scoped to the failing test's own block: a run of the whole suite
    /// prints many failures, and breaking on another test's assertion would
    /// stop the debugger somewhere the user did not ask about. The block
    /// starts at the runner's "failures:"-style banner for this test and
    /// ends at the next test's banner.
    fn failure_site_of(&self, name: &str) -> Option<crate::testing::failure_site::FailureSite> {
        use crate::testing::failure_site::is_failure_banner;
        let lines = crate::output::snapshot(crate::output::CHANNEL_TESTS)?;
        let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
        // Walk backwards to the most recent BANNER for this test, so a
        // re-run's output wins over an earlier one in the same channel.
        // Anchoring on the banner rather than on any mention is what makes
        // this work against real output: libtest reprints every failing
        // name in its trailing `failures:` summary, so "the last line
        // mentioning the name" lands after every block and finds nothing.
        let start = texts.iter().rposition(|t| is_failure_banner(t, name))?;
        // The block runs to the next test's banner, or to the end.
        let end = texts[start + 1..]
            .iter()
            .position(|t| {
                (t.trim_start().starts_with("---- ")
                    || t.trim_start().starts_with('_')
                    || t.trim_start().starts_with('\u{25cf}'))
                    && !is_failure_banner(t, name)
            })
            .map(|i| start + 1 + i)
            .unwrap_or(texts.len());
        crate::testing::failure_site::failure_site(&texts[start..end].join("\n"))
    }

    /// Set a TEMPORARY breakpoint at the assertion the last run of `name`
    /// failed on (#373), unless the user already has one there.
    ///
    /// Recorded in `debug_temp_breakpoint` so [`Self::disarm_failure_breakpoint`]
    /// can take exactly this one back out: a breakpoint croft set and then
    /// left behind would be indistinguishable from one the user set, and
    /// would keep stopping them on a line they never chose.
    fn arm_failure_breakpoint(&mut self, name: &str, root: &Path) {
        self.disarm_failure_breakpoint();
        let Some((file, line)) = self
            .failure_site_of(name)
            .and_then(|site| site.resolve(root))
        else {
            return;
        };
        let line = line as usize;
        let lines = self.editor.breakpoints.entry(file.clone()).or_default();
        // The user's own breakpoint there is left alone: it is theirs, it
        // outlives the session, and removing it on stop would delete work.
        if !lines.insert(line) {
            return;
        }
        self.debug_temp_breakpoint = Some((file.clone(), line));
        // Recorded for the caller to append to whatever message it shows:
        // setting `status` here would be overwritten moments later by the
        // launch's own ("Building test binary…"), so the user would never
        // learn a breakpoint had been set for them.
        self.debug_temp_note = Some(format!(
            "breaking at {}:{line} where it last failed",
            file.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default()
        ));
    }

    /// Append the armed-breakpoint note to `msg`, if one was armed (#373).
    fn with_failure_note(&self, msg: String) -> String {
        match &self.debug_temp_note {
            Some(note) => format!("{msg} — {note}"),
            None => msg,
        }
    }

    /// Remove the breakpoint [`Self::arm_failure_breakpoint`] set, if it is
    /// still ours. The user may have removed it themselves mid-session, in
    /// which case there is nothing to take back.
    fn disarm_failure_breakpoint(&mut self) {
        self.debug_temp_note = None;
        let Some((file, line)) = self.debug_temp_breakpoint.take() else {
            return;
        };
        if let Some(lines) = self.editor.breakpoints.get_mut(&file) {
            lines.remove(&line);
            if lines.is_empty() {
                self.editor.breakpoints.remove(&file);
            }
        }
    }

    /// The editor's breakpoints in launch shape, shared by every session
    /// starter (zero-config and launch.json alike).
    fn collect_editor_breakpoints(
        &self,
    ) -> std::collections::BTreeMap<PathBuf, Vec<crate::dap::session::SourceBreakpoint>> {
        self.editor
            .breakpoints
            .iter()
            .map(|(p, lines)| (p.clone(), self.editor.source_breakpoints(p, lines)))
            .collect()
    }

    /// Spawn the adapter for a resolved launch.json configuration and hand it
    /// the built launch/attach request.
    fn launch_resolved_config(&mut self, mut rc: crate::dap::configs::ResolvedConfig) {
        use crate::dap::configs::{self, RequestKind};
        use crate::dap::session::AdapterKind;
        let breakpoints = self.collect_editor_breakpoints();
        let cwd = rc
            .cwd
            .clone()
            .unwrap_or_else(|| self.active_workspace_root());
        let name = rc.name.clone();
        let result = match rc.kind {
            AdapterKind::Debugpy => {
                if rc.request == RequestKind::Launch && rc.program.is_none() && rc.module.is_none()
                {
                    self.debug_error(format!(
                        "config \"{name}\": a python launch needs a \"program\" or \"module\""
                    ));
                    return;
                }
                match crate::dap::install::ensure_debug_venv() {
                    Ok(py) => {
                        let adapter_args =
                            vec![String::from("-m"), String::from("debugpy.adapter")];
                        crate::dap::session::DapSession::launch_with(
                            &py.to_string_lossy(),
                            &adapter_args,
                            &cwd,
                            configs::debugpy_request(&rc, &py),
                            breakpoints,
                        )
                    }
                    Err(e) => {
                        self.debug_error(format!("Debugger setup failed: {e}"));
                        return;
                    }
                }
            }
            AdapterKind::LldbDap => {
                let Some(adapter) = lldb_dap_path() else {
                    self.debug_error(lldb_dap_missing_message());
                    return;
                };
                match rc.request {
                    RequestKind::Launch => {
                        let Some(program) = rc.program.as_deref() else {
                            self.debug_error(format!(
                                "config \"{name}\": an lldb launch needs a \"program\" (the built binary)"
                            ));
                            return;
                        };
                        match resolve_lldb_program(program, &cwd) {
                            Ok(resolved) => {
                                rc.program = Some(resolved.to_string_lossy().into_owned())
                            }
                            Err(e) => {
                                self.debug_error(format!("config \"{name}\": {e}"));
                                return;
                            }
                        }
                    }
                    RequestKind::Attach => {
                        if rc.process_id.is_none() {
                            self.debug_error(format!(
                                "config \"{name}\": an lldb attach needs a numeric \"processId\""
                            ));
                            return;
                        }
                    }
                }
                crate::dap::session::DapSession::launch_with(
                    &adapter,
                    &[],
                    &cwd,
                    configs::lldb_request(&rc),
                    breakpoints,
                )
            }
            AdapterKind::JsDebug => {
                if rc.request == RequestKind::Launch && rc.program.is_none() {
                    self.debug_error(format!(
                        "config \"{name}\": a node launch needs a \"program\""
                    ));
                    return;
                }
                if rc.request == RequestKind::Attach && rc.port.is_none() {
                    self.debug_error(format!("config \"{name}\": a node attach needs a \"port\""));
                    return;
                }
                let node = match crate::dap::install::node_program() {
                    Ok(n) => n,
                    Err(e) => {
                        self.debug_error(format!("{e}"));
                        return;
                    }
                };
                let server = match crate::dap::install::ensure_js_debug() {
                    Ok(s) => s,
                    Err(e) => {
                        self.debug_error(format!("Debugger setup failed: {e}"));
                        return;
                    }
                };
                crate::dap::session::DapSession::launch_js_with(
                    &node,
                    &server,
                    &cwd,
                    configs::js_request(&rc),
                    breakpoints,
                )
            }
        };
        match result {
            Ok(session) => {
                self.dap_session = Some(session);
                let verb = match rc.request {
                    RequestKind::Launch => "Debugging",
                    RequestKind::Attach => "Attached:",
                };
                self.run_debug.feedback = Some(format!("{verb} {name}"));
                self.run_debug.feedback_is_error = false;
                self.status =
                    format!("{verb} {name} — F5 continue · F10 step over · Shift+F5 stop");
                self.reveal_debug_view();
            }
            Err(e) => self.debug_error(format!("Failed to start debugger: {e}")),
        }
    }

    /// Launch a debug session for the active file, choosing the adapter by file
    /// type. Python (debugpy) is the verified path; other recognised compiled
    /// languages route to lldb-dap.
    fn start_debug_session(&mut self) {
        use crate::dap::session::AdapterKind;
        let Some(path) = self.editor.path.clone() else {
            self.debug_error(String::from("Open a file to debug"));
            return;
        };
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        match crate::dap::registry::adapter_for_extension(&ext) {
            Some(AdapterKind::Debugpy) => {}
            Some(AdapterKind::LldbDap) => {
                self.start_lldb_debug_session(&path);
                return;
            }
            Some(AdapterKind::JsDebug) => {
                self.start_js_debug_session(&path);
                return;
            }
            None => {
                // An executable binary (e.g. a compiled `target/debug/app`) can
                // be debugged directly by lldb-dap with no build step.
                if is_executable_file(&path) {
                    self.launch_lldb(&path, &path);
                } else if let Some(ext_id) = crate::dap::registry::disabled_extension_for(&ext) {
                    // A debugger exists for this file type but its extension is
                    // turned off — say so rather than claim none exists.
                    self.debug_error(format!(
                        "The {ext_id} debugger extension is disabled — enable it in Extensions"
                    ));
                } else {
                    self.debug_error(format!(
                        "No debugger for .{ext} files (Python, JS/TS, Rust, C/C++ are supported)"
                    ));
                }
                return;
            }
        }
        let py = match crate::dap::install::ensure_debug_venv() {
            Ok(py) => py,
            Err(e) => {
                self.debug_error(format!("Debugger setup failed: {e}"));
                return;
            }
        };
        let breakpoints = self.collect_editor_breakpoints();
        let adapter_args = vec![String::from("-m"), String::from("debugpy.adapter")];
        let py_str = py.to_string_lossy().into_owned();
        let debug_root = self
            .roots
            .owning_root(&path)
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf();
        match crate::dap::session::DapSession::launch(
            &py_str,
            &adapter_args,
            &debug_root,
            &path,
            &py,
            breakpoints,
            false,
        ) {
            Ok(session) => {
                self.dap_session = Some(session);
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default();
                self.run_debug.feedback = Some(format!("Debugging {name}"));
                self.run_debug.feedback_is_error = false;
                self.status =
                    format!("Debugging {name} — F5 continue · F10 step over · Shift+F5 stop");
                self.reveal_debug_view();
            }
            Err(e) => {
                self.debug_error(format!("Failed to start debugger: {e}"));
            }
        }
    }

    /// Launch a vscode-js-debug session for a `.js`/`.ts` file run under Node.
    /// Provisions the js-debug server on first use, then drives the shared DAP
    /// session machinery (which transparently spawns the parent + child
    /// connections js-debug requires). TypeScript binds via source maps.
    fn start_js_debug_session(&mut self, path: &Path) {
        let node = match crate::dap::install::node_program() {
            Ok(n) => n,
            Err(e) => {
                self.debug_error(format!("{e}"));
                return;
            }
        };
        let server = match crate::dap::install::ensure_js_debug() {
            Ok(s) => s,
            Err(e) => {
                self.debug_error(format!("Debugger setup failed: {e}"));
                return;
            }
        };
        let breakpoints = self.collect_editor_breakpoints();
        let debug_root = self
            .roots
            .owning_root(path)
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf();
        match crate::dap::session::DapSession::launch_js(
            &node,
            &server,
            &debug_root,
            path,
            breakpoints,
            false,
        ) {
            Ok(session) => {
                self.dap_session = Some(session);
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default();
                self.run_debug.feedback = Some(format!("Debugging {name}"));
                self.run_debug.feedback_is_error = false;
                self.status =
                    format!("Debugging {name} — F5 continue · F10 step over · Shift+F5 stop");
                self.reveal_debug_view();
            }
            Err(e) => {
                self.debug_error(format!("Failed to start debugger: {e}"));
            }
        }
    }

    /// Launch lldb-dap on a Rust / C / C++ source file: build a debuggable
    /// binary, then drive the same DAP session machinery as Python. The binary
    /// build is the only language-specific step; breakpoints, stepping, call
    /// stack, variables, and the REPL all flow through the shared session.
    ///
    /// Note: lldb-dap requires a permitted `debugserver` (macOS gates this
    /// behind code-signing / `DevToolsSecurity`); where that isn't granted the
    /// process runs without binding breakpoints. croft surfaces the adapter's
    /// own status rather than pretending otherwise.
    fn start_lldb_debug_session(&mut self, path: &Path) {
        if lldb_dap_path().is_none() {
            self.debug_error(lldb_dap_missing_message());
            return;
        }
        // Compiled source: build a debuggable binary first, then debug it.
        let binary = match self.build_debuggable_binary(path) {
            Ok(b) => b,
            Err(e) => {
                self.debug_error(format!("Build for debug failed: {e}"));
                return;
            }
        };
        self.launch_lldb(&binary, path);
    }

    /// Launch lldb-dap on an already-built `binary`, attributing status to
    /// `label_path` (the source for a compiled language, or the binary itself
    /// for a directly-debugged executable). Shared by the compiled-source path
    /// and the executable-binary path so neither duplicates the launch plumbing.
    fn launch_lldb(&mut self, binary: &Path, label_path: &Path) {
        let Some(adapter) = lldb_dap_path() else {
            self.debug_error(lldb_dap_missing_message());
            return;
        };
        let breakpoints = self.collect_editor_breakpoints();
        let cwd = label_path
            .parent()
            .unwrap_or(self.workspace_root())
            .to_path_buf();
        match crate::dap::session::DapSession::launch_with(
            &adapter,
            &[],
            &cwd,
            crate::dap::session::lldb_launch_request(binary, false),
            breakpoints,
        ) {
            Ok(session) => {
                self.dap_session = Some(session);
                let name = label_path
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default();
                self.run_debug.feedback = Some(format!("Debugging {name} (lldb)"));
                self.run_debug.feedback_is_error = false;
                self.status =
                    format!("Debugging {name} via lldb-dap — F5 continue · Shift+F5 stop");
                self.reveal_debug_view();
            }
            Err(e) => {
                self.debug_error(format!("Failed to start lldb-dap: {e}"));
            }
        }
    }

    /// Compile `path` to a debuggable binary (with debug info, no optimisation)
    /// and return the binary path. C via `cc`, C++ via `c++`, Rust via `rustc`
    /// for a single file. The binary lands next to the source as `<stem>.dbg`.
    fn build_debuggable_binary(&self, path: &Path) -> std::io::Result<PathBuf> {
        use std::process::Command;
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        let out = path.with_extension("dbg");
        let (program, args): (&str, Vec<String>) = match ext.as_str() {
            "rs" => (
                "rustc",
                vec![
                    String::from("-g"),
                    String::from("-o"),
                    out.to_string_lossy().into_owned(),
                    path.to_string_lossy().into_owned(),
                ],
            ),
            "c" | "h" | "m" => (
                "cc",
                vec![
                    String::from("-g"),
                    String::from("-O0"),
                    path.to_string_lossy().into_owned(),
                    String::from("-o"),
                    out.to_string_lossy().into_owned(),
                ],
            ),
            _ => (
                "c++",
                vec![
                    String::from("-g"),
                    String::from("-O0"),
                    path.to_string_lossy().into_owned(),
                    String::from("-o"),
                    out.to_string_lossy().into_owned(),
                ],
            ),
        };
        // .output(), never .status(): the compiler must not inherit croft's
        // TTY - a compile error would spray its diagnostics over the UI
        // (same class as the pdftoppm trailer-dictionary spray).
        let cmd_out = Command::new(program).args(&args).output()?;
        if !cmd_out.status.success() {
            let stderr = String::from_utf8_lossy(&cmd_out.stderr);
            return Err(std::io::Error::other(format!(
                "{program} exited with {}: {}",
                cmd_out.status,
                stderr.trim()
            )));
        }
        Ok(out)
    }

    /// F9: toggle a breakpoint on the cursor line, pushing it live if a session
    /// is running.
    pub fn debug_toggle_breakpoint(&mut self) {
        self.debug_toggle_breakpoint_line(self.editor.cursor_row + 1);
    }

    /// Toggle a breakpoint on an explicit 1-based `line`, then push the file's
    /// breakpoints to a live session. Shared by F9 (cursor line) and the gutter
    /// right-click menu (clicked line).
    fn debug_toggle_breakpoint_line(&mut self, line: usize) {
        match self.editor.toggle_breakpoint_line(line) {
            Some((_, line, now_set)) => {
                self.status = if now_set {
                    format!("Breakpoint set at line {line}")
                } else {
                    format!("Breakpoint removed from line {line}")
                };
            }
            None => {
                self.status = String::from("Open a file to set a breakpoint");
                return;
            }
        }
        if let Some(path) = self.editor.path.clone() {
            let specs = self
                .editor
                .breakpoints
                .get(&path)
                .map(|lines| self.editor.source_breakpoints(&path, lines))
                .unwrap_or_default();
            if let Some(session) = self.dap_session.as_mut() {
                session.update_breakpoints(&path, &specs);
            }
        }
    }

    /// Open the breakpoint-condition editor for the cursor line, pre-filled with
    /// any existing condition.
    pub fn debug_edit_condition(&mut self) {
        self.debug_edit_condition_line(self.editor.cursor_row + 1);
    }

    /// Open the breakpoint-condition editor for an explicit 1-based `line` as a
    /// centered popup (`PromptKind::BreakpointCondition`), pre-filled with any
    /// existing condition. Shared by the command-palette entry (cursor line)
    /// and the gutter right-click menu (clicked line). The popup, not the
    /// status line, captures the input; commit lives in [`App::commit_prompt`].
    fn debug_edit_condition_line(&mut self, line: usize) {
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("Open a file to set a conditional breakpoint");
            return;
        };
        let existing = self
            .editor
            .breakpoint_conditions
            .get(&path)
            .and_then(|c| c.get(&line))
            .cloned()
            .unwrap_or_default();
        let label = if existing.is_empty() {
            format!("Add Conditional Breakpoint · line {line}")
        } else {
            format!("Edit Condition · line {line}")
        };
        let target_dir = self.tree.root.clone();
        self.prompt = Some(Prompt {
            label,
            buffer: existing,
            kind: PromptKind::BreakpointCondition { path, line },
            target_dir,
            error: None,
        });
    }

    /// Commit the breakpoint-condition popup: ensure a breakpoint exists on the
    /// line, attach the typed expression (or clear it when blank), and push the
    /// file's breakpoints to a live session.
    fn commit_breakpoint_condition(&mut self, path: PathBuf, line: usize, expr: &str) {
        self.editor
            .breakpoints
            .entry(path.clone())
            .or_default()
            .insert(line);
        let cond = expr.trim();
        if cond.is_empty() {
            if let Some(c) = self.editor.breakpoint_conditions.get_mut(&path) {
                c.remove(&line);
            }
            self.status = format!("Plain breakpoint at line {line}");
        } else {
            self.editor
                .breakpoint_conditions
                .entry(path.clone())
                .or_default()
                .insert(line, cond.to_string());
            self.status = format!("Conditional breakpoint at line {line}");
        }
        let specs = self
            .editor
            .breakpoints
            .get(&path)
            .map(|l| self.editor.source_breakpoints(&path, l))
            .unwrap_or_default();
        if let Some(session) = self.dap_session.as_mut() {
            session.update_breakpoints(&path, &specs);
        }
    }

    /// Open the logpoint editor for the cursor line, pre-filled with any
    /// existing message.
    pub fn debug_edit_logpoint(&mut self) {
        self.debug_edit_logpoint_line(self.editor.cursor_row + 1);
    }

    /// Open the logpoint editor for an explicit 1-based `line` as a centered
    /// popup (`PromptKind::Logpoint`). Shared by the palette entry (cursor
    /// line), Shift+Alt+F9, and the gutter right-click menu (clicked line).
    fn debug_edit_logpoint_line(&mut self, line: usize) {
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("Open a file to set a logpoint");
            return;
        };
        let existing = self
            .editor
            .breakpoint_logs
            .get(&path)
            .and_then(|m| m.get(&line))
            .cloned()
            .unwrap_or_default();
        let label = if existing.is_empty() {
            format!("Add Logpoint · line {line}")
        } else {
            format!("Edit Logpoint · line {line}")
        };
        let target_dir = self.tree.root.clone();
        self.prompt = Some(Prompt {
            label,
            buffer: existing,
            kind: PromptKind::Logpoint { path, line },
            target_dir,
            error: None,
        });
    }

    /// Commit the logpoint popup: ensure a breakpoint exists on the line,
    /// attach the typed message (or clear it when blank), and push the file's
    /// breakpoints to a live session.
    fn commit_logpoint(&mut self, path: PathBuf, line: usize, message: &str) {
        self.editor
            .breakpoints
            .entry(path.clone())
            .or_default()
            .insert(line);
        let msg = message.trim();
        if msg.is_empty() {
            if let Some(m) = self.editor.breakpoint_logs.get_mut(&path) {
                m.remove(&line);
            }
            self.status = format!("Plain breakpoint at line {line}");
        } else {
            self.editor
                .breakpoint_logs
                .entry(path.clone())
                .or_default()
                .insert(line, msg.to_string());
            self.status = format!("Logpoint at line {line}");
        }
        let specs = self
            .editor
            .breakpoints
            .get(&path)
            .map(|l| self.editor.source_breakpoints(&path, l))
            .unwrap_or_default();
        if let Some(session) = self.dap_session.as_mut() {
            session.update_breakpoints(&path, &specs);
        }
    }

    /// F10/F11/Shift+F11: step the paused thread (`next` / `stepIn` / `stepOut`).
    pub fn debug_step(&mut self, command: &str) {
        if let Some(session) = self.dap_session.as_mut() {
            session.step(command);
            self.editor.stop_line = None;
            self.clear_inline_values();
        }
    }

    /// Toggle "break on raised exceptions" for the active session. `uncaught` is
    /// always kept on so unhandled exceptions still pause. No-op without a
    /// session.
    pub fn debug_toggle_raised_exceptions(&mut self) {
        let Some(session) = self.dap_session.as_mut() else {
            self.status = String::from("Start debugging first to set exception breakpoints");
            return;
        };
        let raised = !session.has_exception_filter("raised");
        let mut filters = vec![String::from("uncaught")];
        if raised {
            filters.push(String::from("raised"));
        }
        session.set_exception_filters(filters);
        self.status = if raised {
            String::from("Breaking on raised exceptions (and uncaught)")
        } else {
            String::from("Breaking on uncaught exceptions only")
        };
    }

    /// F6: interrupt a running program so it stops at the current line.
    pub fn debug_pause(&mut self) {
        match self.dap_session.as_mut() {
            Some(session) => {
                session.pause();
                self.status = String::from("Pausing");
            }
            None => self.status = String::from("No debug session to pause"),
        }
    }

    /// Restart: tear down the current session and relaunch the active file with
    /// the same breakpoints.
    pub fn debug_restart(&mut self) {
        if self.dap_session.is_some() {
            self.debug_stop();
        }
        self.start_selected_debug();
    }

    /// A session ended: the expressions survive (they usually make sense for
    /// the next run too), but the values, the changed-value baseline, and the
    /// baseline latch are that session's — left in place they made every
    /// watch flash "changed" on a fresh session's first stop.
    fn reset_watch_runtime(&mut self) {
        self.watch_vals.clear();
        self.watch_prev.clear();
        self.watch_baseline_pending = false;
    }

    /// Shift+F5: stop debugging and tear the session down.
    pub fn debug_stop(&mut self) {
        if let Some(session) = self.dap_session.as_mut() {
            session.disconnect();
        }
        self.dap_session = None;
        self.reset_watch_runtime();
        // Sweep js-debug's detached watchdog (and any leftover tree) once it has
        // reparented to init after the server dies. See the Terminated arm in
        // `poll_dap` and `crate::dap::reaper`.
        crate::dap::reaper::reap_orphaned_js_debug_async(std::time::Duration::from_millis(
            REAPER_TEARDOWN_GRACE_MS,
        ));
        self.editor.stop_line = None;
        self.editor.unverified_breakpoints.clear();
        // The breakpoint croft set at the failing assertion goes with the
        // session that asked for it (#373).
        self.disarm_failure_breakpoint();
        self.clear_inline_values();
        self.status = String::from("Debug session stopped");
        // Clear the paused-state feedback ("Paused (breakpoint)") so the
        // empty-state panel doesn't keep showing it under the Run button.
        self.run_debug.feedback = None;
        self.run_debug.feedback_is_error = false;
        // Refresh now: `poll_dap` early-returns once the session is gone, so it
        // would never deactivate the panel on its own — without this the Run &
        // Debug panel keeps showing the stale "Paused" tree until the next event.
        self.refresh_debug_panel();
    }

    pub fn run_active_file(&mut self) {
        let Some(path) = self.editor.path.clone() else {
            self.run_debug.feedback = Some(String::from("Open a file first"));
            self.run_debug.feedback_is_error = true;
            return;
        };
        let run_root = self
            .roots
            .owning_root(&path)
            .unwrap_or_else(|| self.roots.primary())
            .to_path_buf();
        let Some(spec) = Self::run_spec_for(&path, &run_root) else {
            self.run_debug.feedback = Some(format!(
                "Don't know how to run {}",
                path.file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| path.display().to_string())
            ));
            self.run_debug.feedback_is_error = true;
            return;
        };
        match PtyTerminal::new_running(&spec.program, &spec.args, &spec.cwd) {
            Ok(term) => {
                let target = self.active_terminal + 1;
                self.terminals.insert(target, term);
                self.active_terminal = target;
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.focus_pane(Pane::Terminal);
                self.run_debug.feedback = Some(format!(
                    "Running {}",
                    path.file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| path.display().to_string())
                ));
                self.run_debug.feedback_is_error = false;
            }
            Err(e) => {
                self.run_debug.feedback = Some(format!("Failed to spawn terminal: {e}"));
                self.run_debug.feedback_is_error = true;
            }
        }
    }

    /// Open the change at `entry_idx` in the editor pane: a side-by-side
    /// diff against HEAD for Modified / StagedModified entries (the
    /// VS Code Source Control click behaviour), or a plain file open
    /// for everything else where the working tree IS the only version
    /// (Untracked, StagedAdded) or HEAD doesn't carry the file
    /// (Deleted). Selection state on the panel updates so the user can
    /// see which entry the editor is bound to.
    pub fn open_source_control_entry(&mut self, entry_idx: usize) {
        use crate::git::ChangeKind;
        let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
            return;
        };
        self.source_control.selected_change = Some(entry_idx);
        // Porcelain paths are toplevel-relative (#139): join and HEAD-read
        // against the repo root, never the workspace root.
        let scm_root = self.scm_root();
        let abs = scm_root.join(&entry.path);
        let opened = match entry.kind {
            // A conflicted entry opens the three-way MERGE EDITOR (#253)
            // on the index stages — non-overlapping hunks pre-resolve,
            // and "Reopen as Text" reaches the old in-buffer marker flow.
            // If the stages are unreadable (e.g. binary), fall back to
            // opening the working file with its markers, parked on the
            // first conflict as before.
            ChangeKind::Conflicted => {
                if self.open_merge_editor_for(&abs) {
                    true
                } else {
                    match self.editor.open_pinned(&abs) {
                        Ok(()) => {
                            self.focus_pane(Pane::Editor);
                            let n = self.editor.conflicts().len();
                            if let Some(block) = self.editor.conflicts().first().copied() {
                                self.editor.clear_selection();
                                self.editor.cursor_row = block.ours_start;
                                self.editor.cursor_col = 0;
                                self.editor.scroll_col = 0;
                                self.editor.ensure_cursor_col_visible();
                            }
                            self.status = format!(
                                "{n} conflict{} — F7 jumps, Cmd+. accepts, \"Merge: Complete Merge\" stages",
                                if n == 1 { "" } else { "s" }
                            );
                            true
                        }
                        Err(e) => {
                            self.status = format!("Open failed: {e}");
                            false
                        }
                    }
                }
            }
            ChangeKind::Modified | ChangeKind::StagedModified => {
                match crate::git::read_file_at_head(&scm_root, &entry.path) {
                    Ok(head_text) => {
                        let label = std::path::PathBuf::from(format!("{} (HEAD)", entry.path));
                        match self
                            .editor
                            .open_head_diff_with_text(label, &head_text, &abs, true)
                        {
                            Ok(()) => {
                                self.tag_open_diff(
                                    crate::widgets::diff::DiffSource::HeadVsWorking {
                                        root: scm_root.to_path_buf(),
                                        rel: entry.path.clone(),
                                    },
                                );
                                true
                            }
                            Err(e) => {
                                self.status = format!("Diff failed: {e}");
                                false
                            }
                        }
                    }
                    Err(e) => {
                        self.status = format!("git show HEAD failed: {e}");
                        // Fall back to plain open so the user still sees
                        // something rather than nothing.
                        if abs.is_file() {
                            self.editor.open_pinned(&abs).is_ok()
                        } else {
                            false
                        }
                    }
                }
            }
            ChangeKind::Deleted | ChangeKind::StagedDeleted => {
                // No working-tree file to diff against — show the HEAD
                // blob as a one-sided unified diff so every removed
                // line is visible in red, matching `git diff` output
                // for a deletion.
                match crate::git::read_file_at_head(&scm_root, &entry.path) {
                    Ok(head_text) => {
                        let label = std::path::PathBuf::from(&entry.path);
                        match self.editor.open_deleted_diff_with_text(&label, &head_text) {
                            Ok(()) => true,
                            Err(e) => {
                                self.status = format!("Open deletion view failed: {e}");
                                false
                            }
                        }
                    }
                    Err(e) => {
                        self.status = format!("git show HEAD failed: {e}");
                        false
                    }
                }
            }
            _ => {
                if abs.is_file() {
                    match self.editor.open_pinned(&abs) {
                        Ok(()) => true,
                        Err(e) => {
                            self.status = format!("Open failed: {e}");
                            false
                        }
                    }
                } else {
                    false
                }
            }
        };
        if opened {
            self.focus_pane(Pane::Editor);
            self.sync_open_file_poll_mtime();
        }
    }

    /// Open `path` as a pinned editor tab and focus the editor. Used at launch
    /// for `croft <root> --open-file <path>` (the new window spawned by Move /
    /// Copy into New Window opens the handed-off file this way). Best-effort: a
    /// missing / unreadable file just leaves the editor on the welcome screen.
    pub fn open_file_at_launch(&mut self, path: &Path) {
        if self.editor.open_pinned(path).is_ok() {
            // Launch is not a user focus gesture: collapsing here would hide
            // the sidebar before the user has interacted at all (#260).
            self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
            self.sync_open_file_poll_mtime();
        }
    }

    fn initialize_repository(&mut self) {
        match std::process::Command::new("git")
            .arg("-C")
            .arg(&self.tree.root)
            .arg("init")
            .output()
        {
            Ok(out) if out.status.success() => {
                self.status = format!(
                    "Initialized empty Git repository in {}",
                    self.tree.root.display()
                );
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
            }
            Ok(out) => {
                let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
                self.status = format!("git init failed: {err}");
            }
            Err(e) => {
                self.status = format!("git init failed: {e}");
            }
        }
    }

    pub fn stage_selected_source_control_entries(&mut self) {
        let indices: Vec<usize> = if self.source_control.multi_selection.is_empty() {
            self.source_control
                .selected_change
                .iter()
                .copied()
                .collect()
        } else {
            self.source_control
                .multi_selection
                .iter()
                .copied()
                .collect()
        };
        if indices.is_empty() {
            self.status = String::from("No change selected to stage");
            return;
        }
        let paths: Vec<String> = indices
            .iter()
            .filter_map(|i| self.source_control.entries.get(*i))
            .filter(|e| e.kind.section() != crate::git::ChangeSection::Staged)
            .map(|e| e.path.clone())
            .collect();
        if paths.is_empty() {
            self.status = String::from("Selection is already staged");
            return;
        }
        match crate::git::stage_paths(&self.scm_root(), &paths) {
            Ok(()) => {
                self.status = if paths.len() == 1 {
                    format!("Staged {}", paths[0])
                } else {
                    format!("Staged {} files", paths.len())
                };
            }
            Err(err) => {
                self.status = format!("Stage failed: {err}");
                self.source_control.commit_feedback = Some(err);
                self.source_control.commit_feedback_is_error = true;
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    /// Push the current branch without committing. Sibling of
    /// `commit_and_push_source_control`, called from the commit dropdown's
    /// "Push" item so users can ship already-committed work without
    /// having to type a no-op commit message first.
    pub fn push_source_control(&mut self) {
        match crate::git::push_current_branch(&self.scm_root()) {
            Ok(summary) => {
                self.source_control.commit_feedback = Some(if summary.is_empty() {
                    "pushed".to_string()
                } else {
                    format!("pushed: {summary}")
                });
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("Pushed: {summary}");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("push failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Push failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
    }

    /// Pull the current branch from its upstream. Sibling of
    /// `push_source_control`, reached from the commit dropdown's "Pull".
    pub fn pull_source_control(&mut self) {
        match crate::git::pull_current_branch(&self.scm_root()) {
            Ok(summary) => {
                self.source_control.commit_feedback = Some(if summary.is_empty() {
                    "pulled".to_string()
                } else {
                    format!("pulled: {summary}")
                });
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("Pulled: {summary}");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("pull failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Pull failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    /// Sync = pull then push, mirroring VS Code's sync button. A failed
    /// pull short-circuits (we never push on top of an unmerged tree); a
    /// successful pull followed by a failed push reports both halves.
    pub fn sync_source_control(&mut self) {
        let pull_summary = match crate::git::pull_current_branch(&self.scm_root()) {
            Ok(s) => s,
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("sync: pull failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Sync failed on pull: {err}");
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
                return;
            }
        };
        match crate::git::push_current_branch(&self.scm_root()) {
            Ok(push_summary) => {
                self.source_control.commit_feedback = Some(format!(
                    "synced (pulled: {pull_summary} | pushed: {push_summary})"
                ));
                self.source_control.commit_feedback_is_error = false;
                self.status = String::from("Synced");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("pull ok; push failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Sync: pull ok; push failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    /// Stash the working tree (`git stash push`). Reached from the commit
    /// dropdown's "Stash" item.
    pub fn stash_source_control(&mut self) {
        match crate::git::stash_push(&self.scm_root()) {
            Ok(summary) => {
                self.source_control.commit_feedback = Some(format!("stashed: {summary}"));
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("Stashed: {summary}");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("stash failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Stash failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    /// Restore the most recent stash (`git stash pop`). A pop conflict is
    /// surfaced verbatim so the user can resolve it.
    pub fn stash_pop_source_control(&mut self) {
        match crate::git::stash_pop(&self.scm_root()) {
            Ok(summary) => {
                self.source_control.commit_feedback = Some(format!("popped: {summary}"));
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("Stash popped: {summary}");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("stash pop failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Stash pop failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    /// Unstage a single entry by index (the inline "−" icon on a staged
    /// row). Mirror of `stage_source_control_entry`.
    pub fn unstage_source_control_entry(&mut self, entry_idx: usize) {
        let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
            return;
        };
        match crate::git::unstage_path(&self.scm_root(), &entry.path) {
            Ok(()) => {
                self.status = format!("Unstaged {}", entry.path);
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
            }
            Err(err) => {
                self.status = format!("Unstage failed: {err}");
                self.source_control.commit_feedback = Some(err);
                self.source_control.commit_feedback_is_error = true;
            }
        }
    }

    // --- Source Control "⋯" menu plumbing --------------------------------

    /// Append a git command + its outcome to the rolling output log, which
    /// the "Show Git Output" action surfaces read-only. Capped so a long
    /// session can't grow it without bound.
    fn log_git(&mut self, label: &str, outcome: &Result<String, String>) {
        let body = match outcome {
            Ok(s) if s.is_empty() => String::from("(ok)"),
            Ok(s) => s.clone(),
            Err(e) => format!("error: {e}"),
        };
        self.git_output_log.push(format!("$ git {label}\n{body}"));
        const CAP: usize = 200;
        if self.git_output_log.len() > CAP {
            let excess = self.git_output_log.len() - CAP;
            self.git_output_log.drain(0..excess);
        }
    }

    /// Run an immediate git operation: log it, surface its summary or error
    /// in the commit-feedback line, and refresh the panel. The single path
    /// every "⋯"-menu leaf that acts now (vs. opening a modal) flows through.
    fn run_scm_op(&mut self, label: &str, outcome: Result<String, String>, ok_prefix: &str) {
        self.log_git(label, &outcome);
        match outcome {
            Ok(summary) => {
                self.source_control.commit_feedback = Some(if summary.is_empty() {
                    ok_prefix.to_string()
                } else {
                    format!("{ok_prefix}: {summary}")
                });
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("{ok_prefix}: {summary}");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("{ok_prefix} failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("{ok_prefix} failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    pub fn stage_all_source_control(&mut self) {
        let r = crate::git::stage_all(&self.scm_root());
        self.run_scm_op("add -A", r, "Staged all");
    }

    pub fn unstage_all_source_control(&mut self) {
        let r = crate::git::unstage_all(&self.scm_root());
        self.run_scm_op("reset HEAD", r, "Unstaged all");
    }

    /// Arm the Discard All confirmation. Destructive (reverts every tracked
    /// edit to HEAD), so it never acts until `confirm_pending_discard_all`.
    pub fn request_discard_all_source_control(&mut self) {
        self.pending_discard_all = true;
    }

    pub fn cancel_pending_discard_all(&mut self) {
        self.pending_discard_all = false;
    }

    pub fn confirm_pending_discard_all(&mut self) {
        if !self.pending_discard_all {
            return;
        }
        self.pending_discard_all = false;
        let r = crate::git::discard_all_tracked(&self.scm_root());
        self.run_scm_op("checkout -- .", r, "Discarded all changes");
    }

    /// The commit message currently in the input box, trimmed, or an error
    /// surfaced when it is empty (shared by the Commit submenu variants).
    fn require_commit_message(&mut self) -> Option<String> {
        let message = self.source_control.message.trim().to_string();
        if message.is_empty() {
            self.source_control.commit_feedback = Some(String::from("Empty commit message"));
            self.source_control.commit_feedback_is_error = true;
            return None;
        }
        Some(message)
    }

    fn commit_staged_source_control(&mut self) {
        let Some(message) = self.require_commit_message() else {
            return;
        };
        let r = crate::git::commit_staged(&self.scm_root(), &message);
        if r.is_ok() {
            self.source_control.clear_message();
        }
        self.run_scm_op("commit -m", r, "Committed staged");
    }

    fn commit_all_source_control(&mut self) {
        let Some(message) = self.require_commit_message() else {
            return;
        };
        if let Err(err) = crate::git::stage_all(&self.scm_root()) {
            self.run_scm_op("add -A", Err(err), "Stage all");
            return;
        }
        let r = crate::git::commit_staged(&self.scm_root(), &message);
        if r.is_ok() {
            self.source_control.clear_message();
        }
        self.run_scm_op("commit (all)", r, "Committed all");
    }

    fn commit_amend_source_control(&mut self) {
        // Amend keeps the prior message when the box is empty, otherwise
        // rewrites it — matching VS Code's amend.
        let message = self.source_control.message.trim().to_string();
        let r = if message.is_empty() {
            crate::git::commit_amend_no_edit(&self.scm_root())
        } else {
            crate::git::commit_amend(&self.scm_root(), &message)
        };
        if r.is_ok() {
            self.source_control.clear_message();
        }
        self.run_scm_op("commit --amend", r, "Amended commit");
    }

    fn commit_and_sync_source_control(&mut self) {
        let Some(message) = self.require_commit_message() else {
            return;
        };
        let commit = crate::git::commit_all_tracked(&self.scm_root(), &message);
        self.log_git("commit -am", &commit);
        if let Err(err) = commit {
            self.source_control.commit_feedback = Some(err.clone());
            self.source_control.commit_feedback_is_error = true;
            self.status = format!("Commit failed: {err}");
            return;
        }
        self.source_control.clear_message();
        self.sync_source_control();
    }

    fn publish_branch_source_control(&mut self) {
        let Some(branch) = self.source_control.status.branch.clone() else {
            self.source_control.commit_feedback =
                Some(String::from("Detached HEAD has no branch to publish"));
            self.source_control.commit_feedback_is_error = true;
            return;
        };
        let r = crate::git::publish_branch(&self.scm_root(), &branch);
        self.run_scm_op("push -u origin", r, "Published");
    }

    /// Open the read-only "Git Output" log in an editor tab (VS Code's Git
    /// output channel). Empty until croft has run an operation this session.
    fn show_git_output(&mut self) {
        let body = if self.git_output_log.is_empty() {
            String::from("(no git operations run yet this session)")
        } else {
            self.git_output_log.join("\n\n")
        };
        let label = self.scratch_buffer_path("Git Output");
        if let Err(err) = self.editor.open_text_buffer(&label, &body) {
            self.status = format!("Could not open Git Output: {err}");
            return;
        }
        self.focus_pane(Pane::Editor);
    }

    /// Open the branch picker with an explicit purpose (Checkout by default,
    /// or one of the Branch-submenu verbs).
    fn open_branch_picker_for(&mut self, purpose: BranchPurpose) {
        self.branch_purpose = purpose;
        self.open_branch_picker();
    }

    /// Open a single-line input modal for an SCM value (clone URL, branch
    /// rename, …).
    fn open_input_prompt(&mut self, prompt: crate::widgets::input_prompt::InputPrompt) {
        self.scm_menu.close();
        self.input_prompt = Some(prompt);
        self.overlays.input_prompt_clear.request();
    }

    fn close_input_prompt(&mut self) {
        if self.input_prompt.take().is_some() {
            self.overlays.input_prompt_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    /// Open a single-choice list picker (stashes, tags, remotes). Reports
    /// the empty case instead of opening a useless box.
    fn open_list_picker(
        &mut self,
        picker: crate::widgets::list_picker::ListPicker,
        empty_msg: &str,
    ) {
        self.scm_menu.close();
        if picker.rows.is_empty() {
            self.status = empty_msg.to_string();
            return;
        }
        self.list_picker = Some(picker);
        self.overlays.list_picker_clear.request();
    }

    fn close_list_picker(&mut self) {
        if self.list_picker.take().is_some() {
            self.overlays.list_picker_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    /// Route every "⋯"-menu leaf to its handler. Immediate ops run now;
    /// ops needing a value or a choice open a modal/picker.
    pub fn dispatch_scm_action(&mut self, action: crate::widgets::scm_menu::ScmAction) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        use crate::widgets::list_picker::ListPurpose;
        use crate::widgets::scm_menu::ScmAction;
        self.scm_menu.close();
        match action {
            ScmAction::Pull => self.pull_source_control(),
            ScmAction::Push => self.push_source_control(),
            ScmAction::Clone => self.open_input_prompt(InputPrompt::new(
                InputPurpose::CloneUrl,
                "Clone Repository",
                "Repository URL (https://… or git@…)",
            )),
            ScmAction::CheckoutTo => self.open_branch_picker_for(BranchPurpose::Checkout),
            ScmAction::Fetch => {
                let r = crate::git::fetch_all(&self.scm_root());
                self.run_scm_op("fetch --all --prune", r, "Fetched");
            }
            ScmAction::ShowGitOutput => self.show_git_output(),
            ScmAction::Commit => self.commit_source_control(),
            ScmAction::CommitStaged => self.commit_staged_source_control(),
            ScmAction::CommitAll => self.commit_all_source_control(),
            ScmAction::CommitAmend => self.commit_amend_source_control(),
            ScmAction::CommitAndPush => self.commit_and_push_source_control(),
            ScmAction::CommitAndSync => self.commit_and_sync_source_control(),
            ScmAction::StageAll => self.stage_all_source_control(),
            ScmAction::UnstageAll => self.unstage_all_source_control(),
            ScmAction::DiscardAll => self.request_discard_all_source_control(),
            ScmAction::Sync => self.sync_source_control(),
            ScmAction::PullRebase => {
                let r = crate::git::pull_rebase(&self.scm_root());
                self.run_scm_op("pull --rebase", r, "Pulled (rebase)");
            }
            ScmAction::PushTo => self.open_push_to_remote_picker(),
            ScmAction::PushForce => {
                let r = crate::git::push_force(&self.scm_root());
                self.run_scm_op("push --force-with-lease", r, "Force-pushed");
            }
            ScmAction::PublishBranch => self.publish_branch_source_control(),
            ScmAction::CreateBranch => self.open_branch_picker_for(BranchPurpose::Checkout),
            ScmAction::CreateBranchFrom => self.open_branch_picker_for(BranchPurpose::CreateFrom),
            ScmAction::RenameBranch => {
                let seed = self
                    .source_control
                    .status
                    .branch
                    .clone()
                    .unwrap_or_default();
                self.open_input_prompt(
                    InputPrompt::new(
                        InputPurpose::RenameBranch,
                        "Rename Branch",
                        "New branch name",
                    )
                    .with_value(seed),
                );
            }
            ScmAction::DeleteBranch => self.open_branch_picker_for(BranchPurpose::Delete),
            ScmAction::Merge => self.open_branch_picker_for(BranchPurpose::Merge),
            ScmAction::Rebase => self.open_branch_picker_for(BranchPurpose::Rebase),
            ScmAction::AddRemote => self.open_input_prompt(InputPrompt::new(
                InputPurpose::AddRemoteName,
                "Add Remote",
                "Remote name (e.g. origin)",
            )),
            ScmAction::RemoveRemote => self.open_remote_picker(ListPurpose::RemoveRemote),
            ScmAction::Stash => self.stash_source_control(),
            ScmAction::StashIncludeUntracked => {
                let r = crate::git::stash_push_untracked(&self.scm_root());
                self.run_scm_op("stash push -u", r, "Stashed (incl. untracked)");
            }
            ScmAction::StashStaged => {
                let r = crate::git::stash_push_staged(&self.scm_root());
                self.run_scm_op("stash push --staged", r, "Stashed staged");
            }
            ScmAction::ApplyStash => self.open_stash_picker(ListPurpose::StashApply),
            ScmAction::PopStashLatest => self.stash_pop_source_control(),
            ScmAction::PopStashPick => self.open_stash_picker(ListPurpose::StashPop),
            ScmAction::DropStash => self.open_stash_picker(ListPurpose::StashDrop),
            ScmAction::CreateTag => self.open_input_prompt(InputPrompt::new(
                InputPurpose::CreateTag,
                "Create Tag",
                "Tag name (e.g. v1.0.0)",
            )),
            ScmAction::DeleteTag => self.open_tag_picker(),
        }
    }

    fn open_stash_picker(&mut self, purpose: crate::widgets::list_picker::ListPurpose) {
        use crate::widgets::list_picker::{ListPicker, ListRow};
        let rows: Vec<ListRow> = match crate::git::list_stashes(&self.scm_root()) {
            Ok(stashes) => stashes
                .into_iter()
                .map(|s| ListRow {
                    id: s.index.to_string(),
                    label: format!("stash@{{{}}}: {}", s.index, s.message),
                })
                .collect(),
            Err(err) => {
                self.status = format!("Stashes: {err}");
                return;
            }
        };
        let title = match purpose {
            crate::widgets::list_picker::ListPurpose::StashApply => "Apply Stash",
            crate::widgets::list_picker::ListPurpose::StashDrop => "Drop Stash",
            _ => "Pop Stash",
        };
        self.open_list_picker(
            ListPicker::new(purpose, title, rows),
            "No stashes to choose",
        );
    }

    fn open_tag_picker(&mut self) {
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let rows: Vec<ListRow> = match crate::git::list_tags(&self.scm_root()) {
            Ok(tags) => tags
                .into_iter()
                .map(|t| ListRow {
                    id: t.clone(),
                    label: t,
                })
                .collect(),
            Err(err) => {
                self.status = format!("Tags: {err}");
                return;
            }
        };
        self.open_list_picker(
            ListPicker::new(ListPurpose::DeleteTag, "Delete Tag", rows),
            "No tags to delete",
        );
    }

    fn open_remote_picker(&mut self, purpose: crate::widgets::list_picker::ListPurpose) {
        use crate::widgets::list_picker::{ListPicker, ListRow};
        let rows: Vec<ListRow> = match crate::git::list_remotes(&self.scm_root()) {
            Ok(remotes) => remotes
                .into_iter()
                .map(|r| ListRow {
                    id: r.name.clone(),
                    label: format!("{}  {}", r.name, r.url),
                })
                .collect(),
            Err(err) => {
                self.status = format!("Remotes: {err}");
                return;
            }
        };
        self.open_list_picker(
            ListPicker::new(purpose, "Remove Remote", rows),
            "No remotes configured",
        );
    }

    fn open_push_to_remote_picker(&mut self) {
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let rows: Vec<ListRow> = match crate::git::list_remotes(&self.scm_root()) {
            Ok(remotes) => remotes
                .into_iter()
                .map(|r| ListRow {
                    id: r.name.clone(),
                    label: format!("{}  {}", r.name, r.url),
                })
                .collect(),
            Err(err) => {
                self.status = format!("Remotes: {err}");
                return;
            }
        };
        self.open_list_picker(
            ListPicker::new(ListPurpose::PushToRemote, "Push to Remote", rows),
            "No remotes configured",
        );
    }

    /// Apply the value submitted by the input modal to its purpose's git op.
    fn submit_input_prompt(&mut self) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        let Some(prompt) = self.input_prompt.as_ref() else {
            return;
        };
        let Some(value) = prompt.submit_value() else {
            return; // blank: keep waiting
        };
        let purpose = prompt.purpose.clone();
        match purpose {
            InputPurpose::AddWatch => {
                self.close_input_prompt();
                self.add_watch_expression(value);
            }
            InputPurpose::MacroReplayCount => {
                self.close_input_prompt();
                match value.trim().parse::<usize>() {
                    Ok(n) if n > 0 => self.replay_last_macro(n),
                    _ => self.status = format!("Not a repeat count: {}", value.trim()),
                }
            }
            InputPurpose::ArchiveExtract { member } => {
                self.close_input_prompt();
                let dest = PathBuf::from(value.trim());
                let Some((path, kind)) = self
                    .editor
                    .archive
                    .as_ref()
                    .and_then(|v| Some((self.editor.path.clone()?, v.kind)))
                else {
                    return;
                };
                match crate::archive::extract_member(&path, kind, &member, &dest) {
                    Ok(p) => self.status = format!("Extracted to {}", p.display()),
                    Err(e) => self.status = format!("Extract failed: {e}"),
                }
            }
            InputPurpose::NewWorktreeLane => {
                self.close_input_prompt();
                self.create_worktree_lane(&value);
            }
            InputPurpose::FleetCommand => {
                // Closed FIRST, like every sibling arm. Leaving it open hides
                // the status line the run writes, so the user cannot see the
                // answer they just asked for.
                self.close_input_prompt();
                self.run_fleet_command(&value);
            }
            InputPurpose::HexFind => {
                self.close_input_prompt();
                match crate::hex::HexView::parse_find_query(&value) {
                    Some(needle) => {
                        let from = match self.editor.hex.as_mut() {
                            Some(view) => {
                                view.last_find = Some(needle);
                                // The submit searches from the cursor
                                // INCLUSIVE so a match under it is
                                // found; F3 then steps past it.
                                view.cursor
                            }
                            None => return,
                        };
                        self.hex_find_run(from);
                    }
                    None => self.status = String::from("Hex find: empty query"),
                }
            }
            InputPurpose::SaveWorkspaceAs => {
                self.close_input_prompt();
                let dest = PathBuf::from(value.trim());
                let folders: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
                match crate::workspace::write_workspace_file(&dest, &folders) {
                    Ok(()) => {
                        self.status = format!(
                            "Saved workspace ({} folder{}): {}",
                            folders.len(),
                            if folders.len() == 1 { "" } else { "s" },
                            dest.display()
                        );
                    }
                    Err(e) => self.status = format!("Save workspace: {e}"),
                }
            }
            InputPurpose::CloneUrl => {
                self.close_input_prompt();
                let parent = self
                    .tree
                    .root
                    .parent()
                    .map(|p| p.to_path_buf())
                    .unwrap_or_else(|| self.tree.root.clone());
                match crate::git::clone_into(&parent, &value) {
                    Ok(dest) => {
                        self.log_git("clone", &Ok(format!("into {}", dest.display())));
                        self.status = format!("Cloned into {}", self.status_path(&dest));
                        self.change_workspace_root(dest);
                    }
                    Err(err) => {
                        self.log_git("clone", &Err(err.clone()));
                        self.source_control.commit_feedback = Some(format!("clone failed: {err}"));
                        self.source_control.commit_feedback_is_error = true;
                        self.status = format!("Clone failed: {err}");
                    }
                }
            }
            InputPurpose::RenameBranch => {
                self.close_input_prompt();
                let r = crate::git::rename_branch(&self.scm_root(), &value);
                self.run_scm_op("branch -m", r, "Renamed branch");
            }
            InputPurpose::CreateBranchFrom { base } => {
                self.close_input_prompt();
                let r = crate::git::create_branch_from(&self.scm_root(), &value, &base);
                self.run_scm_op("switch -c (from)", r, "Created branch");
            }
            InputPurpose::AddRemoteName => {
                // First step: capture the name, then re-prompt for the URL.
                self.close_input_prompt();
                self.open_input_prompt(InputPrompt::new(
                    InputPurpose::AddRemoteUrl { name: value },
                    "Add Remote",
                    "Remote URL",
                ));
            }
            InputPurpose::AddRemoteUrl { name } => {
                self.close_input_prompt();
                let r = crate::git::add_remote(&self.scm_root(), &name, &value);
                self.run_scm_op("remote add", r, "Added remote");
            }
            InputPurpose::CreateTag => {
                self.close_input_prompt();
                let r = crate::git::create_tag(&self.scm_root(), &value);
                self.run_scm_op("tag", r, "Created tag");
            }
            InputPurpose::ViewerConsent { key, path } => {
                // The user allowed the viewer's extension; record it and
                // resume the open that asked. The viewer is looked up first:
                // one removed while the prompt was up gets a status line and
                // no consent, since what was allowed no longer exists.
                self.close_input_prompt();
                let Some(viewer) =
                    crate::mcp::registry::viewer_by_id_in_dir(&self.config_dir, &key)
                else {
                    self.status = format!("{key} is no longer available");
                    return;
                };
                // The session grant first, so the open passes the gate; the
                // prefs write after, so a failure it reports is the status
                // the user is left with rather than one the open overwrote.
                self.consented_extensions.insert(viewer.ext_id.clone());
                self.open_in_viewer(&viewer, &path);
                self.persist_extension_consent(&viewer.ext_id);
            }
            InputPurpose::McpConsent { command_id } => {
                // The user confirmed; record consent for this command's
                // extension and resume the command (which now passes the gate
                // and proceeds to its argument prompt or runs).
                self.close_input_prompt();
                // The session grant first, so the run passes the gate, and
                // the prefs write before the run here: a sidecar command's
                // run ends on its own argument prompt with no status of its
                // own, so a failure reported after it would sit under that
                // prompt and be cleared with it.
                let ext_id =
                    crate::mcp::registry::resolve_command_in_dir(&self.config_dir, &command_id)
                        .map(|r| r.ext_id);
                if let Some(ext_id) = &ext_id {
                    self.consented_extensions.insert(ext_id.clone());
                    self.persist_extension_consent(ext_id);
                }
                self.run_extension_command(&command_id);
            }
            InputPurpose::McpArg { command_id } => {
                self.close_input_prompt();
                if let Some(resolved) =
                    crate::mcp::registry::resolve_command_in_dir(&self.config_dir, &command_id)
                {
                    self.spawn_mcp_command(resolved, Some(value));
                }
            }
            InputPurpose::ExtensionUninstall { id } => {
                self.close_input_prompt();
                self.perform_extension_uninstall(&id);
            }
            InputPurpose::TreeDelete { paths } => {
                self.close_input_prompt();
                self.perform_delete_paths(paths);
            }
            InputPurpose::ReloadConflict { paths } => {
                self.close_input_prompt();
                let reverted = self.editor.revert_paths_to_disk(&paths);
                self.sync_open_file_poll_mtime();
                // A failed reload (file deleted since the popup opened) keeps
                // its unsaved edits — say so instead of silently doing nothing.
                let failed = paths.len().saturating_sub(reverted.len());
                self.status = match (reverted.len(), failed) {
                    (0, _) => String::from("Reload from disk failed; unsaved edits kept"),
                    (1, 0) => format!("Reloaded {} from disk", reverted[0].display()),
                    (n, 0) => format!("Reloaded {n} files from disk"),
                    (n, f) => format!("Reloaded {n} files; {f} failed and kept their edits"),
                };
            }
            InputPurpose::AskNavigator {
                file,
                range,
                selection,
            } => {
                // The prompt closes only on a SENT ask: a failure (navigator
                // gone or gone busy while the user typed) keeps the box open
                // with the draft intact for a retry, like a failed comment
                // reply keeps its draft.
                let Some(host) = &self.pair_host else {
                    self.status = String::from("Navigator is not active");
                    return;
                };
                let content = self.editor.lines.join("\n");
                let name = host.name().to_string();
                let result = host.send_ask_turn(&file, range, &selection, &value, &content);
                match result {
                    Ok(()) => {
                        self.close_input_prompt();
                        self.status = format!("Asked {name} about {file}:{}", range.0 + 1);
                        // Anchor the turn's prose commentary where it was asked.
                        self.pair_turn_origin = Some((file, range.0));
                    }
                    Err(e) => self.status = format!("Ask Navigator failed: {e}"),
                }
            }
        }
    }

    /// "Session: Participants" (Cmd+K A): who is attached to this
    /// multiplayer session, from the host's presence sidecar
    /// (docs/MULTIPLAYER.md). Enter on a row opens the action picker.
    fn open_participants_picker(&mut self) {
        if self.session_channel.is_none() {
            self.status = String::from("Not a persistent session (start one with `croft attach`)");
            return;
        }
        let rows: Vec<crate::widgets::list_picker::ListRow> = self
            .session_participants
            .iter()
            .map(participant_row)
            .collect();
        let picker = crate::widgets::list_picker::ListPicker::new(
            crate::widgets::list_picker::ListPurpose::SessionParticipant,
            "Session Participants",
            rows,
        );
        self.open_list_picker(picker, "No participants yet");
    }

    /// Second-level picker for one participant: grant or revoke write
    /// control, or disconnect them. Safe to expose to every attacher: a
    /// read-only guest's keystrokes are dropped at the session host, so any
    /// key that reaches this UI came from a control-holding client.
    fn open_participant_actions(&mut self, id: u64) {
        let Some(p) = self.session_participants.iter().find(|p| p.id == id) else {
            return;
        };
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let control_row = if p.control {
            ListRow {
                id: format!("revoke:{id}"),
                label: String::from("Revoke write control"),
            }
        } else {
            ListRow {
                id: format!("grant:{id}"),
                label: String::from("Grant write control"),
            }
        };
        let rows = vec![
            control_row,
            ListRow {
                id: format!("kick:{id}"),
                label: String::from("Disconnect"),
            },
        ];
        let picker = ListPicker::new(ListPurpose::SessionParticipantAction, p.name.clone(), rows);
        self.open_list_picker(picker, "No actions");
    }

    /// Send a participant action to the session host and report it. The
    /// roster update comes back through the presence poll.
    fn run_participant_action(&mut self, verb: ParticipantVerb, id: u64) {
        let name = self
            .session_participants
            .iter()
            .find(|p| p.id == id)
            .map(|p| p.name.clone())
            .unwrap_or_else(|| format!("participant {id}"));
        let Some(channel) = self.session_channel.as_mut() else {
            return;
        };
        let ok = match verb {
            ParticipantVerb::Grant => channel.set_control(id, true),
            ParticipantVerb::Revoke => channel.set_control(id, false),
            ParticipantVerb::Kick => channel.kick(id),
        };
        self.status = if ok {
            match verb {
                ParticipantVerb::Grant => format!("Granted write control to {name}"),
                ParticipantVerb::Revoke => format!("Revoked write control from {name}"),
                ParticipantVerb::Kick => format!("Disconnected {name}"),
            }
        } else {
            String::from("Session host unreachable")
        };
    }

    /// Poll the session host's presence sidecar (multiplayer roster): a stat
    /// every 500ms, reparse only when the mtime moves. Surfaces joins and
    /// leaves in the status line and keeps an open participants picker live.
    fn poll_session_presence(&mut self) -> bool {
        const INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
        if self.session_channel.is_none() {
            return false;
        }
        if self.last_session_presence_poll.elapsed() < INTERVAL {
            return false;
        }
        // A host swap (#238) tears this privileged channel down while the
        // session lives on under the successor host. The socket and token in
        // the environment are still valid - the successor inherited both -
        // so revival is just authenticating again, throttled by this poll's
        // own interval.
        if self.session_channel.as_ref().is_some_and(|c| c.is_dead())
            && let Some(fresh) = crate::session_host::InnerChannel::from_env()
        {
            self.session_channel = Some(fresh);
        }
        let Some(channel) = self.session_channel.as_ref() else {
            return false;
        };
        self.last_session_presence_poll = std::time::Instant::now();
        // #238: the serve wrapper normally re-execs itself into an updated
        // binary, carrying the session along - the marker appears only when
        // that handoff could not happen (exec failed, no handoff fds), so
        // the host is stuck on the old image and the one recovery is a
        // fresh host, which a detach + reattach of the last participant
        // produces. Checked before the presence-mtime early-return: a
        // roster that never changes must not hide the hint.
        if !self.session_host_stale_seen && channel.stale_marker.exists() {
            self.session_host_stale_seen = true;
            self.status = String::from(
                "Session host runs a pre-update binary; detach and reattach (all participants) to pick up the update",
            );
        }
        let path = channel.presence.clone();
        let mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
        if mtime == self.session_presence_mtime {
            return false;
        }
        self.session_presence_mtime = mtime;
        let roster = crate::session_host::read_presence(&path).unwrap_or_default();
        if roster == self.session_participants {
            return false;
        }
        let before = self.session_participants.len();
        let after = roster.len();
        self.session_participants = roster;
        // before == 0 is the initial self-only read; not worth announcing.
        if after > before && before > 0 {
            self.status = format!(
                "A participant attached read-only ({after} attached). Manage via Session: Participants (Cmd+K A)"
            );
        } else if after < before {
            self.status = format!("A participant detached ({after} attached)");
        }
        // Keep an open participants picker live without wiping the user's
        // typed filter, highlight, or scroll (any client resizing churns the
        // roster within the poll window; a naive rebuild would reset it).
        if let Some(p) = self.list_picker.as_ref()
            && p.purpose == crate::widgets::list_picker::ListPurpose::SessionParticipant
        {
            let (query, cursor, selected, scroll) =
                (p.query.clone(), p.cursor, p.selected, p.scroll);
            self.open_participants_picker();
            if let Some(p) = self.list_picker.as_mut() {
                let last = p.rows.len().saturating_sub(1);
                p.query = query;
                p.cursor = cursor;
                p.selected = selected.min(last);
                p.scroll = scroll.min(last);
            }
        }
        true
    }

    /// Drain typing attribution from the session host: when the typing
    /// participant changes, hand the shared cursor over (stash the previous
    /// typist's caret, restore the new one's).
    fn poll_session_typing(&mut self) -> bool {
        let Some(channel) = self.session_channel.as_mut() else {
            return false;
        };
        let typists = channel.drain_typing();
        if typists.is_empty() {
            return false;
        }
        let mut changed = false;
        for id in typists {
            if self.session_typist != Some(id) {
                self.apply_typist_change(id);
                changed = true;
            }
        }
        changed
    }

    /// Participant `id` is typing now: park the previous typist's caret and
    /// move the shared cursor back to where `id` last was (same file only;
    /// a caret parked in another file just renders there as a ghost once
    /// that file is active again).
    fn apply_typist_change(&mut self, id: u64) {
        let path = self.editor.path.clone();
        if let (Some(prev), Some(path)) = (self.session_typist, path.as_ref()) {
            self.session_carets.insert(
                prev,
                SessionCaret {
                    path: path.clone(),
                    row: self.editor.cursor_row,
                    col: self.editor.cursor_col,
                },
            );
        }
        self.session_typist = Some(id);
        if let (Some(parked), Some(path)) = (self.session_carets.get(&id), path.as_ref())
            && parked.path == *path
            && !self.editor.lines.is_empty()
        {
            let row = parked.row.min(self.editor.lines.len() - 1);
            let col = parked.col.min(self.editor.lines[row].chars().count());
            self.editor.cursor_row = row;
            self.editor.cursor_col = col;
        }
    }

    /// The resident navigator's activation check (docs/MULTIPLAYER.md):
    /// stat the workspace's pair record on a 1s cadence, seat or unseat the
    /// pilot on `enabled` transitions, and — on a plain launch with no
    /// collab session — self-appoint the OWNER seat first, because only an
    /// owner answers the pilot's snapshot requests. Solo guests never host:
    /// the owner's croft does.
    fn maybe_seat_navigator(&mut self) -> bool {
        let due = self
            .last_pair_check
            .is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(1));
        if !due {
            return false;
        }
        self.last_pair_check = Some(std::time::Instant::now());
        // A rewritten record re-arms seating: after a failed seat the user
        // re-runs `croft pair`, and the CLI promises "a running croft seats
        // it within a second" — but an enabled→enabled rewrite has no other
        // observable transition. The record's BYTES are the signal (every
        // write stamps them, and mtime misses a same-grain rewrite on a
        // coarse-timestamp filesystem).
        let raw = std::fs::read(&self.pair_record_path).ok();
        if self.last_pair_record_raw != raw {
            if self.last_pair_record_raw.is_some() {
                self.navigator_down = false;
            }
            self.last_pair_record_raw = raw.clone();
        }
        let record: Option<crate::session::PairRecord> = raw
            .as_deref()
            .and_then(|bytes| serde_json::from_slice(bytes).ok());
        let want = record.as_ref().is_some_and(|r| r.enabled);
        if !want {
            // Deactivation clears the death latch, so `croft pair --off`
            // then `croft pair` (or a palette off/on) re-activates.
            self.navigator_down = false;
            self.pair_lock_denied = None;
            // A fix stream cannot outlive the seat: with the navigator
            // deactivated no TurnDone can arrive, and a marker left here
            // spun the row (and woke the renderer) forever (#374 review).
            self.clear_problem_fix();
            if let Some(host) = self.pair_host.take() {
                // Drop tears the seat down; its parked caret goes with it.
                let sites = host.caret_sites();
                self.collab_carets.retain(|s, _| !sites.contains(s));
                self.navigator_notes.clear();
                self.pair_commentary_buf.clear();
                self.pair_turn_origin = None;
                // The turn counters die with the seat: leaking them made
                // the NEXT seat's first TurnDone report a dead seat's notes.
                self.pair_notes_this_turn = 0;
                self.pair_last_noted_file = None;
                self.pair_noted_files.clear();
                self.editor.comment_focus = None;
                self.status = String::from("Navigator unseated");
                return true;
            }
            return false;
        }
        if self.pair_host.is_some() {
            return false;
        }
        // The pilot died or failed to seat: do not respawn it every second.
        // The user re-activates (off/on) to try again; a fresh croft retries.
        if self.navigator_down {
            return false;
        }
        if self
            .collab_config
            .as_ref()
            .is_some_and(|(_, role)| *role == crate::collab::CollabRole::Guest)
        {
            return false;
        }
        let record = record.expect("want implies a record");
        let mut self_appointed_now = false;
        if self.collab_config.is_none() {
            // Only one croft may self-appoint owner per workspace: two owners
            // would both claim site id 1 and corrupt the shared buffer. Claim
            // the single-host lock first; if another croft holds it, do not
            // host (keep checking — take over when that croft exits).
            if self.pair_host_lock.is_none() {
                match crate::session::try_acquire_pair_host_lock(&self.pair_host_lock_path) {
                    Ok(lock) => {
                        self.pair_host_lock = Some(lock);
                        self.pair_lock_denied = None;
                    }
                    Err(e) => {
                        // Announced ONCE per reason: the takeover poll keeps
                        // running every second, and re-announcing clobbered
                        // the window's status line forever at a 1 Hz repaint.
                        let denial = match &e {
                            crate::session::PairHostLockError::Busy => PairLockDenial::Busy,
                            crate::session::PairHostLockError::Io(_) => PairLockDenial::Io,
                        };
                        if self.pair_lock_denied == Some(denial) {
                            return false;
                        }
                        self.pair_lock_denied = Some(denial);
                        // Busy and unopenable read the same from here (no
                        // host this tick, poll again) but not to the user:
                        // one has a window to close, the other has a path
                        // to fix and no window anywhere (#337).
                        self.status = match e {
                            crate::session::PairHostLockError::Busy => format!(
                                "Navigator '{}' is hosted by another croft window in this workspace",
                                record.name
                            ),
                            crate::session::PairHostLockError::Io(e) => format!(
                                "Navigator '{}': cannot open host lock {}: {e}",
                                record.name,
                                self.pair_host_lock_path.display()
                            ),
                        };
                        return true;
                    }
                }
            }
            if let Err(e) = crate::collab::ensure_relay(&self.pair_socket) {
                self.status = format!("Navigator: relay failed: {e}");
                // The spawn failure's sibling: this window holds the lock
                // but cannot host without a relay. Release it so another
                // window can try; this one retries next second and may
                // re-acquire.
                self.pair_host_lock = None;
                return true;
            }
            self.collab_config = Some((self.pair_socket.clone(), crate::collab::CollabRole::Owner));
            self.last_collab_connect = None; // connect this tick, not in 2s
            self_appointed_now = true;
        }
        let cfg = crate::pair::PairConfig {
            socket: self.pair_socket.clone(),
            workspace: self.tree.root.clone(),
            name: record.name.clone(),
            model: record.model.clone(),
            // Resident seating never replays a task: a persisted task would
            // re-execute on every launch, and an @file task would freeze the
            // UI thread on seat (the owner that must serve the file is this
            // very thread). Instructions come from Cmd+K Q. The --repl driver
            // still takes a one-shot task via PairConfig directly.
            task: None,
            provider: crate::pair::Provider::from_record(
                record.provider.as_deref(),
                record.base_url.as_deref(),
            ),
        };
        #[cfg(test)]
        let spawned = match &self.pair_spawn_override {
            Some(spawn) => spawn(&cfg),
            None => crate::pair_host::PairHost::spawn(cfg),
        };
        #[cfg(not(test))]
        let spawned = crate::pair_host::PairHost::spawn(cfg);
        match spawned {
            Ok(host) => {
                self.status = format!(
                    "Navigator '{}' seated (Cmd+K Q asks, Cmd+K Y yields)",
                    host.title()
                );
                self.pair_host = Some(host);
            }
            Err(e) => {
                self.status = format!("Navigator failed to seat: {e}");
                self.navigator_down = true; // no 1s retry storm
                if self_appointed_now {
                    // A window that cannot host must not block one that can:
                    // undo the self-appointment made moments ago (nothing
                    // has connected yet within this same call) and release
                    // the lock so another croft may claim the seat. A host
                    // whose PILOT died later keeps both — it is still the
                    // live collab owner and re-seats on re-activation.
                    self.collab_config = None;
                    self.pair_host_lock = None;
                }
            }
        }
        true
    }

    /// Drain the navigator's per-tick events: commentary to the Navigator
    /// OUTPUT channel, note/turn/death news to the status line, and the
    /// active file's note snapshot for the gutter marks and popup.
    fn poll_pair(&mut self) -> bool {
        let Some(host) = self.pair_host.as_mut() else {
            return false;
        };
        let name = host.name().to_string();
        let events = host.poll();
        let mut changed = !events.is_empty();
        let mut died = false;
        for event in events {
            match event {
                crate::pair_host::PairEvent::Commentary(text) => {
                    // The navigator's voice is its comment boxes: prose
                    // accumulates and lands as one box when the turn ends.
                    if !text.trim().is_empty() {
                        if !self.pair_commentary_buf.is_empty() {
                            self.pair_commentary_buf.push('\n');
                        }
                        self.pair_commentary_buf.push_str(text.trim_end());
                    }
                }
                crate::pair_host::PairEvent::NoteAdded { file, row, body } => {
                    let snippet: String = body.chars().take(60).collect();
                    self.status = format!("{name} commented on {file}:{}: {snippet}", row + 1);
                    self.pair_notes_this_turn += 1;
                    self.pair_noted_files.insert(file.clone());
                    self.pair_last_noted_file = Some(file);
                }
                crate::pair_host::PairEvent::TurnDone { cancelled, failed } => {
                    let mut notes = std::mem::take(&mut self.pair_notes_this_turn);
                    let mut files = std::mem::take(&mut self.pair_noted_files);
                    let file = self.pair_last_noted_file.take();
                    let prose = std::mem::take(&mut self.pair_commentary_buf);
                    let origin = self.pair_turn_origin.take();
                    // Whatever the outcome, the fix turn is over: the row's
                    // spinner stops, and the LSP's next publish decides
                    // whether the row itself goes (#374).
                    self.clear_problem_fix();
                    if !cancelled && !prose.trim().is_empty() {
                        // Anchor the turn's prose at its invocation point (or
                        // where it last commented). A file that is not live
                        // any more falls back to the OUTPUT channel rather
                        // than losing the navigator's words.
                        let anchor = origin.or_else(|| {
                            file.clone().map(|f| {
                                // The caret row only means something in the
                                // file it is in: pairing the last-noted
                                // file with the ACTIVE tab's cursor row
                                // anchored the box at an unrelated line.
                                // Any other file clamps to its end.
                                let same = self
                                    .editor
                                    .path
                                    .as_ref()
                                    .and_then(|p| collab_file_key(&self.tree.root, p))
                                    .is_some_and(|active| active == f);
                                let row = if same {
                                    self.editor.cursor_row
                                } else {
                                    usize::MAX
                                };
                                (f, row)
                            })
                        });
                        let landed = anchor.as_ref().and_then(|(f, row)| {
                            self.pair_host
                                .as_ref()
                                .and_then(|h| h.add_note_now(f, *row, prose.trim()))
                        });
                        match (landed, anchor) {
                            (Some(_), Some((f, _))) => {
                                notes += 1;
                                files.insert(f);
                            }
                            _ => {
                                for line in prose.lines().filter(|l| !l.trim().is_empty()) {
                                    crate::output::push(
                                        "Navigator",
                                        crate::output::OutputLevel::Info,
                                        line,
                                    );
                                }
                            }
                        }
                    }
                    self.status = if cancelled {
                        format!("{name}: turn cancelled")
                    } else if let Some(err) = failed {
                        let err: String = err.chars().take(80).collect();
                        format!("{name}: turn failed: {err}")
                    } else if notes > 0 {
                        format!(
                            "{name} finished: {} · F4 to review",
                            turn_note_summary(notes, &files)
                        )
                    } else {
                        format!("{name} finished its turn")
                    };
                }
                crate::pair_host::PairEvent::Died(reason) => {
                    self.status = format!("Navigator: {reason}");
                    died = true;
                }
            }
        }
        if died {
            let sites = self
                .pair_host
                .take()
                .map(|h| h.caret_sites())
                .unwrap_or_default();
            self.collab_carets.retain(|s, _| !sites.contains(s));
            self.navigator_notes.clear();
            self.pair_commentary_buf.clear();
            self.pair_turn_origin = None;
            self.clear_problem_fix();
            // The turn counters die with the seat (see the unseat twin).
            self.pair_notes_this_turn = 0;
            self.pair_last_noted_file = None;
            self.pair_noted_files.clear();
            self.editor.comment_focus = None;
            self.navigator_down = true; // no auto-respawn; re-activate to retry
            return true;
        }
        // Refresh the active file's snapshot every tick: rows move under
        // concurrent edits without any new event arriving.
        if let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
            && let Some(host) = &self.pair_host
        {
            let snap = host.notes_snapshot(&file);
            if self.navigator_notes.get(&file) != Some(&snap) {
                self.navigator_notes.insert(file, snap);
                changed = true;
            }
        }
        changed
    }

    /// Keys while a comment box's reply field has focus: type into the
    /// draft, Enter sends the reply turn, Esc leaves the box (its draft
    /// survives until the box goes), F4 hops to the next box, Shift+F4
    /// ignores this one.
    fn handle_comment_focus_key(&mut self, key: KeyEvent) {
        if matches!(key.code, KeyCode::F(4)) {
            if key.modifiers.contains(KeyModifiers::SHIFT) {
                self.ignore_focused_comment();
            } else {
                self.cycle_comment_box();
            }
            return;
        }
        match key.code {
            KeyCode::Esc => {
                self.editor.comment_focus = None;
                return;
            }
            KeyCode::Enter => {
                self.submit_comment_reply();
                return;
            }
            _ => {}
        }
        let Some(focus) = self.editor.comment_focus.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Backspace if focus.cursor > 0 => {
                let idx = focus
                    .reply
                    .char_indices()
                    .nth(focus.cursor - 1)
                    .map(|(i, _)| i)
                    .unwrap_or(0);
                focus.reply.remove(idx);
                focus.cursor -= 1;
            }
            KeyCode::Left => focus.cursor = focus.cursor.saturating_sub(1),
            KeyCode::Right => {
                focus.cursor = (focus.cursor + 1).min(focus.reply.chars().count());
            }
            KeyCode::Char(c)
                if !key.modifiers.intersects(
                    KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
                ) =>
            {
                let idx = focus
                    .reply
                    .char_indices()
                    .nth(focus.cursor)
                    .map(|(i, _)| i)
                    .unwrap_or(focus.reply.len());
                focus.reply.insert(idx, c);
                focus.cursor += 1;
            }
            _ => {}
        }
    }

    /// Enter in the focused box: append the reply to the box (the running
    /// conversation stays visible) and send it to the navigator as a
    /// comment-only turn carrying the note's context.
    fn submit_comment_reply(&mut self) {
        let Some(focus) = self.editor.comment_focus.clone() else {
            return;
        };
        let reply = focus.reply.trim().to_string();
        if reply.is_empty() {
            return;
        }
        let Some(host) = &self.pair_host else {
            self.status =
                String::from("Navigator is not active (run croft pair in this workspace)");
            return;
        };
        if host.is_busy() {
            self.status = format!("{} is mid-turn; wait for it to finish", host.name());
            return;
        }
        let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
        else {
            self.status = String::from("Reply: no active workspace file");
            return;
        };
        let Some((_, row, note_body)) = self
            .navigator_notes
            .get(&file)
            .and_then(|notes| notes.iter().find(|(id, ..)| *id == focus.id))
            .cloned()
        else {
            self.status = String::from("That comment is gone");
            self.editor.comment_focus = None;
            return;
        };
        let content = self.editor.lines.join("\n");
        match host.send_reply_turn(&file, row, &note_body, &reply, &content) {
            Ok(()) => {
                // Only after the send: a failed send keeps the draft for a
                // retry, and appending first would duplicate the reply in
                // the box on every attempt.
                host.append_to_note(focus.id, &format!("you: {reply}"));
                self.pair_turn_origin = Some((file, row));
                self.status = format!("Replied to {}", host.name());
                self.editor.comment_focus = None;
            }
            Err(e) => self.status = format!("Reply failed: {e}"),
        }
    }

    /// Follow the open file to its new path so its review boxes survive a
    /// rename or an explorer cut/paste (#366).
    ///
    /// Both guards — the render merge and the F4 walk — compare the stored
    /// path against `editor.path`. A rename repoints the tab and would
    /// otherwise leave the field naming a path nothing matches, so the boxes
    /// vanish from the buffer the user is still editing and the field holds
    /// unreachable garbage.
    fn rename_review_boxes_path(&mut self, old: &Path, new: &Path) {
        if let Some((p, _)) = &mut self.review_boxes
            && p == old
        {
            *p = new.to_path_buf();
        }
    }

    /// Dismiss one comment box: drop the note from the pilot's state and
    /// from the local snapshot (the next poll would resurrect it otherwise
    /// only if the pilot still had it).
    fn ignore_comment_box(&mut self, id: u64) {
        if let Some(host) = &self.pair_host {
            host.remove_note(id);
        }
        for notes in self.navigator_notes.values_mut() {
            notes.retain(|(nid, ..)| *nid != id);
        }
        // Review boxes share this footer and this hit-test, so without
        // retaining here the button would report "Comment ignored" and the
        // box would return on the very next frame (#366).
        //
        // Matching on the id alone is safe because the two sources cannot
        // collide in practice: a navigator note's id counts up from 1 (see
        // `pair.rs`'s `take_note_id`, over `next_note_id`), while a review
        // thread's is GitHub's own comment id, currently around 3.9e9. If
        // notes ever gain a wider allocator, this needs a tag rather than a
        // bare id.
        if let Some((_, threads)) = &mut self.review_boxes {
            threads.retain(|t| t.id != id);
        }
        if self
            .editor
            .comment_focus
            .as_ref()
            .is_some_and(|f| f.id == id)
        {
            self.editor.comment_focus = None;
        }
        self.status = String::from("Comment ignored");
    }

    /// Shift+F4 / palette: ignore the focused box, or the next one from the
    /// caret when none is focused.
    fn ignore_focused_comment(&mut self) {
        let id = self
            .editor
            .comment_focus
            .as_ref()
            .map(|f| f.id)
            .or_else(|| self.next_comment_from_caret().map(|(id, _)| id));
        match id {
            Some(id) => self.ignore_comment_box(id),
            None => self.status = String::from("No navigator comments in this file"),
        }
    }

    /// The active file's next comment from the caret (by row, wrapping):
    /// (id, row).
    fn next_comment_from_caret(&self) -> Option<(u64, usize)> {
        // Built from the same two SOURCES the render merges, in the same
        // order, rather than from `editor.comment_boxes` itself: that field
        // is a render output, so reading it would make F4 depend on a frame
        // having been drawn first, and the walk would find nothing before
        // the first render. Review threads are included so F4 reaches them
        // too (#366) — reading only the navigator's notes left review boxes
        // on screen but unreachable by keyboard, reported as "No navigator
        // comments in this file" while the user was looking at several.
        let mut notes: Vec<(u64, usize, String)> = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
            .and_then(|file| self.navigator_notes.get(&file))
            .cloned()
            .unwrap_or_default();
        if let Some((path, threads)) = &self.review_boxes
            && self.editor.path.as_deref() == Some(path.as_path())
        {
            let lines = self.editor.lines.len();
            notes.extend(
                threads
                    .iter()
                    .map(|t| (t.id, t.box_line(lines), t.body.clone())),
            );
        }
        if notes.is_empty() {
            return None;
        }
        let here = self
            .editor
            .comment_focus
            .as_ref()
            .and_then(|f| notes.iter().position(|(id, ..)| *id == f.id))
            .map(|i| (notes[i].1, i))
            .unwrap_or((self.editor.cursor_row, usize::MAX));
        let idx = next_note_by_row(&notes, here);
        Some((notes[idx].0, notes[idx].1))
    }

    /// Open the ask box: an instruction input for the resident navigator,
    /// scoped to a 0-based inclusive line `range` of the active file, with
    /// `selection` carrying selected text when the scope came from one.
    /// Cmd+K Q, the gutter menu, and the body menu all land here.
    fn open_ask_navigator(&mut self, range: (usize, usize), selection: String) {
        let Some(host) = &self.pair_host else {
            self.status =
                String::from("Navigator is not active (run croft pair in this workspace)");
            return;
        };
        if host.is_busy() {
            self.status = format!("{} is mid-turn; wait for it to finish", host.name());
            return;
        }
        let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
        else {
            self.status = String::from("Ask Navigator: no active workspace file");
            return;
        };
        let scope = if range.0 == range.1 {
            format!("line {}", range.0 + 1)
        } else {
            format!("lines {}-{}", range.0 + 1, range.1 + 1)
        };
        self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
            crate::widgets::input_prompt::InputPurpose::AskNavigator {
                file: file.clone(),
                range,
                selection,
            },
            format!("Ask {} · {file} · {scope}", host.name()),
            "What should it look at or do?",
        ));
    }

    /// Cmd+K Y: hand the navigator the floor on the active file. The turn
    /// is comment-only (host-enforced): its say lands as anchored notes and
    /// commentary, and it must ask before editing.
    fn yield_to_navigator(&mut self) {
        let Some(host) = &self.pair_host else {
            self.status =
                String::from("Navigator is not active (run croft pair in this workspace)");
            return;
        };
        if host.is_busy() {
            self.status = format!("{} is mid-turn; wait for it to finish", host.name());
            return;
        }
        let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
        else {
            self.status = String::from("Yield: no active workspace file");
            return;
        };
        let content = self.editor.lines.join("\n");
        match host.send_yield_turn(&file, &content) {
            Ok(()) => {
                self.status = format!("Yielded {file} to {} (comment-only turn)", host.name());
                // Anchor the turn's prose commentary at the caret.
                self.pair_turn_origin = Some((file, self.editor.cursor_row));
            }
            Err(e) => self.status = format!("Yield failed: {e}"),
        }
    }

    /// Proactive navigator look (docs/MULTIPLAYER.md): when the driver
    /// completes a NEW construct in the active file (tree-sitter judged —
    /// half-typed code never parses as one) and pauses typing, the seated
    /// navigator takes the same comment-only turn Cmd+K Y hands it, anchored
    /// at the new construct. Only files the navigator has already looked at
    /// re-engage it (this is RE-engagement, not ambush), and a buffer state
    /// is scanned at most once. Runs once per frame tick; true = turn sent.
    fn tick_proactive_navigator(&mut self) -> bool {
        if !self.proactive_navigator_enabled {
            return false;
        }
        let Some(host) = &self.pair_host else {
            return false;
        };
        if host.is_busy() || self.editor.comment_focus.is_some() {
            return false;
        }
        // The user is mid-typing in a prompt (the ask box included):
        // stealing the seat now would make their Enter land on a busy host
        // and fail. Suppress WITHOUT consuming the scan latch below, so the
        // look fires once the prompt closes.
        if self.input_prompt.is_some() {
            return false;
        }
        let Some(edited) = self.editor.last_edit_at else {
            return false;
        };
        if edited.elapsed() < PROACTIVE_PAUSE {
            return false;
        }
        let Some(path) = self.editor.path.clone() else {
            return false;
        };
        let seq = self.editor.edit_seq;
        if self.proactive_scanned.get(&path) == Some(&seq) {
            return false;
        }
        self.proactive_scanned.insert(path.clone(), seq);
        let Some(file) = collab_file_key(&self.tree.root, &path) else {
            return false;
        };
        let Some(kind) = path
            .extension()
            .and_then(|e| e.to_str())
            .and_then(crate::highlight::lang_for_extension)
        else {
            return false;
        };
        let Some(old) = host.last_seen(&file) else {
            return false; // it never looked at this file; no self-invite
        };
        let content = self.editor.lines.join("\n");
        let Some(row) = crate::pair::proactive::new_construct_row(kind, &old, &content) else {
            return false;
        };
        match host.send_yield_turn(&file, &content) {
            Ok(()) => {
                self.status = format!("{} is taking a look at {file}:{}", host.name(), row + 1);
                self.pair_turn_origin = Some((file, row));
                true
            }
            Err(_) => false,
        }
    }

    /// Palette toggle for the proactive looks, persisted like the inline
    /// blame preference.
    fn toggle_proactive_navigator(&mut self) {
        self.proactive_navigator_enabled = !self.proactive_navigator_enabled;
        self.status = if self.proactive_navigator_enabled {
            String::from("Navigator proactive comments: on")
        } else {
            String::from("Navigator proactive comments: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_proactive_navigator(self.proactive_navigator_enabled);
        }
    }

    /// Palette toggle: flip the workspace's pair record and let the next
    /// activation check seat or unseat the pilot (within a second).
    fn toggle_navigator(&mut self) {
        let current = crate::session::read_pair_record(&self.pair_record_path);
        let enabled = !current.as_ref().is_some_and(|r| r.enabled);
        let record = crate::session::PairRecord {
            model: current.as_ref().and_then(|r| r.model.clone()),
            name: current
                .as_ref()
                .map(|r| r.name.clone())
                .unwrap_or_else(|| String::from("claude")),
            enabled,
            task: None,
            // The seat's backend survives an off/on round trip: erasing it
            // silently reseated a local-only navigator on the cloud claude
            // CLI - with a model name claude does not even have.
            provider: current.as_ref().and_then(|r| r.provider.clone()),
            base_url: current.as_ref().and_then(|r| r.base_url.clone()),
        };
        if let Some(dir) = self.pair_record_path.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        match crate::session::write_pair_record(&self.pair_record_path, &record) {
            Ok(()) => {
                self.last_pair_check = None; // act on this tick, not in 1s
                self.status = if enabled {
                    format!("Navigator '{}' activated; seating", record.name)
                } else {
                    String::from("Navigator deactivated; unseating")
                };
            }
            Err(e) => self.status = format!("Navigator toggle failed: {e}"),
        }
    }

    /// Palette: drop every navigator comment — the pilot's anchors, the
    /// per-file snapshots, and the boxes they feed.
    fn clear_navigator_notes(&mut self) {
        if let Some(host) = &self.pair_host {
            host.clear_notes();
        }
        self.navigator_notes.clear();
        self.editor.comment_boxes.clear();
        self.editor.comment_focus = None;
        self.status = String::from("Navigator comments cleared");
    }

    /// F4: focus the active file's next comment box (by row, wrapping),
    /// jumping the caret to its anchor line so the box scrolls into view.
    fn cycle_comment_box(&mut self) {
        let Some((id, row)) = self.next_comment_from_caret() else {
            self.status = String::from("No navigator comments in this file");
            return;
        };
        let row = row.min(self.editor.lines.len().saturating_sub(1));
        let path = self.editor.path.clone().expect("comments imply a file");
        match self.open_at(&path, row, 0) {
            Ok(()) => {
                self.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
                    id,
                    reply: String::new(),
                    cursor: 0,
                });
            }
            Err(e) => self.status = format!("Comment jump failed: {e}"),
        }
    }

    /// Phase D per-tick collab pump (docs/MULTIPLAYER.md): connect lazily,
    /// have guests bootstrap newly opened workspace files, extract local
    /// edits into ops BEFORE applying inbound ones (the echo-storm
    /// invariant), then resolve inbound events against the open buffers.
    fn poll_collab(&mut self) -> bool {
        use crate::collab::{CollabChannel, CollabEvent, CollabRole, CollabSession};
        if self.collab.is_none() {
            let Some((socket, role)) = self.collab_config.clone() else {
                return false;
            };
            // While the link is down there is no doc to converge panes of a
            // shared file through, yet input still reaches the active pane:
            // mirror it onto its siblings so panes cannot diverge
            // independently — the reconnect bootstrap keeps and replays
            // exactly ONE divergent text per file, and a second divergent
            // pane would be silently replaced by the attach pass.
            let mirrored = self.mirror_offline_siblings();
            let due = self
                .last_collab_connect
                .is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(2));
            if !due {
                return mirrored;
            }
            self.last_collab_connect = Some(std::time::Instant::now());
            match CollabChannel::connect(&socket, role) {
                Some(ch) => self.collab = Some(CollabSession::new(ch, collab_display_name())),
                None => return mirrored,
            }
        }
        let mut session = self.collab.take().expect("connected above");
        let root = self.tree.root.clone();
        let mut changed = false;

        // Guests share every text file they open under the workspace; files
        // not open on a peer are ignored until opened, then bootstrapped.
        if session.role == CollabRole::Guest {
            let mut files: Vec<String> = Vec::new();
            let mut collect = |editors: &[crate::widgets::editor::Editor]| {
                for ed in editors {
                    if ed.has_non_text_view() {
                        continue;
                    }
                    if let Some(file) = ed.path.as_ref().and_then(|p| collab_file_key(&root, p)) {
                        files.push(file);
                    }
                }
            };
            collect(&self.editor.editors);
            for group in self.editor_layout.inactive_groups() {
                collect(&group.editors);
            }
            for file in files {
                if !session.is_live(&file) && !session.is_bootstrapping(&file) {
                    session.request_file(&file);
                    changed = true;
                }
            }
        }

        // Invariant 1a: extract-before-apply. Applying remote ops first
        // would re-diff them below as local edits and rebroadcast (echo).
        // Only ATTACHED buffers extract (collab_doc_gen != 0): a buffer
        // created after its file went live — a split duplicate, a reopen —
        // was loaded from the disk copy, which is stale by construction
        // (guests never write shared files). Diffing it against the doc
        // would broadcast a delete-everything/reinsert-the-old-file op set
        // and revert every peer; the attach pass below seeds it instead.
        let mut extract = |editors: &mut [crate::widgets::editor::Editor]| {
            for ed in editors.iter_mut() {
                if ed.has_non_text_view() {
                    continue;
                }
                let Some(file) = ed.path.as_ref().and_then(|p| collab_file_key(&root, p)) else {
                    continue;
                };
                if ed.collab_doc_gen == 0
                    || ed.edit_seq == ed.collab_synced_seq
                    || !session.is_live(&file)
                {
                    continue;
                }
                session.local_change(&file, &ed.lines.join("\n"));
                ed.collab_synced_seq = ed.edit_seq;
                ed.collab_doc_gen = session.doc_gen(&file).unwrap_or(0);
            }
        };
        extract(&mut self.editor.editors);
        for group in self.editor_layout.inactive_groups_mut() {
            extract(&mut group.editors);
        }

        // Invariant 1b: drain and resolve. The owner-side lookup opens the
        // requested file as a background tab when needed, so guest edits
        // land in a real buffer that saves, auto-saves, and reloads through
        // the one code path.
        let events = session.poll(|file| self.owner_buffer_text(&root, file));
        for event in events {
            changed = true;
            match event {
                CollabEvent::RemoteEdit { file, spans } => {
                    let doc_gen = session.doc_gen(&file).unwrap_or(0);
                    self.apply_collab_spans(&root, &file, &spans, doc_gen);
                }
                CollabEvent::Bootstrapped { file, text } => {
                    let doc_gen = session.doc_gen(&file).unwrap_or(0);
                    let owner_text = text.clone();
                    let base = self.collab_offline_base.remove(&file);
                    if let Some(kept) = self.finish_collab_bootstrap(&root, &file, text, doc_gen) {
                        // A buffer diverged while the link was down: replay
                        // the divergence as local edits so the offline work
                        // reaches every peer; the attach pass below re-seeds
                        // the kept panes from the doc once it holds the
                        // replayed text. With a harvested base, only this
                        // side's offline delta replays (three-way against
                        // the owner's snapshot), so owner edits made during
                        // the outage survive.
                        let replay = match base {
                            Some(base) => {
                                crate::collab::merge_offline_texts(&base, &kept, &owner_text)
                            }
                            None => kept,
                        };
                        session.local_change(&file, &replay);
                    }
                }
                CollabEvent::BootstrapTimedOut { file } => {
                    self.status = format!("{file}: no session owner answered; editing locally");
                }
                CollabEvent::Caret {
                    file,
                    site,
                    row,
                    col,
                    name,
                } => {
                    // Truncate at ingest so a peer's name can never paint a
                    // whole row; refresh the fade clock only on real moves
                    // (a re-broadcast of a parked caret keeps its old tag
                    // age, or the tag would never fade).
                    let name: String = name.chars().take(24).collect();
                    let moved = self.collab_carets.get(&site).is_none_or(|c| {
                        c.file != file || c.row != row || c.col != col || c.name != name
                    });
                    if moved {
                        self.collab_carets.insert(
                            site,
                            CollabCaret {
                                file,
                                row,
                                col,
                                name,
                                last_moved: std::time::Instant::now(),
                            },
                        );
                    }
                }
                CollabEvent::StreamState {
                    file,
                    site,
                    name,
                    active,
                } => {
                    // Truncate like caret names: a badge can never paint a
                    // whole status row.
                    let name: String = name.chars().take(24).collect();
                    self.collab_stream = active.then_some(CollabStreamInfo { file, name, site });
                }
                // The cancel request is for the streaming pilot, not for
                // viewers; the badge clears via StreamState(inactive).
                CollabEvent::StreamCancel => {}
            }
        }

        // Attach-and-mirror: a buffer of a live file that has never synced
        // (gen 0: a fresh split duplicate or reopen holding stale disk
        // text) is seeded from the replicated text, and a clean buffer
        // whose generation fell behind (a sibling pane extracted a local
        // edit) mirrors the doc. Every pane of a live file converges every
        // tick — "the first found stays synced" was unstable, because
        // focusing another group reorders which pane is found first, and a
        // behind pane accepting a keystroke would diff its older text
        // against the doc and silently delete the other pane's work.
        let mut attach = |editors: &mut [crate::widgets::editor::Editor]| {
            for ed in editors.iter_mut() {
                // Diff/image/sheet tabs can carry a shared file's path, but
                // their `lines` are not documents: never seed or mark them.
                if ed.has_non_text_view() {
                    continue;
                }
                let Some(file) = ed.path.as_ref().and_then(|p| collab_file_key(&root, p)) else {
                    continue;
                };
                let Some(doc_gen) = session.doc_gen(&file) else {
                    continue;
                };
                if ed.collab_doc_gen == doc_gen
                    || (ed.collab_doc_gen != 0 && ed.edit_seq != ed.collab_synced_seq)
                {
                    continue;
                }
                let text = session
                    .doc_text(&file)
                    .expect("doc_gen implies a live doc")
                    .to_string();
                // The owner's buffer at snapshot creation already IS the
                // doc text: attach without a cursor-jolting replace.
                if ed.lines.join("\n") != text {
                    ed.replace_all_lines(text.split('\n').map(str::to_string).collect());
                    changed = true;
                }
                ed.collab_synced_seq = ed.edit_seq;
                ed.collab_doc_gen = doc_gen;
            }
        };
        attach(&mut self.editor.editors);
        for group in self.editor_layout.inactive_groups_mut() {
            attach(&mut group.editors);
        }

        // Broadcast this participant's caret when it moved in a live file.
        if let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&root, p))
            && session.is_live(&file)
        {
            let caret = (file, self.editor.cursor_row, self.editor.cursor_col);
            if self.collab_caret_sent.as_ref() != Some(&caret) {
                session.send_caret(&caret.0, caret.1, caret.2);
                self.collab_caret_sent = Some(caret);
            }
        }

        if session.disconnected() {
            self.drop_lost_collab_session(session);
            return true;
        }
        self.collab = Some(session);
        changed | self.collab_labels_dirty()
    }

    /// The relay hung up (EOF or a failed write): keeping the dead session
    /// made `is_live` lie forever while every op vanished. Drop it; the
    /// connect path re-attaches (2s backoff) and guest files re-bootstrap
    /// through the normal request path.
    fn drop_lost_collab_session(&mut self, session: crate::collab::CollabSession) {
        // Harvest each live doc's replicated text first: it is the merge
        // base for offline edits at the next bootstrap. Without it, the
        // whole diverged buffer replays and reads the owner's concurrent
        // (unseen) edits as deletions.
        for (file, text) in session.live_texts() {
            self.collab_offline_base.insert(file, text);
        }
        self.status = String::from("Shared session link lost; reconnecting");
    }

    /// One redraw when the set of visible caret name tags changes with no
    /// accompanying wire traffic — i.e. the last tag crossing its 2s fade
    /// window (appearances already redraw via the Caret event itself).
    fn collab_labels_dirty(&mut self) -> bool {
        let now = std::time::Instant::now();
        let any = self
            .collab_carets
            .values()
            .any(|c| now.duration_since(c.last_moved) < CARET_LABEL_FADE);
        let flipped = any != self.collab_labels_visible;
        self.collab_labels_visible = any;
        flipped
    }

    /// Cancel the AI stream (gutter stop button, Cmd+K X, palette): ask the
    /// streaming pilot over the relay to stop and revert. The badge clears
    /// when the pilot broadcasts StreamState(inactive), not optimistically —
    /// the revert is the pilot's to confirm.
    pub fn collab_cancel_stream(&mut self) {
        let Some(stream) = &self.collab_stream else {
            self.status = "No AI stream is active".into();
            return;
        };
        let Some(session) = &mut self.collab else {
            self.status = "No AI stream is active".into();
            return;
        };
        session.send_stream_cancel();
        self.status = format!("Asked {} to stop streaming", stream.name);
    }

    /// The buffer row wearing the gutter stop button: the pilot's ghost
    /// caret row when the streamed file is active here (the button rides
    /// the stream), else the top visible row so the button is always in
    /// view; None when no stream targets the active file.
    fn stream_stop_row(&self) -> Option<usize> {
        let stream = self.collab_stream.as_ref()?;
        let active = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))?;
        if active != stream.file {
            return None;
        }
        Some(
            self.collab_carets
                .get(&stream.site)
                .filter(|c| c.file == stream.file)
                .map(|c| c.row)
                .unwrap_or(self.editor.scroll),
        )
    }

    /// While the collab link is down, mirror the active pane onto its
    /// sibling panes of the same file (nothing else converges them without
    /// a live doc). Input only reaches the active pane, so running this
    /// every tick keeps all panes equal and the reconnect bootstrap sees
    /// exactly one divergent text per file. Only a previously-attached pane
    /// (generation != 0) mirrors out: a fresh reopen's disk text is stale
    /// by construction and would revert siblings still holding session
    /// text.
    fn mirror_offline_siblings(&mut self) -> bool {
        if self.editor.collab_doc_gen == 0 || self.editor.has_non_text_view() {
            return false;
        }
        let Some(path) = self.editor.path.clone() else {
            return false;
        };
        if collab_file_key(&self.tree.root, &path).is_none() {
            return false;
        }
        let lines = self.editor.lines.clone();
        let mut changed = false;
        let mut mirror = |ed: &mut crate::widgets::editor::Editor| {
            if ed.has_non_text_view() {
                return;
            }
            if ed.path.as_deref() != Some(path.as_path()) || ed.lines == lines {
                return;
            }
            ed.replace_all_lines(lines.clone());
            changed = true;
        };
        let active = self.editor.active_index();
        for (i, ed) in self.editor.editors.iter_mut().enumerate() {
            if i != active {
                mirror(ed);
            }
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in group.editors.iter_mut() {
                mirror(ed);
            }
        }
        changed
    }

    /// The owner's current text for a file a guest asked to share: the open
    /// buffer if any, else open it as a background tab (keeping the owner's
    /// focus where it was) and read that. None declines the request
    /// (missing, unreadable, or not a text buffer).
    fn owner_buffer_text(&mut self, root: &Path, file: &str) -> Option<String> {
        let path = crate::collab::contained_path(root, file)?;
        // First TEXT tab with the path: a diff tab of the same file found
        // first must not make the owner decline a share its real buffer
        // could serve.
        let is_text = |ed: &&crate::widgets::editor::Editor| {
            ed.path.as_deref() == Some(path.as_path())
                && ed.diff.is_none()
                && ed.image.is_none()
                && ed.sheet.is_none()
        };
        if let Some(ed) = self.editor.editors.iter().find(is_text) {
            return Some(ed.lines.join("\n"));
        }
        for group in self.editor_layout.inactive_groups() {
            if let Some(ed) = group.editors.iter().find(is_text) {
                return Some(ed.lines.join("\n"));
            }
        }
        if !path.is_file() {
            return None;
        }
        let keep = self.editor.active_index();
        self.editor.open_in_new_tab(&path).ok()?;
        let opened = self.editor.active_index();
        self.editor.select(keep);
        let ed = &self.editor.editors[opened];
        (ed.diff.is_none() && ed.image.is_none() && ed.sheet.is_none()).then(|| ed.lines.join("\n"))
    }

    /// Replay resolved remote spans onto every open buffer for `file`,
    /// converting each byte span to the editor's char coordinates. Spans are
    /// sequential (each relative to the text with earlier ones applied), so
    /// they go through `apply_span_edits` one at a time. Every ATTACHED pane
    /// gets them (attached panes hold identical text, so the byte offsets
    /// are valid in each); a never-attached pane still holds stale disk
    /// text where the offsets would splice garbage — the attach pass seeds
    /// it from the doc instead.
    fn apply_collab_spans(
        &mut self,
        root: &Path,
        file: &str,
        spans: &[crate::collab::ResolvedSpan],
        doc_gen: u64,
    ) {
        let Some(path) = crate::collab::contained_path(root, file) else {
            return;
        };
        // Every matching TEXT tab, not the first tab found by path: a
        // diff/image/sheet tab carries the path too (close-by-path), and a
        // first-found lookup let one shadow the real text tab out of its
        // updates while the spans spliced into a buffer that is not a
        // document.
        let apply = |ed: &mut crate::widgets::editor::Editor| {
            if ed.has_non_text_view() {
                return;
            }
            if ed.collab_doc_gen == 0 {
                return;
            }
            for s in spans {
                let (sr, sc) = crate::collab::position(&ed.lines, s.at);
                let (er, ec) = crate::collab::position(&ed.lines, s.at + s.deleted);
                ed.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
                    start: (sr, sc),
                    end: (er, ec),
                    new_text: s.inserted.clone(),
                }]);
            }
            // Echo suppression: apply_span_edits bumped edit_seq, which would
            // re-arm the tick diff and rebroadcast what was just applied.
            ed.collab_synced_seq = ed.edit_seq;
            ed.collab_doc_gen = doc_gen;
        };
        // A symbol tab is a view over a byte range, so a remote edit moves it
        // too (#369). Outside the closure because the tab belongs to the app
        // rather than to one editor.
        // Only when the tab is anchored to THIS file. The range is a byte
        // offset into one buffer, so an edit to any other file would shift,
        // resize or close it against offsets that mean nothing there — a
        // collaborator typing in `other.rs` would move a tab pointed at
        // `main.rs`, or announce that its symbol is gone.
        if self
            .symbol_tab
            .as_ref()
            .is_some_and(|(_, p, _)| p.as_path() == path)
        {
            for span in spans {
                self.follow_symbol_tab_edit(span.at, span.deleted, span.inserted.len());
            }
        }
        for ed in self.editor.editors.iter_mut() {
            if ed.path.as_deref() == Some(path.as_path()) {
                apply(ed);
            }
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in group.editors.iter_mut() {
                if ed.path.as_deref() == Some(path.as_path()) {
                    apply(ed);
                }
            }
        }
    }

    /// A guest's bootstrap snapshot landed: swap every open buffer for the
    /// file to the owner's canonical text (usually identical to what was
    /// read from disk) and mark them synced, which also lifts the input
    /// gate. A buffer that was already attached to an earlier session
    /// incarnation and diverges from the snapshot holds work made while the
    /// link was down — work that exists nowhere else, so replacing it would
    /// silently delete it. Such a buffer keeps its text and is returned for
    /// the caller to re-inject as local edits (panes converged every tick
    /// before the link died, so any divergent pane carries the same text).
    fn finish_collab_bootstrap(
        &mut self,
        root: &Path,
        file: &str,
        text: String,
        doc_gen: u64,
    ) -> Option<String> {
        let path = crate::collab::contained_path(root, file)?;
        let lines: Vec<String> = text.split('\n').map(str::to_string).collect();
        let mut kept = None;
        let mut finish = |ed: &mut crate::widgets::editor::Editor| {
            if ed.has_non_text_view() {
                return;
            }
            if ed.collab_doc_gen != 0 && ed.lines != lines {
                // Offline divergence: keep the buffer; gen 0 lets the
                // attach pass re-mark it once the doc holds the merged
                // text (the caller's local_change makes them equal).
                if kept.is_none() {
                    kept = Some(ed.lines.join("\n"));
                }
                ed.collab_doc_gen = 0;
                return;
            }
            if ed.lines != lines {
                ed.replace_all_lines(lines.clone());
            }
            ed.collab_synced_seq = ed.edit_seq;
            ed.collab_doc_gen = doc_gen;
        };
        // Every matching TEXT tab (see apply_collab_spans): first-found let
        // a diff tab of the file swallow the snapshot while the text tab
        // went unmarked.
        for ed in self.editor.editors.iter_mut() {
            if ed.path.as_deref() == Some(path.as_path()) {
                finish(ed);
            }
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in group.editors.iter_mut() {
                if ed.path.as_deref() == Some(path.as_path()) {
                    finish(ed);
                }
            }
        }
        self.status = format!("{file} is now live-shared");
        kept
    }

    /// True when this croft is a solo-viewport guest: the session owner is
    /// the one writer of shared files to disk, so every save/reload/replace
    /// path for workspace files is gated here. Config-based (not
    /// connection-based) so the gates hold while the relay is still coming
    /// up.
    fn is_collab_guest(&self) -> bool {
        matches!(
            self.collab_config,
            Some((_, crate::collab::CollabRole::Guest))
        )
    }

    /// Act on the row chosen in the list picker.
    fn confirm_list_picker(&mut self) {
        use crate::widgets::list_picker::ListPurpose;
        let Some(picker) = self.list_picker.as_ref() else {
            return;
        };
        let Some(row) = picker.selected_row().cloned() else {
            return;
        };
        let purpose = picker.purpose;
        self.close_list_picker();
        let index = row.id.parse::<usize>().unwrap_or(0);
        match purpose {
            ListPurpose::StashApply => {
                let r = crate::git::stash_apply(&self.scm_root(), index);
                self.run_scm_op("stash apply", r, "Applied stash");
            }
            ListPurpose::StashPop => {
                let r = crate::git::stash_pop_at(&self.scm_root(), index);
                self.run_scm_op("stash pop", r, "Popped stash");
            }
            ListPurpose::StashDrop => {
                let r = crate::git::stash_drop(&self.scm_root(), index);
                self.run_scm_op("stash drop", r, "Dropped stash");
            }
            ListPurpose::RemoveRemote => {
                let r = crate::git::remove_remote(&self.scm_root(), &row.id);
                self.run_scm_op("remote remove", r, "Removed remote");
            }
            ListPurpose::DeleteTag => {
                let r = crate::git::delete_tag(&self.scm_root(), &row.id);
                self.run_scm_op("tag -d", r, "Deleted tag");
            }
            ListPurpose::PushToRemote => {
                let r = crate::git::push_to_remote(&self.scm_root(), &row.id);
                self.run_scm_op("push", r, "Pushed");
            }
            ListPurpose::MergeConflict => {
                let res = match row.id.as_str() {
                    "current" => crate::merge::Resolution::Current,
                    "both" => crate::merge::Resolution::Both,
                    _ => crate::merge::Resolution::Incoming,
                };
                self.resolve_merge_at_cursor(res);
            }
            ListPurpose::CodeAction => {
                // The navigator row's id is not numeric, and the shared
                // `index` above parses non-numbers to 0 — routing through
                // it would silently apply the server's FIRST action
                // instead. Branch on the id itself (#374 review).
                if row.id == "navigator" {
                    if let Some((path, item)) = self.navigator_fix_candidate() {
                        // The server's titles ride along as hints.
                        let hints = self
                            .pending_code_actions
                            .iter()
                            .map(|a| a.title.clone())
                            .collect();
                        self.fix_problem_with_navigator(path, item, hints);
                    }
                } else if let Some(item) = self.pending_code_actions.get(index).cloned() {
                    self.apply_code_action(item);
                }
                self.pending_code_actions.clear();
            }
            ListPurpose::ColorPresentation => {
                // The edits were computed against a specific buffer state;
                // an external reload while the picker was open orphans
                // them (#277 review) — refuse rather than splice at
                // stale offsets.
                let context_ok = self.pending_color_context.take().is_some_and(|(p, seq)| {
                    self.editor.path.as_deref() == Some(p.as_path()) && self.editor.edit_seq == seq
                });
                if context_ok {
                    if let Some((label, edits)) =
                        self.pending_color_presentations.get(index).cloned()
                    {
                        let applied = self.editor.apply_span_edits(&edits);
                        self.status = if applied > 0 {
                            format!("Color rewritten as {label}")
                        } else {
                            String::from("The presentation's edit no longer applies")
                        };
                    }
                } else {
                    self.status =
                        String::from("The buffer changed — re-run Change Color Presentation");
                }
                self.pending_color_presentations.clear();
            }
            ListPurpose::RunTask => {
                if let Some(task) = self.run_tasks.get(index).cloned() {
                    self.run_project_task(task);
                }
            }
            ListPurpose::DebugConfig => {
                if let Some(idx) = row.id.strip_prefix("compound:") {
                    // Index the row straight through rather than round-tripping
                    // via the name. `discover_compounds` dedupes by name, so a
                    // lookup would find the same element today — but it asks a
                    // weaker question than the one the row already answers, and
                    // it made the not-found arm unreachable-but-present.
                    let found = idx
                        .parse::<usize>()
                        .ok()
                        .and_then(|i| self.debug_compounds.get(i));
                    if let Some(compound) = found {
                        // Resolve first: a compound naming a configuration no
                        // launch.json declares is a config error worth
                        // reporting now, separately from the unbuilt feature.
                        // The un-deduped list: `debug_configs` is the picker's
                        // display list and drops a lower-precedence duplicate by
                        // name, which is the very entry a `.vscode` compound
                        // naming that name has to bind.
                        let all = crate::dap::configs::discover_configs_all(
                            &self.active_workspace_root(),
                        );
                        // #310 defers compounds that need SEVERAL sessions at
                        // once. A compound naming ONE configuration needs one,
                        // which croft has run since #250 — so the arity has to
                        // be READ here rather than assumed. Reporting the
                        // multi-session limit for a one-member compound cites
                        // a limitation that does not apply and tells the user
                        // something false about their own launch.json.
                        match crate::dap::configs::resolve_compound(compound, &all) {
                            Err(e) => self.debug_error(e),
                            // A one-member compound carrying keys croft does
                            // not honour is REFUSED rather than launched.
                            // Since #318 completed, only VALUES croft cannot
                            // READ remain: a `presentation` that is not an
                            // object, or a `hidden`/`group`/`order` that is
                            // not a bool/string/number. Every key that says
                            // something croft can act on is honoured -
                            // `preLaunchTask` by the branch below, `hidden`,
                            // `group` and `order` by the picker's sort.
                            // Launching while ignoring what the compound asked
                            // for is the "silently debug something other than
                            // what was asked for" outcome every guard here
                            // exists to prevent.
                            Ok(members)
                                if members.len() == 1
                                    && !compound.unsupported_keys.is_empty() =>
                            {
                                // #318, NOT #310: this compound needs ONE
                                // session, which croft runs. What it cannot do
                                // is honour the key. Citing the multi-session
                                // limit here would be the same false claim the
                                // launching branch below exists to stop making.
                                //
                                // The remedy names both ways out: fix the
                                // value, or run the member directly. Running
                                // it directly DOES skip the compound's own
                                // preLaunchTask, which the message leaves
                                // unsaid on purpose - a test pins that the
                                // status never mentions preLaunchTask, since
                                // naming it here would read as advice to
                                // accept the skip.
                                // Up to three keys can be listed now, so
                                // "a and b and c" would read as one run-on;
                                // the last pair keeps the "and".
                                let keys = match compound.unsupported_keys.split_last() {
                                    Some((last, [])) => (*last).to_string(),
                                    Some((last, rest)) => {
                                        format!("{} and {last}", rest.join(", "))
                                    }
                                    None => String::new(),
                                };
                                let plural = if compound.unsupported_keys.len() > 1 {
                                    "those keys"
                                } else {
                                    "that key"
                                };
                                self.debug_error(format!(
                                    "compound \"{}\" sets {}, which croft cannot read — fix {} to launch \"{}\" through the compound, or run \"{}\" directly",
                                    compound.name,
                                    keys,
                                    plural,
                                    members[0].name,
                                    members[0].name
                                ));
                            }
                            Ok(members) if members.len() == 1 => {
                                let cfg = members[0].clone();
                                self.selected_debug_config = Some(cfg.name.clone());
                                self.run_debug.selected_config = Some(cfg.name.clone());
                                match compound.pre_launch_task.clone() {
                                    // #318: the compound's own task runs
                                    // first, and the member starts only if it
                                    // exits 0 - the same contract a config's
                                    // own task already gets. Chained rather
                                    // than merged: the member may declare a
                                    // task too, and VS Code runs both.
                                    Some(task) => self.launch_after_compound_task(&task, cfg),
                                    None => self.launch_debug_config(&cfg),
                                }
                            }
                            Ok(_) => self.debug_error(format!(
                                "compound \"{}\" needs several debug sessions at once, which croft does not support yet (#310)",
                                compound.name
                            )),
                        }
                    }
                } else if row.id == "active" {
                    self.selected_debug_config = None;
                    self.run_debug.selected_config = None;
                    self.start_selected_debug();
                } else if let Some(cfg) = row
                    .id
                    .parse::<usize>()
                    .ok()
                    .and_then(|i| self.debug_configs.get(i))
                    .cloned()
                {
                    self.selected_debug_config = Some(cfg.name.clone());
                    self.run_debug.selected_config = Some(cfg.name.clone());
                    self.launch_debug_config(&cfg);
                }
            }
            ListPurpose::SessionParticipant => {
                if let Ok(id) = row.id.parse::<u64>() {
                    self.open_participant_actions(id);
                }
            }
            ListPurpose::SessionParticipantAction => {
                if let Some((verb, id)) = parse_participant_action(&row.id) {
                    self.run_participant_action(verb, id);
                }
            }
            ListPurpose::Settings => {
                match row.id.as_str() {
                    "toggle:format_on_save" => self.toggle_format_on_save(),
                    "toggle:auto_close_pairs" => self.toggle_auto_close_pairs(),
                    "toggle:auto_save" => self.toggle_auto_save(),
                    "toggle:auto_save_on_focus_change" => self.toggle_auto_save_on_focus_change(),
                    "toggle:inline_blame" => self.toggle_inline_blame(),
                    "toggle:indent_guides" => self.toggle_indent_guides(),
                    "toggle:bracket_colors" => self.toggle_bracket_colors(),
                    "toggle:render_whitespace" => self.toggle_render_whitespace(),
                    "toggle:inline_values" => self.toggle_inline_values(),
                    "toggle:inlay_hints" => self.toggle_inlay_hints(),
                    "toggle:copy_on_select" => self.toggle_copy_on_select(),
                    "toggle:log_highlight" => self.toggle_log_highlight(),
                    "toggle:secret_redaction" => self.toggle_secret_redaction(),
                    "toggle:format_on_type" => self.toggle_format_on_type(),
                    "cmd:color_theme" => {
                        self.open_theme_picker();
                        return;
                    }
                    "cmd:open_settings_json" => {
                        self.open_config_file_in_editor(
                            crate::prefs::config_path(),
                            ConfigFileSeed::Settings,
                        );
                        return;
                    }
                    "cmd:open_user_settings_local_json" => {
                        self.open_config_file_in_editor(
                            crate::config_layers::user_local_config_path(),
                            ConfigFileSeed::SettingsLayer,
                        );
                        return;
                    }
                    "cmd:open_workspace_settings_json" => {
                        self.open_workspace_settings(false);
                        return;
                    }
                    "cmd:open_workspace_settings_local_json" => {
                        self.open_workspace_settings(true);
                        return;
                    }
                    "cmd:open_keybindings_json" => {
                        self.open_config_file_in_editor(
                            crate::keymap::keybindings_path(),
                            ConfigFileSeed::Keybindings,
                        );
                        return;
                    }
                    "cmd:configure_snippets" => {
                        self.open_config_file_in_editor(
                            crate::snippets::snippets_path(),
                            ConfigFileSeed::Snippets,
                        );
                        return;
                    }
                    _ => return,
                }
                // A toggle stays in the hub: reopen so the new value shows and
                // the user can flip more without reinvoking the palette.
                self.open_settings_view();
            }
        }
    }

    /// Preferences: Open Settings — a searchable hub over the toggleable
    /// settings plus shortcuts to the raw JSON files and the theme picker. Each
    /// toggle row shows its current value; confirming a toggle flips it live and
    /// reopens the hub so the change is visible and more can be flipped.
    pub fn open_settings_view(&mut self) {
        use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
        let on_off = |b: bool| if b { "on" } else { "off" };
        // Per-value provenance (#251): where a non-user layer set the backing
        // key, say so — the usual "I toggled it and nothing changed" is a
        // workspace layer winning the merge.
        let prov = |key: &str| {
            use crate::config_layers::LayerKind;
            match crate::config_layers::layer_of(&self.settings_provenance, key) {
                LayerKind::Default | LayerKind::User => String::new(),
                other => format!("  · {}", other.label()),
            }
        };
        let rows = vec![
            ListRow {
                id: String::from("toggle:auto_close_pairs"),
                label: format!(
                    "Auto Closing Pairs: {}{}",
                    on_off(self.auto_close_pairs),
                    prov("disable_auto_close_pairs")
                ),
            },
            ListRow {
                id: String::from("toggle:format_on_save"),
                label: format!(
                    "Format on Save: {}{}",
                    on_off(self.format_on_save),
                    prov("format_on_save")
                ),
            },
            ListRow {
                id: String::from("toggle:auto_save"),
                label: format!("Auto Save: {}{}", on_off(self.auto_save), prov("auto_save")),
            },
            ListRow {
                id: String::from("toggle:auto_save_on_focus_change"),
                label: format!(
                    "Auto Save on Focus Change: {}{}",
                    on_off(self.auto_save_on_focus_change),
                    prov("auto_save_on_focus_change")
                ),
            },
            ListRow {
                id: String::from("toggle:inline_blame"),
                label: format!(
                    "Git: Inline Blame: {}{}",
                    on_off(self.inline_blame_enabled),
                    prov("disable_inline_blame")
                ),
            },
            ListRow {
                id: String::from("toggle:indent_guides"),
                label: format!(
                    "Editor: Indent Guides: {}{}",
                    on_off(self.indent_guides_enabled),
                    prov("disable_indent_guides")
                ),
            },
            ListRow {
                id: String::from("toggle:bracket_colors"),
                label: format!(
                    "Editor: Bracket Pair Colorization: {}{}",
                    on_off(self.bracket_colors_enabled),
                    prov("disable_bracket_colors")
                ),
            },
            ListRow {
                id: String::from("toggle:render_whitespace"),
                label: format!(
                    "Editor: Render Whitespace: {}{}",
                    self.whitespace_mode.label(),
                    prov("render_whitespace")
                ),
            },
            ListRow {
                id: String::from("toggle:inline_values"),
                label: format!(
                    "Debugger: Inline Values: {}{}",
                    on_off(self.inline_values_enabled),
                    prov("disable_inline_values")
                ),
            },
            ListRow {
                id: String::from("toggle:inlay_hints"),
                label: format!(
                    "Editor: Inlay Hints: {}{}",
                    on_off(self.inlay_hints_enabled),
                    prov("disable_inlay_hints")
                ),
            },
            ListRow {
                id: String::from("toggle:format_on_type"),
                label: format!(
                    "Editor: Format on Type: {}{}",
                    on_off(self.format_on_type),
                    prov("format_on_type")
                ),
            },
            ListRow {
                id: String::from("toggle:copy_on_select"),
                label: format!(
                    "Terminal: Copy on Selection: {}{}",
                    on_off(self.copy_on_select),
                    prov("copy_on_select")
                ),
            },
            ListRow {
                id: String::from("toggle:log_highlight"),
                label: format!(
                    "Log: Highlighting (tailspin): {}{}",
                    on_off(self.log_highlight),
                    prov("disable_log_highlight")
                ),
            },
            ListRow {
                id: String::from("toggle:secret_redaction"),
                label: format!(
                    "Terminal: Redact Secrets (keys, tokens): {}{}",
                    on_off(self.secret_redaction),
                    prov("disable_secret_redaction")
                ),
            },
            ListRow {
                id: String::from("cmd:color_theme"),
                label: format!("Color Theme: {}{}", self.theme.label(), prov("theme")),
            },
            ListRow {
                id: String::from("cmd:open_settings_json"),
                label: String::from("Open User Settings (JSON)"),
            },
            ListRow {
                id: String::from("cmd:open_user_settings_local_json"),
                label: String::from("Open User Settings — Local (JSON, this machine only)"),
            },
            ListRow {
                id: String::from("cmd:open_workspace_settings_json"),
                label: String::from("Open Workspace Settings (JSON)"),
            },
            ListRow {
                id: String::from("cmd:open_workspace_settings_local_json"),
                label: String::from("Open Workspace Settings — Local (JSON, gitignored)"),
            },
            ListRow {
                id: String::from("cmd:open_keybindings_json"),
                label: String::from("Open Keyboard Shortcuts (JSON)"),
            },
            ListRow {
                id: String::from("cmd:configure_snippets"),
                label: String::from("Configure User Snippets"),
            },
        ];
        self.open_list_picker(
            ListPicker::new(ListPurpose::Settings, "Settings", rows),
            "No settings",
        );
    }

    /// Preferences: Open Workspace Settings (#251) — the committed
    /// `.croft/config.json`, or with `local` the gitignored
    /// `.croft/config.local.json`. Creating either ensures
    /// `.croft/.gitignore` covers the local file first, so a personal
    /// override can never land in a commit by accident.
    pub fn open_workspace_settings(&mut self, local: bool) {
        let root = self.roots.primary().to_path_buf();
        if let Err(e) = crate::config_layers::ensure_workspace_local_ignored(&root) {
            self.status = format!("Could not prepare .croft/: {e}");
            return;
        }
        let path = if local {
            crate::config_layers::workspace_local_config_path(&root)
        } else {
            crate::config_layers::workspace_config_path(&root)
        };
        self.open_config_file_in_editor(path, ConfigFileSeed::SettingsLayer);
    }

    /// Tasks: Run Task — discover the workspace's tasks and open the
    /// picker over them.
    pub fn open_run_task_picker(&mut self) {
        self.run_tasks = crate::tasks::discover_tasks(&self.active_workspace_root());
        let rows: Vec<crate::widgets::list_picker::ListRow> = self
            .run_tasks
            .iter()
            .enumerate()
            .map(|(i, t)| crate::widgets::list_picker::ListRow {
                id: i.to_string(),
                label: format!("{} — {}", t.label, t.source),
            })
            .collect();
        self.open_list_picker(
            crate::widgets::list_picker::ListPicker::new(
                crate::widgets::list_picker::ListPurpose::RunTask,
                "Run Task",
                rows,
            ),
            "No tasks found (Makefile, justfile, package.json, Cargo.toml, pyproject.toml, .vscode/tasks.json)",
        );
    }

    /// Run `task` in its own named terminal pane. Rerunning a task whose
    /// pane sits idle at a prompt writes the command into that pane
    /// instead of stacking a new one; a busy pane gets a fresh sibling.
    /// Run a task in its named pane. Returns the pane's uid so a caller can
    /// correlate the task's FinishedCommand (the preLaunchTask gate, #250);
    /// `None` when no pane could be started (already reported in `status`).
    pub fn run_project_task(&mut self, task: crate::tasks::Task) -> Option<u64> {
        let pane_name = format!("Task: {}", task.label);
        // The task's problemMatcher (#252), translated up front so both the
        // reuse and fresh-pane paths assign the same thing (or clear a
        // previous task's leftover).
        let matcher = task
            .problem_matcher
            .as_ref()
            .and_then(crate::problem_matchers::from_tasks_json)
            .map(std::sync::Arc::new);
        // Ctrl-E + Ctrl-U first: the idle shell's line editor may hold a
        // half-typed command that would otherwise concatenate and run
        // (same rule `format_cd_command` pins for the cd seed).
        let command = format!("\x05\x15{}\r", task.command);
        self.last_task = Some(task.clone());
        // Reuse only a pane whose shell is standing exactly where this
        // task will run: after a re-root the old pane's label still
        // matches, and running the new project's build there builds the
        // old one. Shares `pane_is_idle_at` with the runnable-fence path
        // (#430) — this guard existed twice and only one copy was fixed,
        // which is precisely how the two defects survived a green suite.
        let active = self.active_workspace_root();
        let root = active.canonicalize().unwrap_or(active);
        if let Some(idx) = self
            .terminals
            .iter()
            .position(|t| pane_is_idle_at(t, &pane_name, &root))
        {
            // Reused panes may be folded (#313): the release notes name the
            // build pane as the thing you would fold, and a task written into
            // a pane that is never rendered runs invisibly under a status line
            // saying it started.
            self.reveal_terminal_pane(idx);
            self.terminals[idx].write_input(command.as_bytes());
            self.show_terminal = true;
            self.focus_pane(Pane::Terminal);
            self.status = format!("Running {}", task.label);
            let uid = self.terminals[idx].uid();
            self.assign_task_matcher(uid, matcher);
            return Some(uid);
        }
        match crate::widgets::terminal::PtyTerminal::new(&self.active_workspace_root()) {
            Ok(mut term) => {
                term.set_manual_name(Some(pane_name));
                term.write_input(command.as_bytes());
                let uid = term.uid();
                self.insert_terminal(term);
                self.assign_task_matcher(uid, matcher);
                self.status = format!("Running {}", task.label);
                Some(uid)
            }
            Err(e) => {
                self.status = format!("Could not start task pane: {e}");
                None
            }
        }
    }

    /// Record (or clear) the problemMatcher owning a task pane (#252): the
    /// map drives the batch scan at the FinishedCommand boundary, the
    /// pane's watch slot drives the mid-run engine when the matcher is a
    /// background one. Rerunning a matcher-less task in a pane clears the
    /// previous task's leftover, and either way the pane starts the new
    /// run without a stale watch-published flag.
    fn assign_task_matcher(
        &mut self,
        pane: u64,
        matcher: Option<std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
    ) {
        self.watch_published_panes.remove(&pane);
        match &matcher {
            Some(m) => {
                self.task_matcher_by_pane.insert(pane, m.clone());
            }
            None => {
                self.task_matcher_by_pane.remove(&pane);
            }
        }
        if let Some(t) = self.terminals.iter().find(|t| t.uid() == pane) {
            t.set_pane_watch(matcher.filter(|m| m.background.is_some()));
        }
    }

    /// Tasks: Run Build Task (`Cmd+Shift+B`) — run the conventional build
    /// for whatever the workspace is; fall back to the picker when no
    /// manifest declares one.
    pub fn run_build_task(&mut self) {
        let tasks = crate::tasks::discover_tasks(&self.active_workspace_root());
        match crate::tasks::default_build_task(&tasks).cloned() {
            Some(task) => {
                self.run_project_task(task);
            }
            None => {
                self.open_run_task_picker();
                self.status = "No build task detected; pick one".to_string();
            }
        }
    }

    /// Tasks: Rerun Last Task.
    pub fn rerun_last_task(&mut self) {
        match self.last_task.clone() {
            Some(task) => {
                self.run_project_task(task);
            }
            None => self.status = "No task has run yet".to_string(),
        }
    }

    /// Resolve the branch-picker selection per its open purpose.
    fn apply_branch_picker_selection(&mut self) {
        let Some(picker) = self.branch_picker.as_ref() else {
            return;
        };
        match self.branch_purpose {
            BranchPurpose::Checkout => {
                if let Some(action) = picker.selected_action() {
                    self.apply_branch_action(action);
                } else {
                    self.close_branch_picker();
                }
            }
            BranchPurpose::CreateFrom => {
                let Some(base) = picker.selected_existing_branch() else {
                    return;
                };
                self.close_branch_picker();
                self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
                    crate::widgets::input_prompt::InputPurpose::CreateBranchFrom { base },
                    "Create Branch from",
                    "New branch name",
                ));
            }
            BranchPurpose::Delete => {
                let Some(name) = picker.selected_existing_branch() else {
                    return;
                };
                self.close_branch_picker();
                let r = crate::git::delete_branch(&self.scm_root(), &name);
                self.run_scm_op("branch -d", r, "Deleted branch");
            }
            BranchPurpose::Merge => {
                let Some(name) = picker.selected_existing_branch() else {
                    return;
                };
                self.close_branch_picker();
                let r = crate::git::merge_branch(&self.scm_root(), &name);
                self.run_scm_op("merge", r, "Merged");
            }
            BranchPurpose::Rebase => {
                let Some(name) = picker.selected_existing_branch() else {
                    return;
                };
                self.close_branch_picker();
                let r = crate::git::rebase_branch(&self.scm_root(), &name);
                self.run_scm_op("rebase", r, "Rebased");
            }
        }
    }

    /// Open the staged-changes diff (`git diff --staged`) in a read-only
    /// editor tab. Mirrors VS Code's "View Staged Changes" — users hit
    /// the dropdown, click View Staged Changes, and the editor tab pops up
    /// with every `+`/`-` line of the staged hunks highlighted.
    pub fn view_staged_diff_source_control(&mut self) {
        let raw = match crate::git::diff_staged(&self.scm_root()) {
            Ok(r) => r,
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("diff failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("View Staged Changes failed: {err}");
                return;
            }
        };
        let label = std::path::PathBuf::from("git diff --staged");
        if let Err(err) = self.editor.open_git_diff_side_by_side(&label, &raw) {
            self.source_control.commit_feedback = Some(format!("open failed: {err}"));
            self.source_control.commit_feedback_is_error = true;
            self.status = format!("Could not open staged diff: {err}");
            return;
        }
        self.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
            root: self.scm_root(),
            kind: crate::widgets::diff::GitDiffKind::Staged,
        });
        self.source_control.commit_feedback = None;
        self.status = String::from("Showing git diff --staged");
        self.focus_pane(Pane::Editor);
    }

    /// Open `git diff <default-branch>` in a read-only editor tab. The
    /// default branch is resolved via `git::default_branch` (origin/HEAD
    /// first, then common local names). If resolution fails the error
    /// surfaces in the commit-feedback line so the user can fix the
    /// upstream-HEAD config instead of getting a silent no-op.
    pub fn view_default_branch_diff_source_control(&mut self) {
        let branch = match crate::git::default_branch(&self.scm_root()) {
            Ok(b) => b,
            Err(err) => {
                self.source_control.commit_feedback = Some(err.clone());
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Default branch: {err}");
                return;
            }
        };
        let raw = match crate::git::diff_against_branch(&self.scm_root(), &branch) {
            Ok(r) => r,
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("diff failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("View Changes vs {branch} failed: {err}");
                return;
            }
        };
        let label = std::path::PathBuf::from(format!("git diff {branch}"));
        if let Err(err) = self.editor.open_git_diff_side_by_side(&label, &raw) {
            self.source_control.commit_feedback = Some(format!("open failed: {err}"));
            self.source_control.commit_feedback_is_error = true;
            self.status = format!("Could not open diff vs {branch}: {err}");
            return;
        }
        self.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
            root: self.scm_root(),
            kind: crate::widgets::diff::GitDiffKind::AgainstBranch(branch.clone()),
        });
        self.default_branch_label = Some(branch.clone());
        self.source_control.commit_feedback = None;
        self.status = format!("Showing git diff {branch}");
        self.focus_pane(Pane::Editor);
    }

    /// Open `git diff HEAD~1` (working tree versus the commit before HEAD)
    /// in a read-only editor tab. Mirrors "View Changes vs <default>" but
    /// anchored on the previous commit, so the user can review everything
    /// that changed since the last commit. A single-commit repo has no
    /// `HEAD~1`; that error surfaces in the commit-feedback line rather
    /// than as a silent no-op.
    pub fn view_previous_commit_diff_source_control(&mut self) {
        let raw = match crate::git::diff_previous_commit(&self.scm_root()) {
            Ok(r) => r,
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("diff failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("View Changes vs previous failed: {err}");
                return;
            }
        };
        let label = std::path::PathBuf::from("git diff HEAD~1");
        if let Err(err) = self.editor.open_git_diff_side_by_side(&label, &raw) {
            self.source_control.commit_feedback = Some(format!("open failed: {err}"));
            self.source_control.commit_feedback_is_error = true;
            self.status = format!("Could not open diff vs previous: {err}");
            return;
        }
        self.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
            root: self.scm_root(),
            kind: crate::widgets::diff::GitDiffKind::PreviousCommit,
        });
        self.source_control.commit_feedback = None;
        self.status = String::from("Showing git diff HEAD~1");
        self.focus_pane(Pane::Editor);
    }

    pub fn commit_and_push_source_control(&mut self) {
        let message = self.source_control.message.trim().to_string();
        if message.is_empty() {
            self.source_control.commit_feedback = Some(String::from("Empty commit message"));
            self.source_control.commit_feedback_is_error = true;
            return;
        }
        let commit_summary = match crate::git::commit_all_tracked(&self.scm_root(), &message) {
            Ok(s) => s,
            Err(err) => {
                self.source_control.commit_feedback = Some(err.clone());
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Commit failed: {err}");
                return;
            }
        };
        self.source_control.clear_message();
        self.status = format!("Committed: {commit_summary}");
        match crate::git::push_current_branch(&self.scm_root()) {
            Ok(push_summary) => {
                let combined = if push_summary.is_empty() {
                    commit_summary
                } else {
                    format!("{commit_summary} | pushed: {push_summary}")
                };
                self.source_control.commit_feedback = Some(combined.clone());
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("Committed & pushed: {combined}");
            }
            Err(err) => {
                self.source_control.commit_feedback =
                    Some(format!("commit ok; push failed: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Commit ok; push failed: {err}");
            }
        }
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    pub fn stage_source_control_entry(&mut self, entry_idx: usize) {
        let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
            return;
        };
        match crate::git::stage_path(&self.scm_root(), &entry.path) {
            Ok(()) => {
                self.status = format!("Staged {}", entry.path);
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
            }
            Err(err) => {
                self.status = format!("Stage failed: {err}");
                self.source_control.commit_feedback = Some(err);
                self.source_control.commit_feedback_is_error = true;
            }
        }
    }

    /// The workspace-relative path + single-hunk patch for the hunk under
    /// the diff caret. Sets a status message and returns `None` when the
    /// active tab isn't a working-tree diff or no hunk is at the cursor.
    fn diff_hunk_patch_at_caret(&mut self) -> Option<(String, String)> {
        let root = self.tree.root.clone();
        let built = match self.editor.diff.as_ref() {
            None => Err("Hunk actions work inside a Source Control diff"),
            Some(diff) if !diff.left_is_git_head => {
                Err("Hunk actions need a working-tree diff from Source Control")
            }
            Some(diff) => match diff.right_path.strip_prefix(&root) {
                Err(_) => Err("File is outside the workspace"),
                Ok(rel) => {
                    let rel = rel.to_string_lossy().to_string();
                    match diff.hunk_range_at(diff.action_row()) {
                        None => Err("No change hunk at the cursor"),
                        Some(range) => {
                            let patch = diff.hunk_patch(&rel, range);
                            Ok((rel, patch))
                        }
                    }
                }
            },
        };
        match built {
            Ok(pair) => Some(pair),
            Err(msg) => {
                self.status = msg.to_string();
                None
            }
        }
    }

    /// The workspace-relative path + patch for the SELECTED lines of the
    /// open working-tree diff (VS Code's "Stage Selected Ranges"), or
    /// `None` when there is no selection spanning a changed row, so the
    /// caller falls back to the whole-hunk action.
    fn diff_selected_lines_patch(&self) -> Option<(String, String)> {
        let root = self.tree.root.clone();
        let diff = self.editor.diff.as_ref()?;
        if !diff.left_is_git_head {
            return None;
        }
        let sel = diff.selection?;
        if !sel.has_area() {
            return None;
        }
        let rel = diff.right_path.strip_prefix(&root).ok()?;
        let rel = rel.to_string_lossy().to_string();
        let (start, end) = sel.normalized();
        let patch = diff.selected_lines_patch(&rel, (start.0, end.0))?;
        Some((rel, patch))
    }

    /// Cycle the open diff's ignore-whitespace mode (off → leading → all).
    /// Per-view only: the `diff_ignore_whitespace` pref supplies the starting
    /// mode for each new diff and is not rewritten here, so an experiment in
    /// one view never changes what the next file opens with.
    pub fn diff_cycle_whitespace_mode(&mut self) {
        let Some(diff) = self.editor.diff.as_mut() else {
            self.status = String::from("Ignore whitespace applies to a diff view");
            return;
        };
        let mode = diff.ws_mode.next();
        diff.set_whitespace_mode(mode);
        self.status = format!("Diff: ignore whitespace {}", mode.label());
    }

    /// Turn the group-by-seat lens on or off for the diff in view (#349),
    /// so a change can be read as "the agent's part" and "my part".
    ///
    /// Offered only on the Source Control HEAD-vs-working view, the one diff
    /// whose right side IS the working tree: there the row's `right` index
    /// is a real file line and the seat map is keyed on the same index. A
    /// diff parsed out of raw `git diff` text numbers its rows by position
    /// in that text, so the same join would paint confident wrong seats.
    pub fn diff_toggle_group_by_seat(&mut self) {
        let history_root = self.history_root.clone();
        let Some(diff) = self.editor.diff.as_mut() else {
            self.status = String::from("Group by seat applies to a diff view");
            return;
        };
        if !diff.left_is_git_head {
            self.status =
                String::from("Group by seat applies to a Source Control diff of the working tree");
            return;
        }
        diff.group_by_seat = !diff.group_by_seat;
        if !diff.group_by_seat {
            self.status = String::from("Diff: group by seat off");
            return;
        }
        // Read the map fresh each time the lens comes on: the working file
        // may have been saved since the view was built, and a map from
        // before that describes text this diff no longer shows.
        diff.seats = crate::provenance::Provenance::new();
        let path = diff.right_path.clone();
        let right_lines = diff.right_lines.clone();
        let seats = Self::seats_for_working_file(&history_root, &path, &right_lines);
        let Some(diff) = self.editor.diff.as_mut() else {
            return;
        };
        if let Some(seats) = seats {
            diff.seats = seats;
        }
        self.status = format!("Diff: group by seat \u{2022} {}", diff.seat_summary());
    }

    /// Reload the group-by-seat map of a rebuilt view against its new rows
    /// (#349). `carry_view_from` keeps the lens ON but deliberately drops
    /// its map, which named line indices the rebuilt rows have renumbered;
    /// this puts back a map that describes the rows now on screen, or none.
    /// A no-op for a view whose lens is off.
    fn reload_seats_for(history_root: &Path, diff: &mut crate::widgets::diff::DiffData) {
        // The same gate the toggle applies, restated rather than assumed:
        // the map is keyed on working-file line indices, so it may only be
        // joined onto a view whose right side IS the working tree.
        if !diff.group_by_seat || !diff.left_is_git_head {
            return;
        }
        let right_lines = diff.right_lines.clone();
        diff.seats = Self::seats_for_working_file(history_root, &diff.right_path, &right_lines)
            .unwrap_or_default();
    }

    /// The persisted provenance map for a working-tree file, for the rows a
    /// diff view is actually showing (#349). Both halves of the rule
    /// `sync_provenance_for` applies: the newest snapshot must still hold the
    /// bytes on disk, AND those bytes must be the lines this view shows.
    ///
    /// The second half is not redundant. A diff's `right_lines` were read
    /// when the view was built, and a same-length rewrite inside one
    /// filesystem timestamp tick moves the file without moving the
    /// `(mtime, len)` stamp that triggers a rebuild - so the view can be
    /// showing older lines than the snapshot describes. Joining a newer map
    /// onto them would credit lines it never saw, which is the one outcome
    /// the module forbids. Either half failing reads as no map at all.
    fn seats_for_working_file(
        history_root: &Path,
        path: &Path,
        right_lines: &[String],
    ) -> Option<crate::provenance::Provenance> {
        let newest = crate::history::entries_in(history_root, path)
            .into_iter()
            .next()?;
        let mut seats = crate::history::seats_for(history_root, path, newest.millis)?;
        let (on_disk, snapshot) = (std::fs::read(path).ok()?, std::fs::read(&newest.file).ok()?);
        if on_disk != snapshot {
            return None;
        }
        // Split the way the DIFF OPENER splits (`str::lines`), NOT the way
        // `Editor::open` does: a lone `\r` is one line to the opener and two
        // to the editor's splitter, and the comparison has to be against the
        // lines this view was actually built from. The bare UTF-8 decode
        // matches the opener too, which reads the right side with
        // `read_to_string` and so never builds a view for a file this
        // cannot decode.
        let text = String::from_utf8(snapshot).ok()?;
        if !text.lines().eq(right_lines.iter().map(String::as_str)) {
            return None;
        }
        // Defensive: the comparison above already forces equal lengths, so
        // this drops nothing today. It keeps the map bounded by the rows if
        // that gate is ever loosened.
        seats.truncate(right_lines.len());
        Some(seats)
    }

    /// Stage only the hunk under the diff caret (`git apply --cached`).
    pub fn stage_hunk_at_caret(&mut self) {
        // A selection spanning changed rows narrows the action to those
        // lines (VS Code's "Stage Selected Ranges"); without one the whole
        // hunk under the caret is staged, as before.
        if let Some((rel, patch)) = self.diff_selected_lines_patch() {
            match crate::git::apply_patch(&self.scm_root(), &patch, true, false) {
                Ok(_) => {
                    self.status = format!("Staged selected lines in {rel}");
                    self.refresh_after_hunk_op();
                }
                Err(err) => self.status = format!("Stage selected lines failed: {err}"),
            }
            return;
        }
        let Some((rel, patch)) = self.diff_hunk_patch_at_caret() else {
            return;
        };
        match crate::git::apply_patch(&self.scm_root(), &patch, true, false) {
            Ok(_) => {
                self.status = format!("Staged hunk in {rel}");
                self.refresh_after_hunk_op();
            }
            Err(err) => self.status = format!("Stage hunk failed: {err}"),
        }
    }

    /// Remove only the hunk under the diff caret from the index
    /// (`git apply --cached -R`). Errors surface verbatim, e.g. when the
    /// hunk was never staged.
    pub fn unstage_hunk_at_caret(&mut self) {
        // Same selection-first rule as staging: the reverse patch removes
        // exactly the selected lines from the index.
        if let Some((rel, patch)) = self.diff_selected_lines_patch() {
            match crate::git::apply_patch(&self.scm_root(), &patch, true, true) {
                Ok(_) => {
                    self.status = format!("Unstaged selected lines in {rel}");
                    self.refresh_after_hunk_op();
                }
                Err(err) => self.status = format!("Unstage selected lines failed: {err}"),
            }
            return;
        }
        let Some((rel, patch)) = self.diff_hunk_patch_at_caret() else {
            return;
        };
        match crate::git::apply_patch(&self.scm_root(), &patch, true, true) {
            Ok(_) => {
                self.status = format!("Unstaged hunk in {rel}");
                self.refresh_after_hunk_op();
            }
            Err(err) => self.status = format!("Unstage hunk failed: {err}"),
        }
    }

    /// Arm the revert-hunk confirm popup for the hunk under the caret.
    pub fn request_revert_hunk_at_caret(&mut self) {
        if let Some((rel_path, patch)) = self.diff_hunk_patch_at_caret() {
            self.pending_revert_hunk = Some(PendingRevertHunk { rel_path, patch });
        }
    }

    pub fn confirm_pending_revert_hunk(&mut self) {
        let Some(pr) = self.pending_revert_hunk.take() else {
            return;
        };
        match crate::git::apply_patch(&self.scm_root(), &pr.patch, false, true) {
            Ok(_) => {
                self.status = format!("Reverted hunk in {}", pr.rel_path);
                self.refresh_after_hunk_op();
                // The revert rewrote the working file; force the HEAD-side rebuild
                // of the open view so it refreshes even if the rewrite landed
                // within the stamp's granularity. Forced by the root the VIEW is
                // tagged with, not `scm_root()` re-read now: the tag may predate the
                // worker's first status reply and hold the workspace root.
                let force_root = self
                    .editor
                    .diff
                    .as_ref()
                    .and_then(|d| match &d.source {
                        crate::widgets::diff::DiffSource::HeadVsWorking { root, .. } => {
                            Some(root.clone())
                        }
                        _ => None,
                    })
                    .unwrap_or_else(|| self.scm_root());
                self.refresh_open_diff_views(
                    true,
                    std::slice::from_ref(&force_root),
                    &std::collections::BTreeSet::new(),
                );
            }
            Err(err) => self.status = format!("Revert hunk failed: {err}"),
        }
    }

    pub fn cancel_pending_revert_hunk(&mut self) {
        self.pending_revert_hunk = None;
    }

    fn refresh_after_hunk_op(&mut self) {
        self.active_git_bypass_debounce();
        self.refresh_git_status_debounced();
        self.refresh_source_control();
    }

    /// Record on the diff view the opener just made active how it is to be
    /// rebuilt when a side moves (#471), and take its first disk stamps.
    fn tag_open_diff(&mut self, source: crate::widgets::diff::DiffSource) {
        if let Some(diff) = self.editor.diff.as_mut() {
            diff.source = source;
            diff.stamp_sides();
        }
    }

    /// Rebuild every open diff view, in every split group, whose sides may
    /// have moved (#471), keeping each reader's viewport. Returns true when
    /// any view's content actually changed, so the caller owes a redraw.
    ///
    /// Two triggers, two costs. A filesystem event or poll (`git_too` false)
    /// re-reads only file-backed sides, and only those whose stat stamp
    /// moved, so an idle tick is a stat per open diff and nothing more. A
    /// git-status drain (`git_too` true; the worker debounces it) also
    /// re-runs the `git diff` behind a staged / branch / previous-commit
    /// view, whose input is the index or a ref rather than a file, and
    /// re-reads the HEAD blob behind a Source Control view for the roots in
    /// `heads_moved` -- the drain already knows whose HEAD oid changed, and
    /// a `git show` per open diff per status refresh would otherwise run
    /// during every write burst for a HEAD that had not moved.
    /// A view whose content came back identical is left untouched: no reset
    /// of selection or find, no redraw.
    pub fn refresh_open_diff_views(
        &mut self,
        git_too: bool,
        heads_moved: &[PathBuf],
        changed_files: &std::collections::BTreeSet<PathBuf>,
    ) -> bool {
        // Bound before the borrow of `self.editor` below, for the seat map a
        // carried group-by-seat lens needs against its rebuilt rows (#349).
        let self_history_root = self.history_root.clone();
        // The watcher's own list of written paths bypasses the stamp gate: a
        // same-length rewrite that lands within the filesystem's mtime
        // granularity (or restores the mtime) shows the same `(mtime, len)`
        // as before, and the event is the only evidence it happened.
        // Canonicalised once, so a path the watcher reports through a
        // symlinked root (macOS's /tmp -> /private/tmp) still matches the
        // path the view was opened with.
        let touched: Vec<PathBuf> = changed_files
            .iter()
            .map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.clone()))
            .collect();
        let mut changed = false;
        // The active group's active tab, by address: a rebuild there is the
        // one that owes the find bar a recompute. A diff refreshing in a
        // background tab or split must not touch the view the reader is on.
        let active_ptr: *const crate::widgets::editor::Editor = &*self.editor;
        let mut active_changed = false;
        for group in
            std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut())
        {
            for ed in &mut group.editors {
                let Some(old) = ed.diff.as_ref() else {
                    continue;
                };
                let Some(mut fresh) = rebuild_diff_view(old, git_too, heads_moved, &touched) else {
                    continue;
                };
                if fresh.same_content_as(old) {
                    // Same rows: keep the reader's selection and find
                    // state, but take the new stamps so the next tick does
                    // not re-read the file again for a no-op write.
                    if let Some(cur) = ed.diff.as_mut() {
                        cur.left_stamp = fresh.left_stamp;
                        cur.right_stamp = fresh.right_stamp;
                    }
                    continue;
                }
                fresh.carry_view_from(old);
                // The carried lens needs a map for the REBUILT rows:
                // `carry_view_from` deliberately drops the old one, which
                // named lines these rows have renumbered (#349).
                Self::reload_seats_for(&self_history_root, &mut fresh);
                ed.diff = Some(fresh);
                changed = true;
                if std::ptr::eq(&*ed, active_ptr) {
                    active_changed = true;
                }
            }
        }
        // A rebuilt ACTIVE diff with a find bar open gets its match set and
        // active match recomputed against the new rows, the same way a
        // typed query would; `carry_view_from` deliberately dropped the old
        // active match because it named rows that may be gone.
        if active_changed
            && self.editor.diff.is_some()
            && self
                .editor_find
                .as_ref()
                .is_some_and(|s| !s.query.is_empty())
        {
            let pos = self.diff_find_current_pos();
            self.diff_find_apply(pos);
        }
        changed
    }

    pub fn request_discard_source_control_entry(&mut self, entry_idx: usize) {
        use crate::git::ChangeKind;
        let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
            return;
        };
        let untracked = matches!(entry.kind, ChangeKind::Untracked);
        self.pending_discard = Some(PendingDiscard {
            rel_path: entry.path,
            untracked,
        });
    }

    pub fn confirm_pending_discard(&mut self) {
        let Some(pd) = self.pending_discard.take() else {
            return;
        };
        match crate::git::discard_path(&self.scm_root(), &pd.rel_path, pd.untracked) {
            Ok(()) => {
                self.status = format!("Discarded {}", pd.rel_path);
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
            }
            Err(err) => {
                self.status = format!("Discard failed: {err}");
                self.source_control.commit_feedback = Some(err);
                self.source_control.commit_feedback_is_error = true;
            }
        }
    }

    pub fn cancel_pending_discard(&mut self) {
        self.pending_discard = None;
    }

    /// Decide whether to show the unsupported-terminal nudge. Call AFTER
    /// `init_graphics` has resolved `inline_protocol` (including the sixel
    /// promotion), so a sixel host is correctly treated as supported. No-op
    /// when the user has already silenced the nudge in their prefs.
    fn arm_terminal_warning(&mut self) {
        if crate::prefs::Prefs::load_or_default().suppress_terminal_warning {
            return;
        }
        self.pending_terminal_warning = crate::iterm2_inline::terminal_warrants_switch_warning(
            self.inline_protocol,
            crate::iterm2_inline::detect_termux(),
        );
    }

    /// Dismiss the unsupported-terminal nudge. `dont_show_again` persists the
    /// dismissal so it never reappears; otherwise it returns next launch.
    fn dismiss_terminal_warning(&mut self, dont_show_again: bool) {
        self.pending_terminal_warning = false;
        if dont_show_again {
            let _ = crate::prefs::save_suppress_terminal_warning(true);
        }
    }

    fn commit_source_control(&mut self) {
        let message = self.source_control.message.trim().to_string();
        if message.is_empty() {
            self.source_control.commit_feedback = Some(String::from("Empty commit message"));
            self.source_control.commit_feedback_is_error = true;
            return;
        }
        match crate::git::commit_all_tracked(&self.scm_root(), &message) {
            Ok(summary) => {
                self.source_control.clear_message();
                self.source_control.commit_feedback = Some(summary.clone());
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("Committed: {summary}");
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(err.clone());
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Commit failed: {err}");
            }
        }
    }

    /// Housekeeping for the ssh-pane offer (#364), from the top of `render`
    /// like `dress_host_accents`: an offer nobody took or dismissed clears
    /// itself after [`SSH_OFFER_TTL`], and a pane that closed takes its offer
    /// and its per-pane memory along. No system calls: the sampling itself
    /// rides the label thread (see `refresh_terminal_labels`).
    fn expire_ssh_offer(&mut self) {
        let now = std::time::Instant::now();
        if self
            .ssh_offer
            .as_ref()
            .is_some_and(|o| now.duration_since(o.since) > SSH_OFFER_TTL)
        {
            self.dismiss_ssh_offer();
        }
        let live: std::collections::BTreeSet<u64> =
            self.terminals.iter().map(|t| t.uid()).collect();
        self.ssh_offer_seen.retain(|uid, _| live.contains(uid));
        if self
            .ssh_offer
            .as_ref()
            .is_some_and(|o| !live.contains(&o.pane))
        {
            self.dismiss_ssh_offer();
        }
    }

    /// Fold the label thread's ssh samples into the offer state (#364):
    /// each `(shell pid, host)` names the pane by its shell and goes through
    /// `consider_ssh_offer` keyed on the pane's uid.
    fn apply_ssh_samples(&mut self, samples: Vec<(i32, Option<String>)>) {
        for (shell_pid, host) in samples {
            let Some(uid) = self
                .terminals
                .iter()
                .find(|t| t.shell_pid() == Some(shell_pid))
                .map(|t| t.uid())
            else {
                continue;
            };
            self.consider_ssh_offer(uid, host);
        }
    }

    /// One pane's sampled ssh host, against what it was last seen connected
    /// to (#364). A session is offered when it STARTS: the same host on the
    /// next sample is the same session, not a new reason to prompt. `None`
    /// ends the session; an offer for that pane goes with it.
    fn consider_ssh_offer(&mut self, pane: u64, host: Option<String>) {
        let previous = self.ssh_offer_seen.insert(pane, host.clone()).flatten();
        match host {
            None => {
                if self.ssh_offer.as_ref().is_some_and(|o| o.pane == pane) {
                    self.dismiss_ssh_offer();
                }
            }
            Some(host) => {
                if previous.as_deref() == Some(host.as_str()) {
                    return;
                }
                // The pane moved to another host: whatever it was offered
                // for is no longer where it is, offerable or not.
                if self.ssh_offer.as_ref().is_some_and(|o| o.pane == pane) {
                    self.dismiss_ssh_offer();
                }
                if !crate::remote::offer_allowed(
                    &host,
                    self.remote_offer_disabled,
                    &self.remote_offer_excluded,
                    &self.remote_offer_refused,
                    std::time::SystemTime::now(),
                ) {
                    return;
                }
                self.status =
                    format!("Connected to {host} · Open workspace here? (Cmd+K G, Esc dismisses)");
                self.ssh_offer = Some(SshOffer {
                    pane,
                    host,
                    since: std::time::Instant::now(),
                });
            }
        }
    }

    /// Take the open offer's host for launching (#364), clearing the offer.
    fn accept_ssh_offer(&mut self) -> Option<String> {
        let offer = self.ssh_offer.take()?;
        if self.status.starts_with("Connected to ") {
            self.status.clear();
        }
        Some(offer.host)
    }

    /// Remember that provisioning `host` failed (#364): the ssh-pane offer
    /// stops prompting for it for `REFUSED_HOST_TTL`. Recorded for any
    /// install that fails, offer-launched or not, because the fact learned
    /// is about the host; and undone by the next success (below), so a box
    /// that merely failed on a bad day is offered again once it works.
    fn note_provisioning_failed(&mut self, host: &str) {
        let key = host.to_ascii_lowercase();
        let now = std::time::SystemTime::now();
        self.remote_offer_refused.insert(key.clone(), now);
        let _ = crate::remote::remember_refused_host(
            &crate::remote::refused_hosts_path(&croft_cache_dir()),
            &key,
            now,
        );
    }

    /// A provisioning of `host` succeeded (#364): any remembered refusal is
    /// stale, in memory and on disk. The disk side runs unconditionally:
    /// the file is shared by every croft on the machine, so another
    /// instance may have recorded a refusal this one never loaded, and
    /// `forget_refused_host` is a no-op when there is nothing to forget.
    fn note_provisioning_succeeded(&mut self, host: &str) {
        let key = host.to_ascii_lowercase();
        self.remote_offer_refused.remove(&key);
        let _ = crate::remote::forget_refused_host(
            &crate::remote::refused_hosts_path(&croft_cache_dir()),
            &key,
        );
    }

    /// Drop the open offer and its status line, if any (#364).
    fn dismiss_ssh_offer(&mut self) {
        if self.ssh_offer.take().is_some() && self.status.starts_with("Connected to ") {
            self.status.clear();
        }
    }

    fn request_remote_launch(&mut self, host: String, path: Option<String>) {
        self.status = format!("Connecting to {host}");
        match crate::remote_connect::SshAuth::start(&host) {
            Ok(auth) => {
                self.connect_auth = Some(auth);
                self.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
                    host.clone(),
                ));
                self.pending_remote_launch_path = path;
                self.pending_remote_launch_host = Some(host);
                self.overlays.welcome.request_clear();
            }
            Err(e) => {
                self.status = format!("Could not start ssh: {e}");
            }
        }
    }

    /// Re-root the workspace onto the host the active pane is ssh'd into
    /// (#364).
    ///
    /// Reads the pane's foreground argv rather than its scrollback: what the
    /// user typed may have scrolled away, been edited, or never been typed at
    /// all (a shell function, a `Host` alias resolved by ssh itself), while
    /// argv is what is actually running.
    ///
    /// The foreground PROCESS GROUP LEADER is what identifies the session,
    /// and it is right for the case that matters: `ssh box` typed at a
    /// prompt is its own group leader. A PIPELINE is the limit — `ssh box |
    /// tee log` makes the whole pipeline one group whose leader is not
    /// necessarily the ssh, so the command reports "not an SSH session"
    /// rather than guessing. Measured rather than assumed: on zsh the leader
    /// resolves to the LAST stage. Refusing is the right failure here, since
    /// the alternative is walking the process tree to find an ssh somewhere
    /// under the pane and offering to re-root onto a host the user piped
    /// output from rather than one they are working on.
    ///
    /// Explicit in the first slice, deliberately: the automatic status-bar
    /// offer needed a per-host opt-out, a memory of hosts that refused
    /// provisioning and a decision about how often to prompt, none of which
    /// belonged alongside the detection itself. Those exist now (the second
    /// slice: `consider_ssh_offer` and its gates), and the offer accepts
    /// through the same `request_remote_launch` this command reaches for.
    fn open_workspace_on_ssh_host(&mut self) {
        let Some(term) = self.terminals.get(self.active_terminal) else {
            self.status = String::from("No terminal pane is open");
            return;
        };
        let Some(fg) = term.foreground_pid() else {
            self.status = String::from("This pane is not running anything");
            return;
        };
        let Some(cmd) = crate::widgets::terminal::process_cmdline(fg) else {
            self.status = String::from("Could not read what this pane is running");
            return;
        };
        let argv: Vec<&str> = cmd.iter().map(String::as_str).collect();
        let targets = crate::remote::discover_ssh_targets();
        match crate::remote::ssh_reroot_decision(&argv, &targets) {
            Ok(host) => {
                let alias = host.alias.clone();
                // No path: the remote flow opens the login directory, which
                // is where the ssh session started. Carrying the pane's
                // remote cwd across would need the shell's OSC 7 report from
                // the far side, and croft only trusts those against a local
                // cwd it can verify.
                self.request_remote_launch(alias, None);
            }
            // The message distinguishes "not ssh" from "ssh to a box croft
            // has no config entry for": the second names the host, because
            // adding it to ~/.ssh/config is the action available.
            Err(why) => self.status = why,
        }
    }

    /// Open the history scrubber over the current branch (#371).
    ///
    /// Parks at the WORKING TREE rather than at HEAD, so opening the
    /// scrubber changes nothing about what the user is looking at — the
    /// first step is theirs to take. That also makes the gesture free to
    /// try: a user who opens it by accident is exactly where they were.
    fn scrub_history(&mut self) {
        // `branch_history`, NOT `commit_graph`: the latter logs
        // `--branches --tags HEAD` to draw the repo-wide graph, so with any
        // other branch present index 0 is whatever topological order put
        // first rather than HEAD, and stepping back from the working tree
        // lands on a commit the current branch may not even contain.
        let commits = crate::git::branch_history(self.workspace_root(), SCRUB_COMMIT_LIMIT);
        if commits.is_empty() {
            self.status = String::from("No commits to scrub through");
            return;
        }
        let n = commits.len();
        self.scrubber = Some(crate::scrubber::Scrubber::new(commits));
        self.status =
            format!("Scrubbing {n} commits — arrows step, Home returns to your working tree");
    }

    /// Follow an edit with the open symbol tab's range (#369).
    ///
    /// A symbol tab is a VIEW over a byte range rather than a copy, so an
    /// edit that is not reported here leaves the tab pointing at bytes that
    /// have moved — showing the wrong text under the right title, which is
    /// worse than showing nothing.
    ///
    /// **Wired only to the collab span path today**, which is the one place
    /// an edit already arrives as `(at, deleted, inserted)`. Local typing,
    /// backspace, paste, undo and formatting all mutate the buffer through
    /// line/column APIs that do not report a byte span, so a tab opened
    /// while those run would go stale — which is why the tab VIEW is not
    /// built yet and this ships as the tracking layer alone. Giving the
    /// editor a byte-span edit signal is the next piece of #369, and doing
    /// it before there is a view to break is deliberate: the alternative is
    /// a tab that is right for remote edits and silently wrong for the
    /// user's own.
    ///
    /// A symbol the edit removed or straddled CLOSES the tab with a notice,
    /// rather than re-anchoring to half a function glued to whatever
    /// followed it.
    pub(crate) fn follow_symbol_tab_edit(&mut self, at: usize, removed: usize, inserted: usize) {
        let Some((name, path, range)) = self.symbol_tab.take() else {
            return;
        };
        match range.after_edit(at, removed, inserted) {
            crate::symbol_range::RangeAfterEdit::At(moved) => {
                self.symbol_tab = Some((name, path, moved));
            }
            crate::symbol_range::RangeAfterEdit::Gone => {
                self.status = format!("Closed the {name} tab: that symbol is gone");
            }
        }
    }

    /// Open the symbol under the cursor as its own tab (#369).
    ///
    /// The INNERMOST enclosing symbol, so opening from inside a method shows
    /// the method rather than its `impl` — the enclosing block is almost
    /// never what was meant.
    fn open_symbol_tab(&mut self) {
        let line = self.editor.cursor_row as u32;
        let symbols = self.outline.symbols();
        let Some(sym) = crate::symbol_range::enclosing_symbol(symbols, line) else {
            self.status = if symbols.is_empty() {
                String::from("No symbols for this file yet")
            } else {
                String::from("The cursor is not inside a symbol")
            };
            return;
        };
        let name = sym.name.clone();
        let (first, last) = (sym.range_start_line as usize, sym.range_end_line as usize);
        // Converted to BYTES once, here. `SymbolRange` tracks bytes because
        // that is what an edit reports, and holding lines as well would be
        // two representations that can disagree the moment one is updated
        // and the other is not.
        let start: usize = self
            .editor
            .lines
            .iter()
            .take(first)
            .map(|l| l.len() + 1)
            .sum();
        let mut len: usize = self
            .editor
            .lines
            .iter()
            .skip(first)
            .take(last + 1 - first)
            .map(|l| l.len() + 1)
            .sum();
        // The `+ 1` is a SEPARATOR between lines, not a terminator: croft's
        // offset model gives an N-line buffer no trailing newline. Charging
        // one to the final line puts `end` a byte past the buffer, which
        // panics anything that slices by the range — and makes an append at
        // true EOF read as INSIDE the symbol rather than below it.
        if last + 1 >= self.editor.lines.len() {
            len = len.saturating_sub(1);
        }
        let range = crate::symbol_range::SymbolRange::new(start, start + len);
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("Save this buffer before opening a symbol from it");
            return;
        };
        self.symbol_tab = Some((name.clone(), path, range));
        self.status = format!("{name}: {} bytes", range.len());
    }

    /// Start or stop recording the active terminal as an asciicast (#356).
    ///
    /// Toggling rather than two commands, because a recording is a mode with
    /// exactly one visible state: a user who cannot remember whether they
    /// started one reaches for the same entry either way, and gets told
    /// which happened.
    fn toggle_session_recording(&mut self) {
        use std::io::Write as _;
        if let Some((_, _, started)) = self.recording.take() {
            let secs = started.elapsed().as_secs_f64();
            self.status = format!("Stopped recording after {secs:.1}s");
            return;
        }
        let Some(term) = self.terminals.get(self.active_terminal) else {
            self.status = String::from("No terminal pane to record");
            return;
        };
        // `last_inner`, not `last_area`. The PTY grid is sized from the
        // pane's INNER rect — `Borders::ALL` takes a cell on each side — so
        // recording the outer size declares a terminal two columns wider and
        // two rows taller than the content was wrapped for. The player then
        // wraps every long line at the wrong column.
        let (cols, rows) = (term.last_inner.width, term.last_inner.height);
        if cols == 0 || rows == 0 {
            // A zero-sized header makes a cast every player refuses, and the
            // error names the file rather than the moment it was started.
            self.status = String::from("The terminal has no size yet — try once it has drawn");
            return;
        }
        // A per-recording name, not a per-process one: two recordings in
        // one session would otherwise write the same file, and the second
        // would silently destroy the first — which the user only discovers
        // when they go to share the earlier one.
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let path = self
            .workspace_root()
            .join(format!("croft-{}-{stamp}.cast", std::process::id()));
        let rec = crate::asciicast::Recorder::new(cols, rows);
        let header = rec.header(Some("croft session"));
        match std::fs::File::create(&path) {
            Ok(mut f) => {
                if let Err(e) = writeln!(f, "{header}") {
                    self.status = format!("Could not write {}: {e}", path.display());
                    return;
                }
                self.recorded_size = (cols, rows);
                self.recording = Some((rec, f, std::time::Instant::now()));
                self.status = format!("\u{25cf} REC to {}", path.display());
            }
            Err(e) => self.status = format!("Could not create {}: {e}", path.display()),
        }
    }

    /// Load this PR's review threads onto the open file as comment boxes
    /// (#366).
    ///
    /// Only threads for THIS file. A review's comments span the whole PR,
    /// and hanging another file's objections off this buffer's line numbers
    /// would put them against unrelated code — the same failure as placing
    /// an outdated thread silently, arriving through the other axis.
    fn load_review_threads(&mut self) {
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("Open a file from the PR first");
            return;
        };
        // The root that OWNS the open file, not the primary. In a
        // multi-root workspace the two differ, and using the primary runs
        // `gh` in the wrong repository — which answers about a different
        // PR entirely rather than failing.
        let root = self.active_workspace_root();
        // Relative to the REPOSITORY TOPLEVEL, not the workspace root. The
        // API's `path` is repo-relative, and the two coincide only when the
        // workspace root IS the toplevel — open croft on `repo/src` and
        // every comparison fails silently, so a file with review comments
        // reports having none. That is #139's rule; this is the same trap in
        // a new place.
        let Some(repo_root) = self.git_worker_for_root(&root).status().repo_root.clone() else {
            self.status = String::from("This folder is not inside a git repository");
            return;
        };
        let Ok(rel) = path.strip_prefix(&repo_root) else {
            self.status = format!(
                "{} is outside the repository, so it has no review comments",
                path.display()
            );
            return;
        };
        // Forward slashes: the API always uses them, and on Windows a
        // `to_string_lossy` here yields backslashes that match nothing.
        let rel = rel
            .components()
            .map(|c| c.as_os_str().to_string_lossy())
            .collect::<Vec<_>>()
            .join("/");
        let out = std::process::Command::new("gh")
            .args(["pr", "view", "--json", "number", "--jq", ".number"])
            .current_dir(&root)
            .output();
        let number = match out {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
            _ => {
                self.status = String::from("No PR for this branch — check it out first");
                return;
            }
        };
        let api = std::process::Command::new("gh")
            .args([
                "api",
                &format!("repos/{{owner}}/{{repo}}/pulls/{number}/comments"),
                "--paginate",
            ])
            .current_dir(&root)
            .output();
        let json = match api {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
            Ok(o) => {
                // gh's own message names the problem — a missing scope, a
                // rate limit — far better than anything invented here.
                let err = String::from_utf8_lossy(&o.stderr);
                self.status = format!(
                    "Could not read the PR's comments: {}",
                    err.trim().lines().next().unwrap_or("gh failed")
                );
                return;
            }
            Err(e) => {
                self.status = format!("Could not run gh: {e}");
                return;
            }
        };
        let threads: Vec<crate::review_threads::Thread> =
            crate::review_threads::parse_threads(&json)
                .into_iter()
                .filter(|t| t.path == rel)
                .collect();
        if threads.is_empty() {
            self.status = format!("No review comments on {rel}");
            return;
        }
        let outdated = threads
            .iter()
            .filter(|t| matches!(t.anchor, crate::review_threads::Anchor::Outdated(_)))
            .count();
        // Stored against the file they describe; the render derives each
        // box's row and title from the buffer as it is at that moment.
        // `path` is the binding taken at the top of this function, so the
        // threads are keyed to the file the `gh` query was actually about
        // rather than to whatever `editor.path` says afterwards. Today those
        // cannot differ — the event loop is single-threaded and `gh` blocks
        // it, so no keystroke is handled mid-call — but keying to the
        // queried file is the property that matters, and it stops being
        // free the moment this moves off the main thread.
        self.review_boxes = Some((path, threads.clone()));
        self.status = match outdated {
            0 => format!("{} review comments on {rel}", threads.len()),
            n => format!(
                "{} review comments on {rel} \u{b7} {n} outdated, shown where they WERE",
                threads.len()
            ),
        };
    }

    /// Append terminal output to the open recording, if there is one (#356).
    ///
    /// Times are measured from the recording's start rather than from the
    /// process's, because a cast's first event should be at ~0 — a player
    /// given a first timestamp of 4000 seconds sits on a blank screen for
    /// over an hour before anything happens.
    pub(crate) fn record_terminal_output(&mut self, data: &str) {
        use std::io::Write as _;
        let Some((rec, file, started)) = self.recording.as_mut() else {
            return;
        };
        let line = rec.line(&crate::asciicast::Event::Output {
            at: started.elapsed().as_secs_f64(),
            data: data.to_string(),
        });
        // A write failure STOPS the recording rather than being ignored: a
        // half-written cast that keeps growing is worse than one that ends,
        // and the user needs to know the file they are about to share is
        // truncated.
        if writeln!(file, "{line}").is_err() {
            self.recording = None;
            self.status = String::from("Recording stopped: could not write to the cast file");
        }
    }

    /// Run `command` on every configured ssh host and report what differs
    /// (#363).
    ///
    /// In PARALLEL, one thread per host, because the whole point is
    /// comparing a fleet: run serially, ten hosts at a two-second timeout
    /// each is twenty seconds of staring, and a single unreachable host
    /// would hold up every other result behind it.
    fn run_fleet_command(&mut self, command: &str) {
        let command = command.trim();
        if command.is_empty() {
            self.status = String::from("Fleet run needs a command");
            return;
        }
        let known: Vec<String> = crate::remote::discover_ssh_targets()
            .into_iter()
            .map(|t| t.alias)
            .collect();
        if known.is_empty() {
            self.status = String::from("No hosts in ~/.ssh/config to run on");
            return;
        }
        // The fleet must be NAMED. Defaulting to every configured host means
        // running arbitrary text on every remote the user ever set up — and
        // a confirmation saying "run on 5 hosts?" asks them to approve a list
        // they cannot see, which is not consent. `*` is how to say "all of
        // them" deliberately.
        let Some((picked, command)) =
            crate::fleet::parse_request_with_groups(command, &known, &self.fleet_groups)
        else {
            self.status = format!(
                "Fleet run needs 'hosts: command' — e.g. '{}: uptime', or '*: uptime' for all {}",
                known[0],
                known.len()
            );
            return;
        };
        let hosts: Vec<String> = picked.into_iter().cloned().collect();
        if self.fleet_running {
            self.status = String::from("A fleet run is already in flight");
            return;
        }
        crate::output::push(
            crate::output::CHANNEL_FLEET,
            crate::output::OutputLevel::Info,
            &format!("$ {command}   on {}", hosts.join(", ")),
        );
        // Off the event loop: the run waits on the network for up to
        // FLEET_TIMEOUT, and blocking the loop for that would freeze the
        // editor — the user could not scroll, type, or cancel while their
        // fleet answered. Results arrive through `fleet_rx` and are drained
        // on a later tick, the same shape the port poll and label lookup use.
        let host_count = hosts.len();
        let tx = self.fleet_tx.clone();
        let command = command.to_string();
        self.fleet_running = true;
        std::thread::spawn(move || {
            let _ = tx.send(crate::fleet::run_on_hosts(&hosts, &command, FLEET_TIMEOUT));
        });
        self.status = format!("Fleet: running on {host_count} hosts…");
    }

    /// Report a finished fleet run, if one arrived (#363).
    ///
    /// Drained on the tick like the other background results. Returns
    /// whether anything landed, so the caller can redraw only when there is
    /// something new.
    fn drain_fleet_results(&mut self) -> bool {
        // Every queued run, not just the newest. Each message is ONE run's
        // results, unlike the label channel this idiom comes from where each
        // message is a complete snapshot — taking `.last()` there is right
        // and here would drop a whole run's output with no trace of it.
        let batches: Vec<Vec<crate::fleet::HostResult>> = self.fleet_rx.try_iter().collect();
        if batches.is_empty() {
            return false;
        }
        self.fleet_running = false;
        for results in batches {
            let reference = crate::fleet::reference_output(&results).map(String::from);
            for r in &results {
                let mark = match (r.ok(), Some(r.output.as_str()) == reference.as_deref()) {
                    (false, _) => "FAILED",
                    (true, true) => "same",
                    (true, false) => "DIFFERS",
                };
                crate::output::push(
                    crate::output::CHANNEL_FLEET,
                    if r.ok() {
                        crate::output::OutputLevel::Info
                    } else {
                        crate::output::OutputLevel::Error
                    },
                    &format!("{}  [{mark}]  {}", r.host, r.output.replace('\n', " ")),
                );
            }
            let summary = crate::fleet::summarise(&results, reference.as_deref());
            crate::output::push(
                crate::output::CHANNEL_FLEET,
                crate::output::OutputLevel::Info,
                &summary.line(),
            );
            self.status = format!("Fleet: {}", summary.line());
        }
        true
    }

    /// Ask for a new lane's name (#348); the palette command and `Cmd+K
    /// Shift+L` both land here.
    fn open_new_lane_prompt(&mut self) {
        self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
            crate::widgets::input_prompt::InputPurpose::NewWorktreeLane,
            String::from("New worktree lane"),
            String::from("what the agent will work on"),
        ));
    }

    /// Create a worktree lane and add it as a workspace root (#348).
    ///
    /// The worktree is a SIBLING of the repo, never a child: a worktree
    /// nested inside its own repo is a working tree git then tries to track,
    /// and the Explorer would show the lane inside the root it was cut from.
    fn create_worktree_lane(&mut self, name: &str) {
        let repo = self.workspace_root().to_path_buf();
        let Some(mut lane) = crate::git::WorktreeLane::plan(&repo, name) else {
            // Refused rather than defaulted: a name with nothing usable in
            // it would otherwise become the branch `agent/`.
            self.status = format!("{name:?} has no letters or digits to name a lane after");
            return;
        };
        if lane.path.exists() {
            self.status = format!("{} already exists — pick another name", lane.path.display());
            return;
        }
        match crate::git::add_worktree_lane(&repo, &mut lane) {
            Ok(()) => {
                self.add_workspace_folder(lane.path.clone());
                self.open_lane_pane(&lane);
            }
            Err(why) => self.status = format!("Could not create the lane: {why}"),
        }
    }

    /// The pane half of a new lane (#348): a named terminal in the worktree,
    /// running the configured agent's launch line when there is one. The
    /// status says which of the three outcomes happened — agent started,
    /// plain shell because no agent is configured, or plain shell because
    /// the configured agent has no launch line — since a lane that quietly
    /// opens a shell where the user expected an agent reads as broken.
    fn open_lane_pane(&mut self, lane: &crate::git::WorktreeLane) {
        let slug = lane
            .branch
            .strip_prefix("agent/")
            .unwrap_or(&lane.branch)
            .to_string();
        let agent = self
            .lane_agent
            .as_deref()
            .map(str::trim)
            .filter(|a| !a.is_empty())
            .map(str::to_ascii_lowercase);
        let launch = agent
            .as_deref()
            .and_then(|a| self.agents.launch_line(a))
            .map(str::to_string);
        let mut term = match PtyTerminal::new(&lane.path) {
            Ok(t) => t,
            Err(e) => {
                self.status = format!(
                    "Lane {} on branch {} — could not open its pane: {e}",
                    lane.path.display(),
                    lane.branch
                );
                return;
            }
        };
        term.set_manual_name(Some(format!("Lane: {slug}")));
        if let Some(cmd) = &launch {
            term.write_input(lane_launch_input(cmd).as_bytes());
        }
        let seated = launch.is_some();
        // Recorded BEFORE the insert: `insert_terminal` saves the terminal
        // session, and the save reads this map.
        self.lane_panes.insert(
            term.uid(),
            crate::terminal_session::LaneRecord {
                // Canonical, like the workspace roots it is compared with
                // when the lane closes; taken now, while the directory
                // exists to resolve.
                path: lane
                    .path
                    .canonicalize()
                    .unwrap_or_else(|_| lane.path.clone())
                    .display()
                    .to_string(),
                branch: lane.branch.clone(),
                agent: if seated { agent.clone() } else { None },
                base: lane.base.clone(),
            },
        );
        self.insert_terminal(term);
        let pane = match (agent, seated) {
            (Some(a), true) => format!("{a} started in pane Lane: {slug}"),
            (Some(a), false) => {
                format!(
                    "plain shell in pane Lane: {slug} (agents.json has no launch line for {a:?})"
                )
            }
            (None, _) => format!("shell in pane Lane: {slug} (set lane_agent to start an agent)"),
        };
        self.status = format!(
            "Lane {} on branch {} — {pane}",
            lane.path.display(),
            lane.branch
        );
    }

    /// The review-queue summary, one row per agent, grouped by the workspace
    /// root each file lives under (#348).
    ///
    /// Grouping is what makes the queue usable once worktree lanes exist:
    /// with an agent working in a lane and you working in the main checkout,
    /// a flat list of basenames cannot say which `mod.rs` it means. Each
    /// group is named by its lane's BRANCH where the root is a lane, and by
    /// the root's display label otherwise.
    ///
    /// A row whose files all sit under ONE root keeps the pre-grouping flat
    /// shape, `agent: n to review (a.rs, b.rs)`: with one group the label
    /// names the only place the files could be and the group count merely
    /// repeats `n`. So the common single-root session is untouched, and
    /// grouping appears exactly when there is something to tell apart.
    ///
    /// A grouped row carries labels and counts but no file names, because
    /// the status bar is one row that elides its MIDDLE: a row long enough
    /// to be cut loses the group labels, which is precisely what grouping
    /// exists to show. The flat row keeps its sample, being short already.
    fn agent_lane_rows(&self) -> Vec<String> {
        let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
        let labels = crate::workspace::root_display_labels(&roots);
        // A lane's branch names it better than its directory does: the
        // directory is `repo-fix-login`, the branch is what the agent is on.
        let branch_of = |root: &Path| -> Option<String> {
            self.lane_panes
                .values()
                .find(|l| Path::new(&l.path) == root)
                .map(|l| l.branch.clone())
        };
        // Up to three names per group, with an ellipsis when there are more:
        // a count next to a truncated list otherwise reads as an
        // enumeration that lost two entries.
        let sample = |files: &[&crate::agent_lane::LaneFile]| -> String {
            let names: Vec<String> = files
                .iter()
                .take(3)
                .map(|f| {
                    let name = f
                        .path
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_default();
                    if f.shared {
                        format!("{name} (shared)")
                    } else {
                        name
                    }
                })
                .collect();
            let mut out = names.join(", ");
            if files.len() > names.len() {
                out.push_str(", \u{2026}");
            }
            out
        };
        self.agent_ledger
            .agents()
            .into_iter()
            .map(|agent| {
                let n = self.agent_ledger.unreviewed_count(agent);
                let groups = self.agent_ledger.lane_by_root(agent, &roots);
                // One group is the single-root session this feature does not
                // change: the root label would name the only place the files
                // could be, and the group count would repeat `n`.
                if groups.len() <= 1 {
                    let files = groups.first().map(|(_, f)| sample(f)).unwrap_or_default();
                    return format!("{agent}: {n} to review ({files})");
                }
                // A lane's branch is derived from its slug alone, so two
                // lanes cut from different repos can share one; fall back to
                // the disambiguated root label when that happens, since a
                // row naming two groups identically is worse than a row
                // naming them by folder.
                let branches: Vec<Option<String>> = groups
                    .iter()
                    .map(|(root, _)| root.and_then(&branch_of))
                    .collect();
                let named: Vec<String> = groups
                    .iter()
                    .zip(&branches)
                    .map(|((root, files), branch)| {
                        let root_label = |r: &Path| {
                            roots
                                .iter()
                                .position(|candidate| candidate == r)
                                .and_then(|i| labels.get(i).cloned())
                                .unwrap_or_else(|| r.display().to_string())
                        };
                        let label = match (root, branch) {
                            (Some(_), Some(b))
                                if branches.iter().flatten().filter(|o| *o == b).count() == 1 =>
                            {
                                b.clone()
                            }
                            (Some(r), _) => root_label(r),
                            (None, _) => String::from("outside the workspace"),
                        };
                        // Labels and counts only. The status bar is ONE row
                        // and elides the MIDDLE of anything too long
                        // (`elide_middle`), so a row carrying samples for
                        // every group loses the group labels first — the
                        // one thing grouping adds. Which files they are is
                        // a question the Explorer's dots already answer.
                        format!("{label} {}", files.len())
                    })
                    .collect();
                format!("{agent}: {n} to review \u{2014} {}", named.join("; "))
            })
            .collect()
    }

    /// Give each lane's root row in the Explorer its branch and its agent
    /// (#348), from the lane panes: `agent/fix-login · ◆ claude ●` while the
    /// agent is seated, the configured agent's name before it is, the branch
    /// alone for a plain-shell lane. Runs from the top of `render`; the map
    /// is swapped only when its contents change, so the common frame costs a
    /// walk over a handful of lanes and a small map that is then dropped.
    fn sync_lane_root_badges(&mut self) {
        // Several panes on one lane: the pane that knows the most decides
        // the badge, whichever order the map walks them in. Seated beats
        // configured beats plain, decided from the state rather than by
        // reading the glyph back out of the text.
        let mut best: std::collections::HashMap<PathBuf, (u8, String)> =
            std::collections::HashMap::new();
        for (uid, lane) in &self.lane_panes {
            let seated = self
                .terminals
                .iter()
                .find(|t| t.uid() == *uid)
                .and_then(|t| t.agent());
            let rank = match (seated, lane.agent.as_deref()) {
                (Some(_), _) => 2,
                (None, Some(_)) => 1,
                (None, None) => 0,
            };
            let key = PathBuf::from(&lane.path);
            if best.get(&key).is_some_and(|(have, _)| *have >= rank) {
                continue;
            }
            let badge = lane_root_badge(&lane.branch, seated, lane.agent.as_deref());
            best.insert(key, (rank, badge));
        }
        let badges: std::collections::HashMap<PathBuf, String> =
            best.into_iter().map(|(k, (_, b))| (k, b)).collect();
        // Swapped only on a change: the map built here is dropped, not
        // handed to the tree, when nothing moved.
        if *self.tree.root_badges != badges {
            self.tree.root_badges = std::sync::Arc::new(badges);
        }
    }

    /// Close the panes that belong to the lane at `lane` (#348), through the
    /// undoable close so a mistaken lane removal does not also lose the
    /// pane's scrollback. Returns how many closed and how many stayed.
    ///
    /// The close refuses the last pane, and a lane pane left standing would
    /// sit in a directory git just removed; so when the lane's panes are ALL
    /// the panes, a fresh shell in the primary root is opened first to be
    /// the one that stays. Only when that shell cannot spawn does a lane
    /// pane remain, stripped of its lane name, and the caller says so.
    fn close_lane_panes(&mut self, lane: &Path) -> (usize, usize) {
        let doomed: Vec<usize> = self
            .terminals
            .iter()
            .enumerate()
            .filter(|(_, t)| {
                self.lane_panes
                    .get(&t.uid())
                    .is_some_and(|l| Path::new(&l.path) == lane)
            })
            .map(|(i, _)| i)
            .collect();
        if !doomed.is_empty() && doomed.len() == self.terminals.len() {
            // Pushed, not `insert_terminal`ed: the doomed indices must stay
            // where they are, and the session is saved by the closes below.
            match PtyTerminal::new(self.roots.primary()) {
                Ok(term) => self.terminals.push(term),
                Err(e) => self.status = format!("Could not open a replacement pane: {e}"),
            }
        }
        let (mut closed, mut kept) = (0, 0);
        // Highest index first so the earlier indices stay valid.
        for idx in doomed.into_iter().rev() {
            let uid = self.terminals[idx].uid();
            if self.close_terminal_at(idx) {
                closed += 1;
            } else {
                // The last pane stays; it is no longer a lane's (its
                // worktree is gone), so it stops wearing the lane's name.
                kept += 1;
                self.terminals[idx].set_manual_name(None);
                self.lane_panes.remove(&uid);
            }
        }
        (closed, kept)
    }

    /// Point the COMMITS graph at `base..lane` for the active lane (#348).
    ///
    /// Uses `active_scm_root` like `close_worktree_lane` beside it, rather
    /// than the primary: a lane is never index 0, and a sibling command that
    /// silently switched which root it acted on is how that one destroyed a
    /// lane in testing.
    ///
    /// Leaves the panel showing the diff until something else refreshes it -
    /// the tag on the reply keeps a background history fetch from replacing
    /// it, and returning to history is the ordinary refresh path.
    fn diff_worktree_lane(&mut self) {
        let lane = self.active_scm_root.clone();
        if lane == self.roots.primary() {
            self.status =
                String::from("The primary folder is not a lane — open a file in the lane first");
            return;
        }
        let Some(record) = self
            .lane_panes
            .values()
            .find(|r| std::path::Path::new(&r.path) == lane)
        else {
            self.status = String::from("No lane is open for this folder");
            return;
        };
        // A lane made before the base was recorded, or cut from a detached
        // HEAD, has nothing to diff against. Say which rather than showing an
        // empty graph that reads as "no commits".
        let Some(base) = record.base.clone() else {
            self.status = format!(
                "Lane {} records no base branch to diff against",
                record.branch
            );
            return;
        };
        let branch = record.branch.clone();
        self.graph_revspec = Some(format!("{base}..{branch}"));
        self.refresh_commit_graph();
        self.status = format!("COMMITS: {branch} against {base}");
    }

    /// Remove the active root's worktree lane, refusing when it is dirty
    /// (#348).
    ///
    /// The refusal is the point. `git worktree remove` DISCARDS uncommitted
    /// work, so this is the one place in the lane flow where being wrong
    /// destroys something rather than annoying someone — and the check fails
    /// closed, treating a tree git cannot report on as unsafe.
    fn close_worktree_lane(&mut self) {
        // The ACTIVE root, not the primary. `workspace_root()` is
        // `roots.primary()`, and a lane is appended by `add_workspace_folder`
        // so it is never index 0 — this targeted the user's main repo every
        // time. Today git's own "is a main working tree" refusal masks that,
        // but the guard is git's rather than ours: launch croft INSIDE a lane
        // (the workflow this feature creates) and the primary becomes a
        // removable worktree, so the directory is deleted, the folder cannot
        // be dropped, and the status reports success.
        let lane = self.active_scm_root.clone();
        if lane == self.roots.primary() {
            self.status =
                String::from("The primary folder is not a lane — open a file in the lane first");
            return;
        }
        // The diff outlives the lane otherwise: `remove_workspace_folder`
        // re-seeds the primary, and its COMMITS panel is then stuck on a
        // range whose right side no longer resolves.
        //
        // Cleared BEFORE the refusals, not in the success arm: `git worktree
        // remove` can still fail after `lane_removal_block` passed (a locked
        // worktree, below), and that arm returns too. On a refusal the rows
        // already drawn outlive the clear until the next refresh, which is
        // correct - they are still this lane's commits, and the lane is
        // still here.
        self.graph_revspec = None;
        if let Some(why) = crate::git::lane_removal_block(&lane) {
            self.status = format!("Keeping the lane: {why}");
            return;
        }
        // git FIRST, then the folder. `lane_removal_block` answers "is there
        // uncommitted work", which is not the same question as "will git
        // remove this" — a LOCKED worktree reports a clean status and is
        // then refused, measured. Dropping the folder first would leave the
        // user with the lane gone from their workspace and the directory
        // still on disk, which is the worst of both.
        match crate::git::remove_worktree_lane(&lane) {
            Ok(()) => {
                self.remove_workspace_folder(lane.clone());
                // `remove_workspace_folder` refuses the primary and says so
                // in the status; only claim success when the folder really
                // left, or a refusal there would be overwritten by a message
                // saying the whole thing worked.
                let (closed, kept) = self.close_lane_panes(&lane);
                if self.roots.iter().any(|r| r == lane) {
                    self.status = format!(
                        "Removed {} on disk, but it is still in this workspace",
                        lane.display()
                    );
                } else if kept > 0 {
                    self.status = format!(
                        "Removed lane {} — its pane stays (no replacement pane could open) in a directory that is now gone",
                        lane.display()
                    );
                } else if closed > 0 {
                    self.status = format!(
                        "Removed lane {} and closed its pane (Cmd+K Shift+T reopens it)",
                        lane.display()
                    );
                } else {
                    self.status = format!("Removed lane {}", lane.display());
                }
            }
            Err(why) => self.status = format!("Keeping the lane: {why}"),
        }
    }

    /// One scrubber keystroke. Returns whether it was consumed (#371).
    ///
    /// Returning `false` for anything else matters: the scrubber is a view,
    /// not a mode that swallows the keyboard, so a key it does not use keeps
    /// its normal meaning rather than being silently eaten.
    fn handle_scrubber_key(&mut self, code: KeyCode) -> bool {
        let Some(scrub) = self.scrubber.as_mut() else {
            return false;
        };
        match code {
            KeyCode::Left => scrub.older(),
            KeyCode::Right => scrub.newer(),
            KeyCode::Home => scrub.home(),
            KeyCode::Esc => {
                // Closing returns to the live buffer by construction: the
                // scrubber never replaced it, so there is nothing to put
                // back and no path where unsaved edits could be lost.
                self.scrubber = None;
                self.status = String::from("Left the history scrubber");
                return true;
            }
            _ => return false,
        }
        // git's own short hash, not a byte slice of the full one: that
        // slice is safe only while the string is ASCII hex, and the width
        // git abbreviates to is per-repo rather than always seven.
        self.status = match self.scrubber.as_ref().and_then(|s| s.commit()) {
            Some(c) => format!("At {} — {}", c.short_hash, c.summary),
            None => String::from("At your working tree"),
        };
        true
    }

    pub fn poll_connect_dialog(&mut self) -> bool {
        let Some(auth) = self.connect_auth.as_mut() else {
            return false;
        };
        let events = auth.drain_events();
        if events.is_empty() {
            return false;
        }
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return false;
        };
        let mut authenticated = false;
        let mut failed: Option<String> = None;
        for ev in events {
            match ev {
                crate::remote_connect::SshAuthEvent::Log(chunk) => {
                    dialog.push_log(&chunk);
                }
                crate::remote_connect::SshAuthEvent::Prompt { kind, line } => {
                    dialog.set_prompt(kind, line);
                }
                crate::remote_connect::SshAuthEvent::Authenticated => {
                    dialog.set_installing();
                    authenticated = true;
                }
                crate::remote_connect::SshAuthEvent::Failed(detail) => {
                    failed = Some(detail);
                }
            }
        }
        if let Some(detail) = failed {
            dialog.set_failed(detail);
            self.tear_down_connect_auth();
        }
        if authenticated
            && let (Some(auth), Some(host)) = (
                self.connect_auth.take(),
                self.pending_remote_launch_host.take(),
            )
        {
            let adopted = auth.hand_off();
            let path = self.pending_remote_launch_path.take();
            self.install_session = Some(crate::install_session::InstallSession::start(
                adopted,
                host.clone(),
                path,
            ));
            self.status = format!("Preparing remote croft on {host}");
        }
        true
    }

    pub fn poll_install_session(&mut self) -> bool {
        let Some(session) = self.install_session.as_mut() else {
            return false;
        };
        let events = session.drain_events();
        let mut changed = !events.is_empty();
        let mut can_launch = false;
        let mut done = false;
        let mut failure: Option<String> = None;
        for ev in events {
            match ev {
                crate::install_session::InstallEvent::Log(line) => {
                    if let Some(dialog) = self.connect_dialog.as_mut() {
                        dialog.push_log(&line);
                    }
                }
                crate::install_session::InstallEvent::CanLaunch => can_launch = true,
                crate::install_session::InstallEvent::FallbackPrompt { reason } => {
                    if let Some(dialog) = self.connect_dialog.as_mut() {
                        dialog.set_fallback_prompt(&reason);
                    } else if let Some(session) = self.install_session.as_ref() {
                        // No dialog to ask through: decline so the installer
                        // errors out with the `croft setup-cross` guidance
                        // instead of blocking forever on an answer.
                        session.respond_fallback(false);
                    }
                }
                crate::install_session::InstallEvent::Done(Ok(())) => done = true,
                crate::install_session::InstallEvent::Done(Err(detail)) => {
                    failure = Some(detail);
                }
            }
        }
        // Once we've handed the terminal to the remote croft, the install
        // keeps running in a detached thread and signals completion to that
        // remote process via the install-stamp it watches; nothing here.
        if self.remote_launch.is_some() {
            return changed;
        }
        // A croft is already on the remote: drop the user into it now and
        // let the (re)install finish in the background. The running remote
        // croft re-execs into the new binary when the stamp advances.
        if can_launch {
            if let Some(session) = self.install_session.as_mut()
                && let Some(adopted) = session.take_adopted()
            {
                let host = session.host.clone();
                let path = session.path.clone();
                self.note_provisioning_succeeded(&host);
                self.remote_launch = Some(RemoteLaunch {
                    host: host.clone(),
                    path,
                    adopted: Some(adopted),
                });
                self.status = format!("Launching croft on {host}");
                self.connect_dialog = None;
                self.quit = true;
            }
            return true;
        }
        if let Some(detail) = failure {
            // Remember the host as one croft could not provision (#364), so
            // the ssh-pane offer stops prompting for it for a while. Kept
            // beside the failure it learns from, and best-effort: a write
            // that fails costs one repeated offer.
            if let Some(host) = self.install_session.as_ref().map(|s| s.host.clone()) {
                self.note_provisioning_failed(&host);
            }
            if let Some(dialog) = self.connect_dialog.as_mut() {
                dialog.set_failed(detail.clone());
            }
            self.install_session = None;
            self.status = format!("Remote install failed: {detail}");
            changed = true;
        } else if done {
            if let Some(mut session) = self.install_session.take()
                && let Some(adopted) = session.take_adopted()
            {
                let host = session.host.clone();
                let path = session.path.clone();
                self.note_provisioning_succeeded(&host);
                self.remote_launch = Some(RemoteLaunch {
                    host: host.clone(),
                    path,
                    adopted: Some(adopted),
                });
                self.status = format!("Launching croft on {host}");
                self.connect_dialog = None;
                self.quit = true;
            }
            changed = true;
        }
        changed
    }

    /// Start the background self-update watcher on a remote-launched croft.
    /// No-op unless `CROFT_REMOTE_AUTOUPDATE` is set (it is, by the remote
    /// launch command) and an install-stamp exists to compare against.
    fn start_update_watch_if_remote(&mut self) {
        if std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_none() {
            return;
        }
        let cache_dir = croft_cache_dir();
        let launch_stamp = std::fs::read_to_string(cache_dir.join("install-stamp"))
            .map(|s| s.trim().to_string())
            .unwrap_or_default();
        self.update_watch = Some(crate::update_watch::UpdateWatch::start(
            cache_dir,
            launch_stamp,
        ));
    }

    /// Start the one-shot local drift probe (#242) on a locally-launched
    /// croft. A remote-launched croft skips it: its binary is re-stamped by
    /// the launching machine on every connect, and its baked manifest dir
    /// points at a tree on another box anyway.
    fn start_drift_probe_if_local(&mut self) {
        if std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_some() {
            return;
        }
        self.drift_probe = Some(crate::update_watch::DriftProbe::start(
            String::from(env!("CARGO_MANIFEST_DIR")),
            String::from(env!("CROFT_GIT_HASH_FULL")),
        ));
    }

    /// Start the release-availability check (#333) on a locally-launched
    /// croft. A remote-launched croft is shipped by its launcher; a build
    /// with `CROFT_NO_UPDATE_CHECK` set in the environment never asks.
    fn start_update_check_if_local(&mut self) {
        if std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_some()
            || std::env::var_os("CROFT_NO_UPDATE_CHECK").is_some()
        {
            return;
        }
        self.update_check = Some(crate::update_check::UpdateCheck::start(
            croft_cache_dir(),
            String::from(env!("CARGO_PKG_VERSION")),
        ));
    }

    /// Raise the popup when the check finds a newer, undismissed release.
    /// The check is dropped either way - it only ever answers once.
    fn poll_update_check(&mut self) -> bool {
        let Some(check) = self.update_check.as_ref() else {
            return false;
        };
        let Some(verdict) = check.take() else {
            return false;
        };
        self.update_check = None;
        let Some(version) = verdict else {
            return false;
        };
        self.update_toast = Some(UpdateToast {
            version,
            ready: false,
            buttons: Vec::new(),
        });
        true
    }

    /// Kick off the staged build the popup offered. The existing update
    /// state machine takes it from here: spinner while cargo runs, then
    /// the popup and the status bar both offer Relaunch.
    fn start_staged_update(&mut self, version: String) {
        self.staged_status = UpdateStatus::Idle;
        self.staged_install = Some(crate::update_check::StagedInstall::start(
            croft_cache_dir(),
            version,
            staged_install_log_path(),
        ));
    }

    /// Decline the offered version for good (until a newer one appears).
    fn dismiss_update_offer(&mut self, version: &str) {
        if let Err(e) = crate::update_check::dismiss(&croft_cache_dir(), version) {
            self.status = format!("Could not remember the dismissed update: {e}");
        }
    }

    /// The staged binary waiting to be swapped in, once its build landed.
    fn staged_update_binary(&self) -> Option<PathBuf> {
        let install = self.staged_install.as_ref()?;
        (self.staged_status == UpdateStatus::Ready).then(|| install.binary().to_path_buf())
    }

    /// Whether any producer has an update ready to re-exec into: the
    /// status-bar pill and bare F9 mean "any".
    fn any_update_ready(&self) -> bool {
        self.update_status == UpdateStatus::Ready || self.staged_status == UpdateStatus::Ready
    }

    /// Whether any producer is mid-build (drives the spinner).
    fn any_update_in_progress(&self) -> bool {
        self.update_status == UpdateStatus::InProgress
            || self.staged_status == UpdateStatus::InProgress
    }

    /// Arm the rebuild hint when the drift probe's verdict lands. The probe
    /// is dropped either way — it only ever answers once.
    fn poll_drift_probe(&mut self) -> bool {
        let Some(probe) = self.drift_probe.as_ref() else {
            return false;
        };
        let Some(verdict) = probe.take() else {
            return false;
        };
        self.drift_probe = None;
        let Some(current) = verdict else {
            return false;
        };
        self.status = format!(
            "This croft was built at {}, but its repo is now at {current} - press F9 to rebuild & reinstall in the background",
            env!("CROFT_GIT_HASH"),
        );
        self.local_drift = Some(current);
        true
    }

    /// Kick off the background reinstall the drift hint offered. The
    /// existing update state machine takes it from here: spinner while
    /// `cargo install` runs, then the same "F9 to relaunch" flow a remote
    /// background update uses.
    fn start_local_reinstall(&mut self) {
        self.self_install = Some(crate::update_watch::SelfInstall::start(
            String::from(env!("CARGO_MANIFEST_DIR")),
            self_install_log_path(),
        ));
    }

    /// True when bare F9 is claimed by the update flow: either a landed
    /// update waiting to re-exec, or an armed drift hint waiting to rebuild.
    fn f9_update_armed(&self) -> bool {
        self.any_update_ready()
            || (self.local_drift.is_some()
                && self.update_status == UpdateStatus::Idle
                && self.staged_status != UpdateStatus::InProgress
                // `update_status` only leaves Idle when the InProgress event
                // is drained - once per outer loop, BEFORE the input drain -
                // so without this latch two F9s in one crossterm batch spawn
                // two concurrent `cargo install`s racing cargo's locks
                // (#245). The staged release build holds the same cargo
                // lock, so it latches F9 the same way.
                && self.self_install.is_none()
                && self.staged_install.is_none())
    }

    pub fn poll_update_watch(&mut self) -> bool {
        let mut changed = self.poll_drift_probe();
        changed |= self.poll_update_check();
        // Three producers share one event vocabulary; each event keeps its
        // origin so a drift rebuild's failure is never charged to the
        // staged release build (or the reverse).
        let mut events: Vec<(UpdateSource, crate::update_watch::UpdateEvent)> = Vec::new();
        if let Some(watch) = self.update_watch.as_ref() {
            events.extend(watch.drain().into_iter().map(|e| (UpdateSource::Watch, e)));
        }
        if let Some(install) = self.self_install.as_ref() {
            events.extend(
                install
                    .drain()
                    .into_iter()
                    .map(|e| (UpdateSource::SelfInstall, e)),
            );
        }
        if let Some(staged) = self.staged_install.as_ref() {
            events.extend(
                staged
                    .drain()
                    .into_iter()
                    .map(|e| (UpdateSource::Staged, e)),
            );
        }
        for (source, ev) in events {
            changed = true;
            // Each producer writes ITS cell; the other cell is never
            // touched, so nothing one build does can strand the other's
            // landed binary (there is exactly one Ready per channel).
            let staged = source == UpdateSource::Staged;
            match ev {
                crate::update_watch::UpdateEvent::InProgress => {
                    if staged {
                        self.staged_status = UpdateStatus::InProgress;
                    } else {
                        self.update_status = UpdateStatus::InProgress;
                    }
                    // The dedicated red, spinning status-bar span renders the
                    // message now, so the generic status line stays clear.
                    self.update_spinner_start = Some(std::time::Instant::now());
                    self.status.clear();
                }
                crate::update_watch::UpdateEvent::Failed => {
                    if staged {
                        self.staged_status = UpdateStatus::Idle;
                    } else {
                        self.update_status = UpdateStatus::Idle;
                    }
                    if !self.any_update_in_progress() {
                        self.update_spinner_start = None;
                    }
                    self.status = match source {
                        UpdateSource::Staged => {
                            let version = self
                                .staged_install
                                .take()
                                .map(|s| s.version)
                                .unwrap_or_default();
                            // The offer stays declinable: the popup comes
                            // back so a retry or Later is one click away -
                            // unless the user already said Later to this
                            // version in an earlier session.
                            let dismissed =
                                crate::update_check::CheckCache::load(&croft_cache_dir())
                                    .dismissed
                                    .as_deref()
                                    == Some(version.as_str());
                            if !dismissed {
                                self.update_toast = Some(UpdateToast {
                                    version: version.clone(),
                                    ready: false,
                                    buttons: Vec::new(),
                                });
                            }
                            format!(
                                "croft {version} could not be built - see {} (still on v{})",
                                staged_install_log_path().display(),
                                env!("CARGO_PKG_VERSION")
                            )
                        }
                        UpdateSource::SelfInstall => {
                            self.self_install = None;
                            format!(
                                "croft rebuild failed - see {} (still on the old binary)",
                                self_install_log_path().display()
                            )
                        }
                        UpdateSource::Watch => String::from(
                            "Background croft update failed; staying on current version",
                        ),
                    };
                }
                crate::update_watch::UpdateEvent::Ready => {
                    if staged {
                        self.staged_status = UpdateStatus::Ready;
                    } else {
                        self.update_status = UpdateStatus::Ready;
                    }
                    if !self.any_update_in_progress() {
                        self.update_spinner_start = None;
                    }
                    // Do NOT yank the user mid-work: surface a persistent
                    // "Update ready - F9 to relaunch" prompt in the status
                    // bar and let them pick the moment. The re-exec only
                    // fires when they press F9 (handle_key) or click
                    // Relaunch on the popup (#333).
                    self.status = String::from(
                        "Update ready - press F9 to relaunch croft (terminals will reset)",
                    );
                    if staged && let Some(install) = self.staged_install.as_ref() {
                        self.update_toast = Some(UpdateToast {
                            version: install.version.clone(),
                            ready: true,
                            buttons: Vec::new(),
                        });
                    }
                }
            }
        }
        changed
    }

    /// Current spinner glyph for an in-progress update (frame 0 when idle).
    fn update_spinner_glyph(&self) -> &'static str {
        match self.update_spinner_start {
            Some(t) => update_spinner_frame(t.elapsed().as_millis()),
            None => UPDATE_SPINNER_FRAMES[0],
        }
    }

    /// Monotonic spinner phase the main loop watches to force a redraw each
    /// time the glyph should advance. Stays `0` whenever no update is running,
    /// so it never wakes the renderer outside an active update.
    fn update_spinner_phase(&self) -> u128 {
        match self.update_spinner_start {
            Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
            None => 0,
        }
    }

    /// Spinner glyph for an in-flight extension command (frame 0 when idle).
    fn mcp_spinner_glyph(&self) -> &'static str {
        match self.mcp_started {
            Some(t) => update_spinner_frame(t.elapsed().as_millis()),
            None => UPDATE_SPINNER_FRAMES[0],
        }
    }

    /// Monotonic phase so the loop redraws each frame while an extension command
    /// runs (`0` when idle, so it never wakes the renderer otherwise).
    fn mcp_spinner_phase(&self) -> u128 {
        match self.mcp_started {
            Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
            None => 0,
        }
    }

    pub fn capture_session_state(&self) -> crate::session_state::SessionState {
        let mut tabs = Vec::new();
        let mut active_tab = 0;
        for (idx, ed) in self.editor.editors.iter().enumerate() {
            // Only plain text file tabs survive a re-exec; diff / sheet /
            // image tabs are derived views with no path to reopen from.
            if ed.has_non_text_view() {
                continue;
            }
            let Some(path) = ed.path.clone() else {
                continue;
            };
            if idx == self.editor.active_index() {
                active_tab = tabs.len();
            }
            let unsaved_text = if ed.dirty {
                Some(ed.lines.join("\n"))
            } else {
                None
            };
            tabs.push(crate::session_state::OpenTabState {
                path,
                cursor_row: ed.cursor_row,
                cursor_col: ed.cursor_col,
                scroll: ed.scroll,
                scroll_col: ed.scroll_col,
                dirty: ed.dirty,
                unsaved_text,
            });
        }
        crate::session_state::SessionState {
            workspace_root: self.workspace_root().to_path_buf(),
            tabs,
            active_tab,
            sidebar_view: sidebar_view_label(self.sidebar_view).to_string(),
            sidebar_width: self.sidebar_width,
            terminal_height: self.terminal_height,
            focus_editor: self.focus == Pane::Editor,
        }
    }

    fn apply_session_state(&mut self, state: &crate::session_state::SessionState) {
        for tab in &state.tabs {
            if self.editor.open_pinned(&tab.path).is_err() {
                continue;
            }
            let Some(ed) = self
                .editor
                .editors
                .iter_mut()
                .find(|e| e.path.as_deref() == Some(tab.path.as_path()))
            else {
                continue;
            };
            if tab.dirty
                && let Some(text) = &tab.unsaved_text
            {
                ed.lines = text.split('\n').map(str::to_string).collect();
                if ed.lines.is_empty() {
                    ed.lines.push(String::new());
                }
                ed.dirty = true;
                // Make the restored unsaved content eligible for auto save:
                // due() keys on last_edit_at, which a fresh Editor lacks.
                ed.last_edit_at = Some(std::time::Instant::now());
            }
            let max_row = ed.lines.len().saturating_sub(1);
            ed.cursor_row = tab.cursor_row.min(max_row);
            let max_col = ed.lines.get(ed.cursor_row).map_or(0, |l| l.chars().count());
            ed.cursor_col = tab.cursor_col.min(max_col);
            ed.scroll = tab.scroll;
            ed.scroll_col = tab.scroll_col;
        }
        if state.active_tab < self.editor.tab_count() {
            self.editor.select(state.active_tab);
        }
        if let Some(view) = sidebar_view_from_label(&state.sidebar_view) {
            self.set_sidebar_view(view);
        }
        self.sidebar_width = state.sidebar_width;
        self.terminal_height = state.terminal_height;
        self.focus = if state.focus_editor {
            Pane::Editor
        } else {
            Pane::Tree
        };
    }

    fn tear_down_connect_auth(&mut self) {
        if let Some(mut auth) = self.connect_auth.take() {
            auth.cancel();
        }
        self.install_session = None;
        self.pending_remote_launch_host = None;
        self.pending_remote_launch_path = None;
    }

    pub fn handle_connect_dialog_key(&mut self, key: KeyEvent) {
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return;
        };
        if dialog.phase.is_terminal() {
            if matches!(key.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char(' ')) {
                self.connect_dialog = None;
                self.tear_down_connect_auth();
            }
            return;
        }
        let has_mod = key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
        match key.code {
            KeyCode::Esc => {
                self.connect_dialog = None;
                self.tear_down_connect_auth();
                self.status = String::from("Connect cancelled");
            }
            KeyCode::Enter => {
                if !dialog.phase.awaits_input() {
                    return;
                }
                if matches!(
                    dialog.phase,
                    crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
                ) {
                    let payload = dialog.input_for_submit();
                    self.answer_install_fallback(&payload);
                    return;
                }
                let payload = dialog.input_for_submit();
                dialog.submitted = true;
                dialog.status_line = format!("Verifying credentials with {}", dialog.host);
                dialog.clear_input();
                if let Some(auth) = self.connect_auth.as_mut() {
                    auth.respond_password(&payload);
                }
            }
            KeyCode::Backspace => dialog.pop_input_char(),
            KeyCode::Char('l') | KeyCode::Char('L') if has_mod || !dialog.phase.awaits_input() => {
                dialog.toggle_logs();
            }
            KeyCode::Char(c) if !has_mod => dialog.push_input_char(c),
            _ => {}
        }
    }

    pub fn handle_connect_dialog_click(&mut self, col: u16, row: u16) -> bool {
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return false;
        };
        if rect_contains(dialog.toggle_logs_btn, col, row) {
            dialog.toggle_logs();
            return true;
        }
        if rect_contains(dialog.cancel_btn, col, row) {
            self.connect_dialog = None;
            self.tear_down_connect_auth();
            self.status = String::from("Connect cancelled");
            return true;
        }
        if rect_contains(dialog.submit_btn, col, row) && dialog.phase.awaits_input() {
            if matches!(
                dialog.phase,
                crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
            ) {
                let payload = dialog.input_for_submit();
                self.answer_install_fallback(&payload);
                return true;
            }
            let payload = dialog.input_for_submit();
            dialog.submitted = true;
            dialog.status_line = format!(
                "Sending {} chars to {}",
                payload.chars().count(),
                dialog.host
            );
            dialog.clear_input();
            if let Some(auth) = self.connect_auth.as_mut() {
                auth.respond_password(&payload);
            }
            return true;
        }
        rect_contains(dialog.last_area, col, row)
    }

    /// Resolve the connect dialog's slow-fallback question. "y"/"yes"
    /// continues with the compile-on-remote install; anything else aborts
    /// the connect so the user can run `croft setup-cross` and reconnect
    /// for the seconds-fast prebuilt-binary path.
    fn answer_install_fallback(&mut self, payload: &str) {
        let proceed = matches!(payload.trim().to_ascii_lowercase().as_str(), "y" | "yes");
        if proceed {
            if let Some(dialog) = self.connect_dialog.as_mut() {
                dialog.set_installing();
            }
            if let Some(session) = self.install_session.as_ref() {
                session.respond_fallback(true);
            }
            return;
        }
        if let Some(session) = self.install_session.as_ref() {
            session.respond_fallback(false);
        }
        self.connect_dialog = None;
        self.tear_down_connect_auth();
        self.status = String::from(
            "Connect cancelled — run `croft setup-cross`, then reconnect for a fast install",
        );
    }

    fn open_ssh_config_in_editor(&mut self) {
        let Some(path) = crate::remote::primary_ssh_config_path() else {
            self.status = String::from("Cannot find $HOME/.ssh/config");
            return;
        };
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        if !path.exists()
            && let Err(e) = std::fs::write(&path, "")
        {
            self.status = format!("Could not create {}: {e}", path.display());
            return;
        }
        match self.editor.open_pinned(&path) {
            Ok(()) => {
                self.focus_pane(Pane::Editor);
                self.status = format!("Opened {}", self.status_path(&path));
            }
            Err(e) => {
                self.status = format!("Open {} failed: {e}", self.status_path(&path));
            }
        }
    }

    fn open_ssh_learn_more(&mut self) {
        let url = "https://man.openbsd.org/ssh_config";
        if self.drop_relay_active() {
            if self.trust_local_browser {
                self.request_remote_url_open(url.to_string());
                self.status = String::from("Opening ssh_config(5) on your local Mac");
            } else {
                self.pending_local_open = Some(url.to_string());
            }
            return;
        }
        match open_url(url) {
            Ok(()) => self.status = String::from("Opened ssh_config(5) docs"),
            Err(e) => self.status = format!("Open link failed: {e}"),
        }
    }

    fn refresh_remote_if_config_changed(&mut self) -> bool {
        if self.sidebar_view != SidebarView::Remote {
            return false;
        }
        if !self.remote.refresh_if_config_changed() {
            return false;
        }
        self.status = String::from("Reloaded SSH remotes");
        true
    }

    fn open_search_hit(&mut self, hit: &crate::widgets::search::SearchHit) {
        match self.editor.open_preview(&hit.path) {
            Ok(()) => {
                self.sync_open_file_poll_mtime();
                let row = hit
                    .line_no
                    .saturating_sub(1)
                    .min(self.editor.lines.len().saturating_sub(1));
                self.editor.cursor_row = row;
                // Drop the cursor at the first match column on this line so
                // long lines (HTML with base64 blobs, minified JS) auto-scroll
                // horizontally and the user lands on the match instead of the
                // line's leftmost cell - which on a 200k-char line means
                // never seeing the match without manual scrolling.
                let needle = self.search.query.trim();
                let opts = self.search.opts;
                let line = self.editor.lines.get(row).cloned().unwrap_or_default();
                // Locate the first match on the line: its start column and
                // length (in chars). The length lets us mark this occurrence
                // as the *active* match so the renderer paints it the stronger
                // orange while sibling matches stay yellow - mirroring the
                // Cmd+F path's `active_search_match` behaviour and VS Code's
                // "current match" highlight.
                let first_match = if needle.is_empty() {
                    None
                } else {
                    let mut col = 0usize;
                    let mut found = None;
                    for (chunk, is_match) in
                        crate::widgets::search::split_for_highlight(&line, needle, opts)
                    {
                        if is_match {
                            found = Some((col, chunk.chars().count()));
                            break;
                        }
                        col = col.saturating_add(chunk.chars().count());
                    }
                    found
                };
                let match_col = first_match.map(|(c, _)| c).unwrap_or(0);
                self.editor.active_search_match = first_match.map(|(c, len)| (row, c, len));
                self.editor.cursor_col = match_col;
                self.editor.scroll_col = 0;
                self.editor.ensure_cursor_col_visible();
                self.status = format!(
                    "Opened {} at line {}",
                    self.status_path(&hit.path),
                    hit.line_no
                );
                self.focus_pane(Pane::Editor);
            }
            Err(e) => {
                self.status = format!("Open failed: {e}");
            }
        }
    }

    fn handle_tree_key(&mut self, key: KeyEvent) {
        // Delete key (or Cmd+Backspace) trashes every selected node.
        if is_delete_node_key(key) {
            self.delete_selection();
            return;
        }
        if is_editor_select_all_key(key) {
            self.tree.select_all_visible();
            return;
        }
        if is_editor_copy_key(key) {
            self.copy_selection_to_explorer_clipboard(ExplorerClipMode::Copy);
            return;
        }
        if is_editor_cut_key(key) {
            self.copy_selection_to_explorer_clipboard(ExplorerClipMode::Cut);
            return;
        }
        if is_clipboard_paste_key(key) {
            self.paste_explorer_clipboard();
            return;
        }
        if is_compare_key(key) {
            self.toggle_compare_on_selected_file();
            return;
        }
        if key.code == KeyCode::Esc {
            if !self.tree.marked.is_empty() {
                self.tree.clear_marks();
            }
            return;
        }
        let extending = key.modifiers.contains(KeyModifiers::SHIFT);
        match key.code {
            KeyCode::Up => {
                if extending {
                    self.tree.move_up_extend();
                } else {
                    self.tree.move_up();
                }
            }
            KeyCode::Down => {
                if extending {
                    self.tree.move_down_extend();
                } else {
                    self.tree.move_down();
                }
            }
            KeyCode::PageUp => {
                if extending {
                    self.tree.page_up_extend(10);
                } else {
                    self.tree.page_up(10);
                }
            }
            KeyCode::PageDown => {
                if extending {
                    self.tree.page_down_extend(10);
                } else {
                    self.tree.page_down(10);
                }
            }
            KeyCode::Home => {
                if extending {
                    self.tree.home_extend();
                } else {
                    self.tree.home();
                }
            }
            KeyCode::End => {
                if extending {
                    self.tree.end_extend();
                } else {
                    self.tree.end();
                }
            }
            KeyCode::Enter => {
                if let Some(path) = self.tree.activate() {
                    // Ctrl+Enter is the primary "open in new tab" gesture — it
                    // reaches the app on every terminal. Cmd+Enter is also
                    // accepted but iTerm2 binds it to Toggle Fullscreen by
                    // default and never forwards it to the app unless the user
                    // has remapped that shortcut in iTerm Preferences →
                    // Profiles → Keys.
                    let in_new_tab = key.modifiers.intersects(
                        KeyModifiers::CONTROL | KeyModifiers::SUPER | KeyModifiers::META,
                    );
                    let result = if in_new_tab {
                        self.editor.open_pinned(&path)
                    } else {
                        self.editor.open_preview(&path)
                    };
                    match result {
                        Ok(()) => {
                            self.sync_open_file_poll_mtime();
                            self.status = self.editor.status.clone();
                            // Hand the keyboard to the editor, as VS Code does
                            // on Enter. Without this every navigation key the
                            // new tab defines is dead on arrival - arrows walk
                            // the file list while a PDF sits frozen on page 1
                            // and a spreadsheet never scrolls. Right-arrow
                            // (below) is the gesture that previews *without*
                            // leaving the tree.
                            self.focus_pane(Pane::Editor);
                        }
                        Err(e) => {
                            self.status = format!("Error: {e}");
                        }
                    }
                }
            }
            KeyCode::Right => {
                let selected_is_dir = self
                    .tree
                    .nodes
                    .get(self.tree.selected)
                    .is_some_and(|node| node.is_dir);
                if selected_is_dir {
                    self.tree.expand_selected();
                } else if let Some(path) = self.tree.activate() {
                    let result = self.editor.open_preview(&path);
                    match result {
                        Ok(()) => {
                            self.sync_open_file_poll_mtime();
                            self.status = self.editor.status.clone();
                        }
                        Err(e) => {
                            self.status = format!("Error: {e}");
                        }
                    }
                }
            }
            KeyCode::Left => {
                self.tree.collapse_selected();
            }
            KeyCode::Char(c)
                if !key.modifiers.intersects(
                    KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
                ) =>
            {
                self.apply_tree_typeahead(c, std::time::Instant::now());
            }
            _ => {}
        }
    }

    /// Flip native modal (vim) editing on or off. Driven by the global Cmd+E
    /// shortcut, so it can fire from any pane. Turning it off also dismisses
    /// any lingering `/` `?` search-match highlights, since the modal layer is
    /// the only place that clears them.
    fn toggle_vim_mode(&mut self) {
        // The Vim modal layer is a bundled, toggleable extension: when disabled
        // in the Extensions panel, Cmd+E is inert (and any active session is
        // force-ended so a disable can't strand the editor in modal mode).
        if !self.is_extension_enabled("vim") {
            if self.vim.enabled {
                self.vim.toggle();
            }
            self.status = String::from("Vim extension is disabled");
            return;
        }
        self.vim.toggle();
        if self.vim.enabled {
            self.status = String::from("vim mode on");
        } else {
            self.editor
                .set_search_highlight(None, crate::widgets::search::SearchOpts::default());
            self.status = String::from("vim mode off");
        }
    }

    /// True when the active editor tab holds an editable text buffer (not a
    /// read-only diff / spreadsheet / image preview), so text-editing chords
    /// know whether to act.
    fn editor_is_text(&self) -> bool {
        !self.editor.has_non_text_view() && self.editor.markdown_preview.is_none()
    }

    /// Markdown: Toggle Preview — flips the active tab between source and the
    /// rendered view; explains itself on a non-Markdown tab.
    fn toggle_markdown_preview(&mut self) {
        if self.editor.toggle_markdown_preview() {
            self.status = if self.editor.markdown_preview.is_some() {
                String::from("Markdown Preview")
            } else {
                String::from("Markdown source")
            };
        } else {
            self.status = String::from("Markdown Preview needs a Markdown file");
        }
    }

    fn handle_editor_key(&mut self, key: KeyEvent) {
        // Inline find bar (Cmd+F / Ctrl+F) eats every key while open.
        if self.editor_find.is_some() {
            self.handle_editor_find_key(key);
            return;
        }
        // F7 / Shift+F7 in a buffer with merge conflicts: jump between the
        // blocks, the same chord the diff view uses for its hunks (VS Code's
        // "Go to Next/Previous Conflict"). Only claimed while conflicts
        // exist, so F7 keeps its normal meaning everywhere else.
        if matches!(key.code, KeyCode::F(7)) && !self.editor.conflicts().is_empty() {
            self.jump_conflict(key.modifiers.contains(KeyModifiers::SHIFT));
            return;
        }
        // Merge editor (#253): F7 hops the tracked Result regions (the
        // Result has no markers, so the arm above never claims it) and
        // Alt+Up/Down scrolls the source panes together. Every other key
        // falls through to the ordinary text path — the Result is a real
        // buffer.
        if self.editor.merge.is_some() {
            if matches!(key.code, KeyCode::F(7)) {
                self.merge_jump(key.modifiers.contains(KeyModifiers::SHIFT));
                return;
            }
            if key.modifiers.contains(KeyModifiers::ALT)
                && matches!(key.code, KeyCode::Up | KeyCode::Down)
            {
                let delta = if key.code == KeyCode::Up { -3 } else { 3 };
                if let Some(mv) = self.editor.merge.as_mut() {
                    mv.scroll_panes(delta);
                }
                return;
            }
        }
        if is_editor_find_key(key) {
            self.open_editor_find();
            return;
        }
        if is_editor_replace_key(key) {
            self.open_editor_replace();
            return;
        }
        // `.http`/`.rest` (#370): Cmd/Ctrl+Enter sends the request under
        // the caret, REST Client's own chord. Checked BEFORE the runnable
        // fence (#353), which claims the same chord: this arm is scoped to
        // request files, so the two compose — a `.http` file sends, and
        // every other file falls through to the fence path with its
        // meaning intact.
        if matches!(key.code, KeyCode::Enter)
            && key
                .modifiers
                .intersects(KeyModifiers::SUPER | KeyModifiers::CONTROL)
            && self
                .editor
                .path
                .as_deref()
                .is_some_and(crate::http_file::is_http_file)
        {
            self.send_http_request_under_caret();
            return;
        }
        // Runnable docs (#353): Cmd+Enter runs the fence under the caret.
        if is_run_fence_key(key) && self.focus == Pane::Editor && self.run_fence_at_cursor() {
            return;
        }
        // Markdown: Toggle Preview (Cmd/Ctrl+Shift+V, the VS Code default).
        if is_markdown_preview_key(key) {
            self.toggle_markdown_preview();
            return;
        }
        // While the rendered preview is up the buffer is not visible, so
        // navigation scrolls the preview and every other key is swallowed
        // (no invisible edits). Cmd+Shift+V above flips back to the source.
        if self.editor.markdown_preview.is_some() {
            // Copy Path / Copy Relative Path first: their chords are
            // Cmd+Opt+C and Cmd+Opt+Shift+C, which the looser copy-key
            // predicate below also matches. They are meaningful while a
            // preview is up (the file has a path either way), and this
            // block returns unconditionally, so they must be dispatched
            // here or they never run.
            if is_copy_path_key(key) {
                if let Some(path) = self.editor.path.clone() {
                    self.copy_path_to_clipboard(path);
                }
                return;
            }
            if is_copy_relative_path_key(key) {
                if let Some(path) = self.editor.path.clone() {
                    self.copy_relative_path_to_clipboard(path);
                }
                return;
            }
            // Copy the rendered selection (#215): the preview swallows every
            // other key, so without this branch Cmd+C here never copies.
            if is_editor_copy_key(key) {
                self.copy_editor_selection();
                return;
            }
            if matches!(key.code, KeyCode::Esc)
                && let Some(md) = self.editor.markdown_preview.as_mut()
                && md.has_selection()
            {
                md.selection = None;
                md.dragging = false;
                return;
            }
            let page = self.editor.text_rows() as i32;
            match key.code {
                KeyCode::Up => {
                    self.editor.scroll_markdown_preview(-1);
                }
                KeyCode::Down => {
                    self.editor.scroll_markdown_preview(1);
                }
                KeyCode::PageUp => {
                    self.editor.scroll_markdown_preview(-page);
                }
                KeyCode::PageDown | KeyCode::Char(' ') => {
                    self.editor.scroll_markdown_preview(page);
                }
                KeyCode::Home => {
                    self.editor.scroll_markdown_preview(i16::MIN as i32);
                }
                // The render pass clamps to the wrapped height, so jumping
                // far past the end lands exactly on the last page.
                KeyCode::End => {
                    self.editor.scroll_markdown_preview(i16::MAX as i32);
                }
                _ => {}
            }
            return;
        }
        // Completion popup intercepts navigation / accept / dismiss keys
        // before normal editor handling. Any other key dismisses the popup
        // and falls through so the character lands in the buffer.
        if self.handle_completion_popup_key(key) {
            return;
        }
        // A snippet tab-stop session survives only plain typing, Backspace, and
        // Tab (which advances it). Any other key ends the session so Tab returns
        // to its normal indent role.
        if self.editor.snippet_active() && !snippet_key_continues(key) {
            self.editor.cancel_snippet();
        }
        // Esc closes the parameter-hints popup first (VS Code parity); a second
        // Esc then falls through to clear the selection / collapse cursors.
        if self.signature_help_popup.is_some() && matches!(key.code, KeyCode::Esc) {
            self.dismiss_signature_help();
            return;
        }
        // F4: focus the active file's next navigator comment box;
        // Shift+F4 ignores the nearest one.
        if matches!(key.code, KeyCode::F(4)) {
            if key.modifiers == KeyModifiers::SHIFT {
                self.ignore_focused_comment();
                return;
            }
            if key.modifiers.is_empty() {
                self.cycle_comment_box();
                return;
            }
        }
        if is_completion_trigger_key(key) {
            self.trigger_completion();
            return;
        }
        // Rename Symbol (F2) and Change All Occurrences (Cmd/Ctrl+F2) are only
        // meaningful on a text buffer, so they sit above the read-only diff /
        // sheet / image guards below.
        if is_rename_symbol_key(key) {
            self.start_rename_symbol();
            return;
        }
        if is_change_all_occurrences_key(key) {
            self.start_change_all_occurrences();
            return;
        }
        if is_select_next_occurrence_key(key) {
            self.start_select_next_occurrence();
            return;
        }
        if is_delete_line_key(key) {
            self.delete_current_line();
            return;
        }
        // VS Code "Reveal in Finder" (Cmd+Opt+R) for the active file. Works on
        // any tab backed by a real path (text, diff, sheet, image), so it sits
        // above the text-only guards. Local-macOS only, matching the Explorer
        // chord and the tab-menu entry; withheld on remote/headless sessions.
        if !self.is_remote && cfg!(target_os = "macos") && is_reveal_in_finder_key(key) {
            if let Some(path) = self.editor.path.clone() {
                self.reveal_in_finder(path);
            }
            return;
        }
        // VS Code "Copy Path" (Cmd+Opt+C): copy the active file's absolute path
        // to the clipboard. Works on any tab with a real path, local or remote;
        // a blank/untitled buffer is a no-op (the keystroke is still swallowed).
        if is_copy_path_key(key) {
            if let Some(path) = self.editor.path.clone() {
                self.copy_path_to_clipboard(path);
            }
            return;
        }
        // VS Code "Copy Relative Path" (Cmd+Opt+Shift+C): copy the active file's
        // path relative to the workspace root. Same path-or-no-op rule as Copy
        // Path; the keystroke is swallowed even on a blank/untitled buffer.
        if is_copy_relative_path_key(key) {
            if let Some(path) = self.editor.path.clone() {
                self.copy_relative_path_to_clipboard(path);
            }
            return;
        }
        // VS Code "Toggle Line Comment" (Cmd+/ / Ctrl+/), "Toggle Block
        // Comment" (Shift+Alt+A), and "View: Toggle Word Wrap" (Alt+Z). All
        // act on a text buffer, so they no-op on read-only diff / sheet /
        // image tabs (the keystroke is still swallowed). Each is also
        // reachable from the Command Palette, which guarantees parity on
        // terminals that don't deliver the Alt+letter chords.
        if is_toggle_line_comment_key(key) {
            if self.editor_is_text() {
                self.editor.toggle_line_comment();
            }
            return;
        }
        if is_toggle_block_comment_key(key) {
            if self.editor_is_text() {
                self.editor.toggle_block_comment();
            }
            return;
        }
        if is_toggle_wrap_key(key) {
            if self.editor_is_text() {
                self.editor.toggle_wrap();
            }
            return;
        }
        // VS Code "Go to Bracket" (Cmd+Shift+\): jump the cursor to the
        // matching bracket. Also reachable from the Command Palette.
        if is_goto_bracket_key(key) {
            if self.editor_is_text() {
                self.editor.jump_to_matching_bracket();
            }
            return;
        }
        // VS Code "Select to Bracket" (Cmd+Opt+\): select the region between
        // the matching brackets, including the brackets.
        if is_select_to_bracket_key(key) {
            if self.editor_is_text() {
                self.editor.select_to_matching_bracket();
            }
            return;
        }
        // VS Code "Go Back" (Ctrl+-): the keyboard twin of the
        // Ctrl+Shift+click chord, so navigation history is reachable
        // without depending on the host terminal's mouse delivery (#31).
        if is_navigate_forward_key(key) {
            self.nav_forward();
            return;
        }
        if is_navigate_back_key(key) {
            self.nav_back();
            return;
        }
        // VS Code "Transpose Characters around the Cursor" (Ctrl+T).
        if is_transpose_key(key) {
            if self.editor_is_text() {
                self.editor.transpose_chars();
            }
            return;
        }
        // VS Code "Convert Indentation to Spaces" (Cmd+Opt+Shift+S).
        if is_indentation_to_spaces_key(key) {
            if self.editor_is_text() {
                self.editor.indentation_to_spaces();
                self.status = String::from("Converted indentation to spaces");
            }
            return;
        }
        // VS Code "Convert Indentation to Tabs" (Cmd+Opt+Shift+T).
        if is_indentation_to_tabs_key(key) {
            if self.editor_is_text() {
                self.editor.indentation_to_tabs();
                self.status = String::from("Converted indentation to tabs");
            }
            return;
        }
        // VS Code's `files.trimFinalNewlines`, as a command (Cmd+Opt+Shift+N).
        if is_trim_final_newlines_key(key) {
            if self.editor_is_text() && self.editor.trim_final_newlines() {
                self.status = String::from("Trimmed final newlines");
            }
            return;
        }
        // Formerly palette-only editor commands, now each on a chord so none
        // ships without an accelerator (croft tenet: everything has a shortcut).
        if is_join_lines_key(key) {
            if self.editor_is_text() {
                self.editor.join_lines();
            }
            return;
        }
        if is_transform_upper_key(key) {
            if self.editor_is_text() {
                self.editor
                    .transform_selection_case(crate::widgets::editor::CaseTransform::Upper);
            }
            return;
        }
        if is_transform_lower_key(key) {
            if self.editor_is_text() {
                self.editor
                    .transform_selection_case(crate::widgets::editor::CaseTransform::Lower);
            }
            return;
        }
        if is_sort_lines_asc_key(key) {
            if self.editor_is_text() {
                self.editor.sort_lines(true);
            }
            return;
        }
        if is_sort_lines_desc_key(key) {
            if self.editor_is_text() {
                self.editor.sort_lines(false);
            }
            return;
        }
        if is_trim_trailing_whitespace_key(key) {
            if self.editor_is_text() && self.editor.trim_trailing_whitespace() {
                self.status = String::from("Trimmed trailing whitespace");
            }
            return;
        }
        // VS Code "Format Document" (Cmd+Opt+Shift+F): reformat the whole buffer
        // through the language server. No-op on read-only diff / sheet / image.
        if is_format_document_key(key) {
            if self.editor_is_text() {
                self.start_format_document();
            }
            return;
        }
        // VS Code "Quick Fix" (Cmd+. / Ctrl+.): code actions at the cursor.
        if is_quick_fix_key(key) {
            if self.editor_is_text() {
                self.start_code_action();
            }
            return;
        }
        // Go to Definition (F12) / References (Shift+F12) / Type Definition
        // (Ctrl+F12) / Implementations (Cmd+F12) / Declaration (Ctrl+Shift+F12),
        // the VS Code F12-family bindings, also need a real text buffer. All are
        // no-ops on read-only diff / sheet / image tabs; the keystroke is still
        // swallowed so it never leaks into the buffer.
        if is_peek_definition_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.peek_definition_at_cursor();
            }
            return;
        }
        if is_go_to_definition_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_definition_at_cursor();
            }
            return;
        }
        if is_go_to_declaration_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_declaration_at_cursor();
            }
            return;
        }
        if is_go_to_type_definition_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_type_definition_at_cursor();
            }
            return;
        }
        if is_go_to_implementation_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_implementation_at_cursor();
            }
            return;
        }
        if is_go_to_references_key(key) {
            if self.editor.diff.is_none()
                && self.editor.sheet.is_none()
                && self.editor.image.is_none()
            {
                self.request_references_at_cursor();
            }
            return;
        }
        // While multi-cursor mode is live, printable typing / backspace /
        // delete fan out to every caret and Esc collapses back to one cursor.
        // Any other key collapses the carets and falls through to normal
        // single-cursor handling (e.g. an arrow moves just the primary).
        if self.editor.has_multi_cursor() {
            match key.code {
                KeyCode::Esc => {
                    self.editor.collapse_carets();
                    self.status = String::from("Cursors collapsed");
                    return;
                }
                KeyCode::Backspace => {
                    self.editor.multi_backspace();
                    return;
                }
                KeyCode::Delete => {
                    self.editor.multi_delete_forward();
                    return;
                }
                KeyCode::Char(c)
                    if !key.modifiers.contains(KeyModifiers::CONTROL)
                        && !key.modifiers.contains(KeyModifiers::ALT)
                        && !key.modifiers.contains(KeyModifiers::SUPER) =>
                {
                    self.editor.multi_insert_char(c);
                    return;
                }
                _ => self.editor.collapse_carets(),
            }
        }
        // Close-tab (Cmd/Ctrl+W) applies to every tab type, so it sits above
        // the read-only diff / sheet / image guards below. Those guards each
        // short-circuit to a view-specific handler that has no close branch,
        // so without this hoist Cmd+W is silently swallowed on a diff, sheet,
        // or image tab and the tab can never be closed from the keyboard.
        if is_close_tab_key(key) {
            self.record_closed_tab_at(self.editor.active_index());
            if self.editor.close_active() {
                self.sync_open_file_poll_mtime();
                self.status = String::from("Closed tab");
                // Closing the focused group's last tab while split closes
                // the group: collapse back to the surviving column.
                self.collapse_split_if_empty();
            } else {
                self.status = String::from("Cannot close last tab");
            }
            return;
        }
        if self.editor.diff.is_some() {
            self.handle_diff_key(key);
            return;
        }
        if self.editor.sheet.is_some() {
            self.handle_sheet_key(key);
            return;
        }
        if self.editor.hex.is_some() {
            self.handle_hex_key(key);
            return;
        }
        if self.editor.archive.is_some() {
            self.handle_archive_key(key);
            return;
        }
        // Image preview tabs are read-only. PDF tabs page with every
        // navigation key (arrows, PageUp/PageDown, Space, Home/End) and with
        // the wheel; everything else is swallowed.
        if self.editor.image.is_some() {
            match key.code {
                KeyCode::Right | KeyCode::PageDown | KeyCode::Down | KeyCode::Char(' ') => {
                    self.step_pdf_page(1);
                }
                KeyCode::Left | KeyCode::PageUp | KeyCode::Up => {
                    self.step_pdf_page(-1);
                }
                KeyCode::Home => self.jump_pdf_page(1),
                KeyCode::End => self.jump_pdf_page(u32::MAX),
                _ => {}
            }
            return;
        }
        // When modal editing is on it fully owns the editor pane and the
        // always-on `editor_vim_chord` convenience layer is bypassed. A
        // PassThrough means the key is not claimed by vim (Insert-mode typing,
        // or any Cmd/Ctrl shortcut in Normal mode) and falls through to the
        // editor's normal handling below.
        if self.vim.enabled {
            match self.vim.on_key(key) {
                crate::vim::VimKeyResult::Consumed(actions) => {
                    for action in actions {
                        self.apply_vim_action(action);
                    }
                    return;
                }
                crate::vim::VimKeyResult::PassThrough => {}
            }
        } else if self.handle_editor_vim_chord(key) {
            return;
        }
        if is_editor_line_home_key(key) {
            self.editor.clear_selection();
            self.editor.home_line();
            return;
        }
        if is_editor_line_end_key(key) {
            self.editor.clear_selection();
            self.editor.end_line();
            return;
        }
        if is_editor_kill_to_eol_key(key) {
            let killed = self.editor.kill_to_eol();
            if !killed.is_empty() {
                copy_to_clipboard(&killed);
                self.status = format!("Killed {} chars", killed.chars().count());
            }
            return;
        }
        if is_editor_kill_to_bol_key(key) {
            let killed = self.editor.kill_to_bol();
            if !killed.is_empty() {
                copy_to_clipboard(&killed);
                self.status = format!("Killed {} chars", killed.chars().count());
            }
            return;
        }
        if is_editor_open_line_below_key(key) {
            self.editor.open_line_below();
            self.status = String::from("Opened line below");
            return;
        }
        if is_editor_open_line_above_key(key) {
            self.editor.open_line_above();
            self.status = String::from("Opened line above");
            return;
        }
        // Clipboard gestures take precedence over text input. They never
        // conflict with normal typing (Ctrl/Cmd + C/X/A) so the order is
        // safe even when the user is in the middle of editing.
        if is_editor_copy_key(key) {
            self.copy_editor_selection();
            return;
        }
        if is_editor_cut_key(key) {
            self.cut_editor_selection();
            return;
        }
        if is_editor_paste_key(key) {
            let text = (self.clipboard_reader)();
            self.paste_clipboard_into_editor(text.as_deref());
            return;
        }
        if is_editor_select_all_key(key) {
            self.editor.select_all();
            self.status = format!(
                "Selected {} chars",
                self.editor.selection_text().chars().count()
            );
            return;
        }
        if is_editor_undo_key(key) {
            if self.editor.undo() {
                self.status = String::from("Undo");
            } else {
                self.status = String::from("Nothing to undo");
            }
            return;
        }
        if is_editor_redo_key(key) {
            if self.editor.redo() {
                self.status = String::from("Redo");
            } else {
                self.status = String::from("Nothing to redo");
            }
            return;
        }
        if let Some(idx) = jump_to_tab_index(key) {
            if self.editor.select(idx) {
                self.sync_open_file_poll_mtime();
                self.status = format!("Tab {}", idx + 1);
            }
            return;
        }
        if matches!(key.code, KeyCode::Esc) && self.editor.selection.is_some() {
            self.editor.clear_selection();
            return;
        }

        // Shift+<motion> extends selection in the motion's direction.
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let is_motion = matches!(
            key.code,
            KeyCode::Up
                | KeyCode::Down
                | KeyCode::Left
                | KeyCode::Right
                | KeyCode::Home
                | KeyCode::End
                | KeyCode::PageUp
                | KeyCode::PageDown
        );
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        // The command modifier: Cmd (SUPER) on macOS, Ctrl on Linux / Termux.
        let cmd = key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL);
        // VS Code "Add Cursor Above/Below" (Cmd+Opt+Up / Cmd+Opt+Down). Must
        // come before the plain-Alt move-line check so the cmd+alt combo is
        // routed here, not there.
        if cmd && alt && matches!(key.code, KeyCode::Up | KeyCode::Down) {
            match key.code {
                KeyCode::Up => self.editor.add_cursor_above(),
                KeyCode::Down => self.editor.add_cursor_below(),
                _ => unreachable!(),
            }
            return;
        }
        if shift && alt && matches!(key.code, KeyCode::Up | KeyCode::Down) {
            match key.code {
                KeyCode::Up => self.editor.duplicate_lines_up(),
                KeyCode::Down => self.editor.duplicate_lines_down(),
                _ => unreachable!(),
            }
            return;
        }
        // Expand / Shrink Selection (#254): Shift+Alt+Right/Left, VS Code's
        // smart-select chords. This deliberately claims what used to be
        // word-wise selection extension — the same collision VS Code
        // resolves the same way.
        if shift && alt && !cmd && matches!(key.code, KeyCode::Left | KeyCode::Right) {
            if key.code == KeyCode::Right {
                self.expand_selection();
            } else {
                self.shrink_selection();
            }
            return;
        }
        // VS Code "Move Line Up/Down" (Alt+Up / Alt+Down, no Shift, no Cmd).
        if alt && !shift && !cmd && matches!(key.code, KeyCode::Up | KeyCode::Down) {
            match key.code {
                KeyCode::Up => self.editor.move_lines_up(),
                KeyCode::Down => self.editor.move_lines_down(),
                _ => unreachable!(),
            }
            return;
        }
        if is_motion && shift {
            if self.editor.selection.is_none() {
                self.editor.start_selection_at_cursor();
            }
            match key.code {
                KeyCode::Up => self.editor.move_up(),
                KeyCode::Down => self.editor.move_down(),
                KeyCode::Left if alt => self.editor.move_word_left(),
                KeyCode::Right if alt => self.editor.move_word_right(),
                KeyCode::Left => self.editor.move_left(),
                KeyCode::Right => self.editor.move_right(),
                KeyCode::Home => self.editor.home_line(),
                KeyCode::End => self.editor.end_line(),
                KeyCode::PageUp => self.editor.page_up_one_screen(),
                KeyCode::PageDown => self.editor.page_down_one_screen(),
                _ => {}
            }
            self.editor.extend_selection_to_cursor();
            return;
        }
        if is_motion {
            // Plain motion clears any prior selection (VS Code / Sublime
            // convention: arrows without Shift collapse the selection).
            self.editor.clear_selection();
        }

        match key.code {
            KeyCode::Up => self.editor.move_up(),
            KeyCode::Down => self.editor.move_down(),
            KeyCode::Left if alt => self.editor.move_word_left(),
            KeyCode::Right if alt => self.editor.move_word_right(),
            KeyCode::Left => self.editor.move_left(),
            KeyCode::Right => self.editor.move_right(),
            KeyCode::PageUp => self.editor.page_up_one_screen(),
            KeyCode::PageDown => self.editor.page_down_one_screen(),
            KeyCode::Home => self.editor.home_line(),
            KeyCode::End => self.editor.end_line(),
            KeyCode::Backspace => self.editor.backspace(),
            KeyCode::Delete => self.editor.delete_forward(),
            KeyCode::Enter => self.editor.insert_newline(),
            // Tab advances a live snippet, else expands a snippet whose prefix
            // was just typed, else indents (whole block for a multi-line
            // selection, otherwise to the next tab stop).
            KeyCode::Tab => self.handle_editor_tab(),
            // Shift+Tab arrives as BackTab. Outdent the current line, or every
            // line a selection touches, mirroring VS Code's Shift+Tab.
            KeyCode::BackTab => self.editor.dedent_lines(),
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !key.modifiers.contains(KeyModifiers::SUPER) =>
            {
                self.editor.insert_char(c);
                // `.` is the canonical LSP trigger character for member
                // access in Python / TS / Rust. Fire a completion request
                // immediately so the popup pops without a Ctrl+Space.
                // The popup's fallthrough already dismissed any prior
                // popup when this char arrived, so the new request just
                // populates a fresh popup when the response lands.
                if c == '.' {
                    self.trigger_completion();
                }
                // Parameter hints: `(` / `,` open or advance a call. Closing
                // (typing `)`, moving away, deleting) is handled by the tick's
                // re-query, which also covers nested calls.
                if is_signature_help_trigger(c) {
                    self.trigger_signature_help();
                }
            }
            _ => {}
        }
    }

    /// Vim-style chord layer for the editor: `cmd+gg` jumps to top, `cmd+G`
    /// jumps to bottom, `cmd+yy` yanks a line. Counts go between the chord
    /// start and the completion key (`cmd+g 12 g` jumps to line 12). There is
    /// no `cmd+dd`: `cmd+d` is Add Selection to Next Match, and Delete Line
    /// moved to `cmd+shift+k`.
    /// Returns true when the key was consumed; false means the caller
    /// should continue with normal editor handling.
    fn handle_editor_vim_chord(&mut self, key: KeyEvent) -> bool {
        if is_vim_goto_bottom(key) {
            let count = self.editor_vim_chord.count;
            self.editor_vim_chord.reset();
            if count > 0 {
                self.editor.goto_line(count);
                self.status = format!("Line {count}");
            } else {
                self.editor.goto_bottom();
                self.status = String::from("Bottom of file");
            }
            return true;
        }

        let count_pending = self.editor_vim_chord.count > 0;
        let op_pending = self.editor_vim_chord.op != VimOp::None;

        if (op_pending || count_pending)
            && let Some(d) = chord_digit_value(key)
        {
            self.editor_vim_chord.count = self
                .editor_vim_chord
                .count
                .saturating_mul(10)
                .saturating_add(d);
            let op = match self.editor_vim_chord.op {
                VimOp::G => 'g',
                VimOp::Y => 'y',
                VimOp::None => ' ',
            };
            self.status = chord_status_text(op, self.editor_vim_chord.count);
            return true;
        }

        if !op_pending {
            if is_vim_chord_g(key) {
                self.editor_vim_chord.op = VimOp::G;
                self.status = chord_status_text('g', self.editor_vim_chord.count);
                return true;
            }
            if is_vim_chord_y(key) {
                self.editor_vim_chord.op = VimOp::Y;
                self.status = chord_status_text('y', self.editor_vim_chord.count);
                return true;
            }
            if !count_pending {
                if let Some(d) = cmd_only_digit_value(key) {
                    self.editor_vim_chord.count = d;
                    self.status = chord_status_text(' ', self.editor_vim_chord.count);
                    return true;
                }
                return false;
            }
            self.editor_vim_chord.reset();
            self.status = String::from("Chord cancelled");
            return false;
        }

        let completes = match self.editor_vim_chord.op {
            VimOp::G => is_plain_letter(key, 'g') || is_vim_chord_g(key),
            VimOp::Y => is_plain_letter(key, 'y') || is_vim_chord_y(key),
            VimOp::None => false,
        };

        if completes {
            let count = self.editor_vim_chord.count;
            match self.editor_vim_chord.op {
                VimOp::G => {
                    if count > 0 {
                        self.editor.goto_line(count);
                        self.status = format!("Line {count}");
                    } else {
                        self.editor.goto_top();
                        self.status = String::from("Top of file");
                    }
                }
                VimOp::Y => {
                    let n = count.max(1);
                    let yanked = self.editor.yank_lines(n);
                    if !yanked.is_empty() {
                        copy_to_clipboard(&yanked);
                    }
                    self.status = format!("Yanked {n} {}", if n == 1 { "line" } else { "lines" });
                }
                VimOp::None => {}
            }
            self.editor_vim_chord.reset();
            return true;
        }

        self.editor_vim_chord.reset();
        self.status = String::from("Chord cancelled");
        false
    }

    /// Apply one resolved vim intent to the editor. The vim state machine has
    /// already advanced its own mode; this only mutates the buffer/cursor.
    fn apply_vim_action(&mut self, action: crate::vim::VimAction) {
        use crate::vim::{Target, VimAction};
        match action {
            VimAction::Move(motion, count) => {
                self.vim_apply_motion(motion, count);
                self.vim_sync_visual_selection();
            }
            VimAction::Operate { op, target, count } => match target {
                Target::Lines => self.vim_operate_lines(op, self.editor.cursor_row, count),
                Target::Object(obj) => self.vim_operate_textobject(op, obj),
                Target::Motion(m) => self.vim_operate_motion(op, m, count),
            },
            VimAction::DeleteChar(count) => self.vim_delete_chars(count),
            VimAction::Insert(at) => self.vim_enter_insert(at),
            VimAction::Paste(at, count) => self.vim_paste(at, count),
            VimAction::Undo => {
                self.status = if self.editor.undo() {
                    String::from("Undo")
                } else {
                    String::from("Nothing to undo")
                };
            }
            VimAction::Redo => {
                self.status = if self.editor.redo() {
                    String::from("Redo")
                } else {
                    String::from("Nothing to redo")
                };
            }
            VimAction::EnterVisual { line } => {
                self.editor.break_undo_coalescing();
                self.vim_visual_line = line;
                self.vim
                    .set_visual_anchor(self.editor.cursor_row, self.editor.cursor_col);
                self.editor.start_selection_at_cursor();
                self.status = String::from(if line {
                    "-- VISUAL LINE --"
                } else {
                    "-- VISUAL --"
                });
            }
            VimAction::ExitVisual => {
                self.editor.clear_selection();
                self.vim_visual_line = false;
                self.status.clear();
            }
            VimAction::VisualOperate(op) => self.vim_visual_operate(op),
            VimAction::ExitInsert => {
                self.editor.break_undo_coalescing();
                if self.editor.cursor_col > 0 {
                    self.editor.cursor_col -= 1;
                }
                self.status.clear();
            }
            VimAction::RunEx(cmd) => self.vim_run_ex(&cmd),
            VimAction::Search(dir, term) => self.vim_search(dir, &term),
            VimAction::ClearPending => {
                self.editor.clear_selection();
                self.vim_visual_line = false;
            }
            // `q{a-z}` starts, a bare `q` stops. The vim machine reports the
            // gesture; the recording itself lives on App so a macro recorded
            // in vim mode replays from the palette and vice versa (#255).
            // Recording control is inert during replay. `macro_replaying`
            // gates capture, not dispatch, so without this a replayed `q`
            // would reach here and leave the user silently recording after
            // the replay returned — the class of command the issue's
            // exclusion list exists for.
            VimAction::MacroRecord(_) | VimAction::MacroReplay(..) if self.macro_replaying => {}
            VimAction::MacroRecord(register) => match register {
                // A register letter STARTS; a bare `q` stops. The app owns
                // the recording state, so vim never has to track it.
                Some(r) if self.macro_recording.is_none() => self.start_macro_recording(Some(r)),
                _ => self.stop_macro_recording(),
            },
            VimAction::MacroReplay(register, count) => match register {
                Some(r) => self.replay_macro_register(r, count),
                None => self.replay_last_macro(count),
            },
        }
    }

    fn vim_line_len(&self, row: usize) -> usize {
        self.editor
            .lines
            .get(row)
            .map(|l| l.chars().count())
            .unwrap_or(0)
    }

    fn vim_first_non_blank(&self, row: usize) -> usize {
        self.editor
            .lines
            .get(row)
            .map(|l| l.chars().take_while(|c| c.is_whitespace()).count())
            .unwrap_or(0)
    }

    fn vim_apply_motion(&mut self, motion: crate::vim::Motion, count: usize) {
        use crate::vim::Motion;
        let n = count.max(1);
        match motion {
            Motion::Left => {
                self.editor.cursor_col = self.editor.cursor_col.saturating_sub(n);
            }
            Motion::Right => {
                let len = self.vim_line_len(self.editor.cursor_row);
                self.editor.cursor_col = (self.editor.cursor_col + n).min(len);
            }
            Motion::Up => {
                for _ in 0..n {
                    self.editor.move_up();
                }
            }
            Motion::Down => {
                for _ in 0..n {
                    self.editor.move_down();
                }
            }
            Motion::WordForward => {
                for _ in 0..n {
                    self.vim_word_forward();
                }
            }
            Motion::WordBackward => {
                for _ in 0..n {
                    self.vim_word_backward();
                }
            }
            Motion::WordEnd => {
                for _ in 0..n {
                    self.vim_word_end();
                }
            }
            Motion::LineStart => self.editor.cursor_col = 0,
            Motion::FirstNonBlank => {
                self.editor.cursor_col = self.vim_first_non_blank(self.editor.cursor_row);
            }
            Motion::LineEnd => {
                self.editor.cursor_col = self.vim_line_len(self.editor.cursor_row);
            }
            Motion::FileStart => self.editor.goto_top(),
            Motion::FileEnd => self.editor.goto_bottom(),
            Motion::GotoLine(line) => self.editor.goto_line(line),
            Motion::Find(kind, ch) => {
                self.vim_last_find = Some((kind, ch));
                self.vim_find_char(kind, ch, n);
            }
            Motion::RepeatFind => {
                if let Some((kind, ch)) = self.vim_last_find {
                    self.vim_find_char(kind, ch, n);
                }
            }
            Motion::RepeatFindRev => {
                if let Some((kind, ch)) = self.vim_last_find {
                    self.vim_find_char(reverse_find(kind), ch, n);
                }
            }
        }
        self.editor.ensure_cursor_col_visible();
    }

    fn vim_find_char(&mut self, kind: crate::vim::FindKind, ch: char, count: usize) {
        use crate::vim::FindKind;
        let row = self.editor.cursor_row;
        let Some(line) = self.editor.lines.get(row) else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let mut col = self.editor.cursor_col;
        for _ in 0..count.max(1) {
            match kind {
                FindKind::CharForward => match (col + 1..chars.len()).find(|&i| chars[i] == ch) {
                    Some(idx) => col = idx,
                    None => return,
                },
                FindKind::TillForward => match (col + 1..chars.len()).find(|&i| chars[i] == ch) {
                    Some(idx) if idx > 0 => col = idx - 1,
                    _ => return,
                },
                FindKind::CharBackward => match (0..col).rev().find(|&i| chars[i] == ch) {
                    Some(idx) => col = idx,
                    None => return,
                },
                FindKind::TillBackward => match (0..col).rev().find(|&i| chars[i] == ch) {
                    Some(idx) => col = idx + 1,
                    None => return,
                },
            }
        }
        self.editor.cursor_col = col;
    }

    /// Character class for vim word motions: 0 = blank (or past line end),
    /// 1 = keyword (alphanumeric/underscore), 2 = punctuation. A `w`/`b`/`e`
    /// word is a maximal run of one non-blank class.
    fn vim_class_at(&self, row: usize, col: usize) -> u8 {
        match self.editor.lines.get(row).and_then(|l| l.chars().nth(col)) {
            None => 0,
            Some(c) if c.is_whitespace() => 0,
            Some(c) if c.is_alphanumeric() || c == '_' => 1,
            Some(_) => 2,
        }
    }

    fn vim_next_pos(&self, row: usize, col: usize) -> Option<(usize, usize)> {
        if col < self.vim_line_len(row) {
            Some((row, col + 1))
        } else if row + 1 < self.editor.lines.len() {
            Some((row + 1, 0))
        } else {
            None
        }
    }

    fn vim_prev_pos(&self, row: usize, col: usize) -> Option<(usize, usize)> {
        if col > 0 {
            Some((row, col - 1))
        } else if row > 0 {
            Some((row - 1, self.vim_line_len(row - 1)))
        } else {
            None
        }
    }

    fn vim_word_forward(&mut self) {
        let mut row = self.editor.cursor_row;
        let mut col = self.editor.cursor_col;
        let start = self.vim_class_at(row, col);
        if start != 0 {
            while self.vim_class_at(row, col) == start {
                match self.vim_next_pos(row, col) {
                    Some((r, c)) => {
                        row = r;
                        col = c;
                    }
                    None => {
                        self.editor.cursor_row = row;
                        self.editor.cursor_col = col;
                        return;
                    }
                }
            }
        }
        while self.vim_class_at(row, col) == 0 {
            match self.vim_next_pos(row, col) {
                Some((r, c)) => {
                    row = r;
                    col = c;
                }
                None => break,
            }
        }
        self.editor.cursor_row = row;
        self.editor.cursor_col = col;
    }

    fn vim_word_backward(&mut self) {
        let mut row = self.editor.cursor_row;
        let mut col = self.editor.cursor_col;
        let Some((r, c)) = self.vim_prev_pos(row, col) else {
            return;
        };
        row = r;
        col = c;
        while self.vim_class_at(row, col) == 0 {
            match self.vim_prev_pos(row, col) {
                Some((r, c)) => {
                    row = r;
                    col = c;
                }
                None => {
                    self.editor.cursor_row = row;
                    self.editor.cursor_col = col;
                    return;
                }
            }
        }
        let class = self.vim_class_at(row, col);
        while let Some((pr, pc)) = self.vim_prev_pos(row, col) {
            if self.vim_class_at(pr, pc) != class {
                break;
            }
            row = pr;
            col = pc;
        }
        self.editor.cursor_row = row;
        self.editor.cursor_col = col;
    }

    fn vim_word_end(&mut self) {
        let mut row = self.editor.cursor_row;
        let mut col = self.editor.cursor_col;
        let Some((r, c)) = self.vim_next_pos(row, col) else {
            return;
        };
        row = r;
        col = c;
        while self.vim_class_at(row, col) == 0 {
            match self.vim_next_pos(row, col) {
                Some((r, c)) => {
                    row = r;
                    col = c;
                }
                None => {
                    self.editor.cursor_row = row;
                    self.editor.cursor_col = col;
                    return;
                }
            }
        }
        let class = self.vim_class_at(row, col);
        while let Some((nr, nc)) = self.vim_next_pos(row, col) {
            if self.vim_class_at(nr, nc) != class {
                break;
            }
            row = nr;
            col = nc;
        }
        self.editor.cursor_row = row;
        self.editor.cursor_col = col;
    }

    fn vim_operate_lines(&mut self, op: crate::vim::Op, start_row: usize, count: usize) {
        use crate::vim::Op;
        self.editor.cursor_row = start_row.min(self.editor.lines.len().saturating_sub(1));
        let n = count.max(1);
        match op {
            Op::Delete => {
                let text = self.editor.delete_lines(n);
                copy_to_clipboard(&text);
                self.status = format!("Deleted {n} line(s)");
            }
            Op::Yank => {
                let text = self.editor.yank_lines(n);
                copy_to_clipboard(&text);
                self.status = format!("Yanked {n} line(s)");
            }
            Op::Change => {
                let text = self.editor.delete_lines(n);
                copy_to_clipboard(&text);
                self.editor.open_line_above();
                self.vim.enter_insert_mode();
                self.status = String::from("-- INSERT --");
            }
        }
    }

    fn vim_operate_motion(&mut self, op: crate::vim::Op, motion: crate::vim::Motion, count: usize) {
        if vim_motion_is_linewise(motion) {
            let (first, last) = self.vim_line_range_for_motion(motion, count);
            self.vim_operate_lines(op, first, last + 1 - first);
            return;
        }
        let start = (self.editor.cursor_row, self.editor.cursor_col);
        self.vim_apply_motion(motion, count);
        let end = (self.editor.cursor_row, self.editor.cursor_col);
        let (lo, hi) = if start <= end {
            (start, end)
        } else {
            (end, start)
        };
        // Forward-inclusive motions (f/t/e) cover the char they land on.
        let head = if start <= end && vim_motion_is_forward_inclusive(motion) {
            let len = self.vim_line_len(hi.0);
            (hi.0, (hi.1 + 1).min(len))
        } else {
            hi
        };
        self.editor.selection = Some(crate::widgets::editor::EditorSelection { anchor: lo, head });
        self.vim_apply_operator_to_selection(op, lo);
    }

    fn vim_operate_textobject(&mut self, op: crate::vim::Op, obj: crate::vim::TextObject) {
        use crate::vim::TextObject;
        let row = self.editor.cursor_row;
        let Some((start, mut end)) = self.editor.word_at(row, self.editor.cursor_col) else {
            return;
        };
        if obj == TextObject::AWord
            && let Some(line) = self.editor.lines.get(row)
        {
            let chars: Vec<char> = line.chars().collect();
            while end < chars.len() && chars[end].is_whitespace() {
                end += 1;
            }
        }
        self.editor.selection = Some(crate::widgets::editor::EditorSelection {
            anchor: (row, start),
            head: (row, end),
        });
        self.vim_apply_operator_to_selection(op, (row, start));
    }

    /// Delete / yank / change whatever the editor selection currently spans,
    /// leaving the cursor at `start` and entering Insert mode for a change.
    fn vim_apply_operator_to_selection(&mut self, op: crate::vim::Op, start: (usize, usize)) {
        use crate::vim::Op;
        let text = self.editor.selection_text();
        copy_to_clipboard(&text);
        match op {
            Op::Yank => {
                self.editor.clear_selection();
                self.editor.cursor_row = start.0;
                self.editor.cursor_col = start.1;
            }
            Op::Delete => {
                self.editor.delete_selection();
            }
            Op::Change => {
                self.editor.delete_selection();
                self.vim.enter_insert_mode();
                self.status = String::from("-- INSERT --");
            }
        }
    }

    fn vim_line_range_for_motion(
        &self,
        motion: crate::vim::Motion,
        count: usize,
    ) -> (usize, usize) {
        use crate::vim::Motion;
        let row = self.editor.cursor_row;
        let last = self.editor.lines.len().saturating_sub(1);
        let n = count.max(1);
        match motion {
            Motion::Down => (row, (row + n).min(last)),
            Motion::Up => (row.saturating_sub(n), row),
            Motion::FileStart => (0, row),
            Motion::FileEnd => (row, last),
            Motion::GotoLine(line) => {
                let target = line.saturating_sub(1).min(last);
                if target >= row {
                    (row, target)
                } else {
                    (target, row)
                }
            }
            _ => (row, row),
        }
    }

    fn vim_delete_chars(&mut self, count: usize) {
        let row = self.editor.cursor_row;
        let Some(line) = self.editor.lines.get(row) else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let col = self.editor.cursor_col;
        let end = (col + count.max(1)).min(chars.len());
        if col < end {
            let deleted: String = chars[col..end].iter().collect();
            copy_to_clipboard(&deleted);
            for _ in col..end {
                self.editor.delete_forward();
            }
        }
    }

    fn vim_enter_insert(&mut self, at: crate::vim::InsertAt) {
        use crate::vim::InsertAt;
        let row = self.editor.cursor_row;
        match at {
            InsertAt::Cursor => {}
            InsertAt::After => {
                let len = self.vim_line_len(row);
                if self.editor.cursor_col < len {
                    self.editor.cursor_col += 1;
                }
            }
            InsertAt::LineStart => self.editor.cursor_col = self.vim_first_non_blank(row),
            InsertAt::LineEnd => self.editor.cursor_col = self.vim_line_len(row),
            InsertAt::Below => self.editor.open_line_below(),
            InsertAt::Above => self.editor.open_line_above(),
        }
        self.editor.break_undo_coalescing();
        self.status = String::from("-- INSERT --");
    }

    fn vim_paste(&mut self, at: crate::vim::PasteAt, count: usize) {
        use crate::vim::PasteAt;
        let Some(text) = (self.clipboard_reader)() else {
            return;
        };
        if text.is_empty() {
            return;
        }
        let n = count.max(1);
        if let Some(body) = text.strip_suffix('\n') {
            // Linewise paste: the yank ended on a newline, so it lands on
            // fresh lines rather than inside the current one.
            let block = std::iter::repeat_n(body, n).collect::<Vec<_>>().join("\n");
            match at {
                PasteAt::After => {
                    self.editor.cursor_col = self.vim_line_len(self.editor.cursor_row);
                    self.editor.insert_str(&format!("\n{block}"));
                }
                PasteAt::Before => {
                    self.editor.cursor_col = 0;
                    self.editor.insert_str(&format!("{block}\n"));
                }
            }
        } else {
            let block = text.repeat(n);
            if at == PasteAt::After {
                let len = self.vim_line_len(self.editor.cursor_row);
                if self.editor.cursor_col < len {
                    self.editor.cursor_col += 1;
                }
            }
            self.editor.insert_str(&block);
        }
        self.status = String::from("Pasted");
    }

    fn vim_visual_operate(&mut self, op: crate::vim::Op) {
        use crate::vim::Op;
        let Some(sel) = self.editor.selection else {
            return;
        };
        if self.vim_visual_line {
            let ((sr, _), (er, _)) = sel.normalised();
            self.vim_operate_lines(op, sr, er + 1 - sr);
            self.vim_visual_line = false;
            return;
        }
        // Charwise visual is inclusive of the cell under the cursor, so extend
        // the high end one char before operating.
        let ((sr, sc), (er, ec)) = sel.normalised();
        let len = self.vim_line_len(er);
        self.editor.selection = Some(crate::widgets::editor::EditorSelection {
            anchor: (sr, sc),
            head: (er, (ec + 1).min(len)),
        });
        self.vim_apply_operator_to_selection(op, (sr, sc));
        self.vim_visual_line = false;
        if !matches!(op, Op::Change) {
            self.status.clear();
        }
    }

    fn vim_run_ex(&mut self, cmd: &str) {
        let cmd = cmd.trim();
        if let Ok(line) = cmd.parse::<usize>() {
            self.editor.goto_line(line);
            return;
        }
        match cmd {
            "w" | "write" => self.save(),
            "q" | "q!" | "quit" => {
                self.record_closed_tab_at(self.editor.active_index());
                if self.editor.close_active() {
                    self.sync_open_file_poll_mtime();
                    self.status = String::from("Closed tab");
                } else {
                    self.quit = true;
                }
            }
            "wq" | "x" | "wq!" => {
                self.save();
                self.record_closed_tab_at(self.editor.active_index());
                if !self.editor.close_active() {
                    self.quit = true;
                }
            }
            "qa" | "qa!" | "quitall" => self.quit = true,
            other => self.status = format!("Unknown command: {other}"),
        }
    }

    fn vim_search(&mut self, dir: crate::vim::SearchDir, term: &str) {
        self.editor.set_search_highlight(
            Some(term.to_string()),
            crate::widgets::search::SearchOpts::default(),
        );
        match self.vim_find_match(dir, term) {
            Some((row, col)) => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.editor.ensure_cursor_col_visible();
                // Record the hit the cursor jumped to so the renderer paints it
                // in the distinct active colour (orange) while the remaining
                // matches keep the regular yellow. Literal search, so the match
                // is exactly `term` long in characters.
                self.editor.active_search_match = Some((row, col, term.chars().count()));
                self.status = match dir {
                    crate::vim::SearchDir::Forward => format!("/{term}"),
                    crate::vim::SearchDir::Backward => format!("?{term}"),
                };
            }
            None => {
                self.editor.active_search_match = None;
                self.status = format!("Pattern not found: {term}");
            }
        }
    }

    fn vim_find_match(&self, dir: crate::vim::SearchDir, term: &str) -> Option<(usize, usize)> {
        use crate::vim::SearchDir;
        let lines = &self.editor.lines;
        if term.is_empty() || lines.is_empty() {
            return None;
        }
        let (cr, cc) = (self.editor.cursor_row, self.editor.cursor_col);
        let total = lines.len();
        match dir {
            SearchDir::Forward => {
                for off in 0..=total {
                    let row = (cr + off) % total;
                    let from = if off == 0 { cc + 1 } else { 0 };
                    if let Some(col) = find_char_index(&lines[row], term, from) {
                        return Some((row, col));
                    }
                }
                None
            }
            SearchDir::Backward => {
                for off in 0..=total {
                    let row = (cr + total - off) % total;
                    let limit = if off == 0 { cc } else { usize::MAX };
                    if let Some(col) = rfind_char_index(&lines[row], term, limit) {
                        return Some((row, col));
                    }
                }
                None
            }
        }
    }

    fn vim_sync_visual_selection(&mut self) {
        if !matches!(
            self.vim.mode(),
            crate::vim::VimMode::Visual | crate::vim::VimMode::VisualLine
        ) {
            return;
        }
        if let Some(anchor) = self.vim.visual_anchor() {
            self.editor.selection = Some(crate::widgets::editor::EditorSelection {
                anchor,
                head: (self.editor.cursor_row, self.editor.cursor_col),
            });
        }
    }

    /// Keyboard handling for the PROBLEMS view while it owns the panel pane:
    /// arrow / page keys scroll the list, Escape hands focus back to the editor.
    /// Keys while the PROBLEMS tab owns the panel pane. Plain typing goes
    /// to the free-text filter (VS Code's Problems filter box), so Esc
    /// clears the filter first and only hands the pane back once it is
    /// already empty, mirroring the Remote panel's filter behaviour.
    fn handle_problems_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Up => self.problems.scroll_up(1),
            KeyCode::Down => self.problems.scroll_down(1),
            KeyCode::PageUp => self.problems.scroll_up(10),
            KeyCode::PageDown => self.problems.scroll_down(10),
            KeyCode::Backspace if !self.problems.text_filter.is_empty() => {
                self.problems.pop_filter_char();
            }
            KeyCode::Char(c)
                if !key.modifiers.intersects(
                    KeyModifiers::CONTROL | KeyModifiers::SUPER | KeyModifiers::ALT,
                ) =>
            {
                self.problems.push_filter_char(c);
            }
            KeyCode::Esc if !self.problems.clear_text_filter() => {
                self.focus_pane(Pane::Editor);
            }
            _ => {}
        }
    }

    fn handle_output_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Up => self.output.scroll_up(1),
            KeyCode::Down => self.output.scroll_down(1),
            KeyCode::PageUp => self.output.scroll_up(10),
            KeyCode::PageDown => self.output.scroll_down(10),
            KeyCode::Esc => self.focus_pane(Pane::Editor),
            _ => {}
        }
    }

    /// Keys while the PORTS tab owns the panel pane. `⏎` opens (forwarding first
    /// on a remote port), `f` forwards without opening, `c` copies the address,
    /// `x` stops watching (and tears the tunnel down).
    fn handle_ports_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Up => self.ports.move_selection(-1),
            KeyCode::Down => self.ports.move_selection(1),
            KeyCode::Esc => self.focus_pane(Pane::Editor),
            KeyCode::Enter => self.ports_open_selected(),
            KeyCode::Char('f') => self.ports_forward_selected(),
            KeyCode::Char('c') => self.ports_copy_selected(),
            KeyCode::Char('x') => self.ports_stop_selected(),
            _ => {}
        }
    }

    fn handle_captures_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Up => self.captures.move_selection(-1),
            KeyCode::Down => self.captures.move_selection(1),
            KeyCode::Esc => self.focus_pane(Pane::Editor),
            KeyCode::Enter => self.captures_open_selected(),
            KeyCode::Char('n') => self.ask_navigator_about_capture(),
            KeyCode::Char('x') => self.captures.remove_selected(),
            KeyCode::Char('c') => {
                self.captures.clear();
                self.status = String::from("Cleared captured output");
            }
            _ => {}
        }
    }

    /// Cmd+K D: snapshot the active pane's scrollback + screen. A pane that
    /// showed colour is written, colours as SGR, to a private file under the
    /// scrollback dir and opened as a pinned rendered-log tab (#257); a pane
    /// with no colour goes into the scratch editor tab it always had. Read
    /// from one grid pass (`grid_lines_ansi`, the plain twin of which is the
    /// text the find bar searches); the blank live-screen tail is trimmed so
    /// the buffer ends at the last real row.
    fn open_scrollback_in_editor(&mut self) {
        // Plain and coloured rows come from ONE grid read, so a redact rule
        // is applied to the row it matches and never to a neighbour that
        // shifted in while a second read was taken.
        let rows_both = self.terminal().grid_lines_ansi();
        let last = rows_both
            .iter()
            .rposition(|(plain, _)| !plain.trim().is_empty())
            .map_or(0, |i| i + 1);
        let pane = self.terminal().label();
        let pane = if pane.is_empty() { "terminal" } else { pane };
        let label = format!("{pane} scrollback");
        // Every redact rule applies here, copy-mode or not: this buffer
        // leaves the pane as bytes (#360). Masking works on the plain text;
        // a row the rules touch keeps its masked plain form and gives up its
        // colour, since a mask spliced between escapes could break them.
        let mut plain_rows: Vec<String> = Vec::with_capacity(last);
        let mut rows: Vec<String> = Vec::with_capacity(last);
        let mut fallback_reason: Option<String> = None;
        for (plain, ansi) in &rows_both[..last] {
            let masked = crate::triggers::mask_text(plain, &self.triggers, false);
            rows.push(if masked == *plain {
                ansi.clone()
            } else {
                masked.clone()
            });
            plain_rows.push(masked);
        }
        // A pane that showed colour lands in the rendered log view (#257),
        // which indexes from disk, so the rows go to a real file under the
        // scrollback dir, one per pane, overwritten on each dump. The gate
        // uses the open path's own sniff, so the file can never open as an
        // editable buffer of raw escapes. A pane with no colour keeps the
        // scratch buffer it always had.
        if scrollback_opens_as_log(&rows) {
            // Keyed on the pane's stable uid as well as its label: two
            // unnamed shells both read `terminal`, and two labels can
            // sanitise to one name, and neither may overwrite the other's
            // dump or close its tab.
            // The uid is a per-process counter that restarts at 1, so two
            // croft processes would share a name without the pid, as the
            // session handoff file learned before this one.
            let file = self.scrollback_dir.join(format!(
                "{}-{}-{}-scrollback.log",
                pane.chars()
                    .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' {
                        c
                    } else {
                        '_'
                    })
                    .collect::<String>(),
                std::process::id(),
                self.terminal().uid()
            ));
            // A tab from an earlier dump holds a byte index over the OLD
            // file; it is closed so the open below rebuilds the view over the
            // new bytes rather than reading them through the stale index.
            self.close_tabs_with_path_everywhere(&file);
            // Terminal output is written owner-only whatever the umask: the
            // redaction rules are finite, and another local account has no
            // business reading a shell's history.
            let written = write_private(&self.scrollback_dir, &file, &(rows.join("\n") + "\n"));
            // Dumps left by croft processes that have exited are reaped on
            // the way past: nothing will ever overwrite them. Here rather
            // than at startup because this is the one place the dir grows,
            // so its size is bounded at the moment it would grow; the cost
            // is one `read_dir` and one `kill(0)` per stale file, paid by a
            // command that just wrote a scrollback to disk.
            if written.is_ok() {
                reap_dead_scrollback_dumps(&self.scrollback_dir);
            }
            // Pinned, as the scratch buffer was: a later file peek must not
            // replace the dump, and two panes' dumps must not share a slot.
            let opened = written
                .map_err(anyhow::Error::from)
                .and_then(|()| self.editor.open_pinned(&file));
            match opened {
                Ok(()) if self.editor.log.is_some() => {
                    self.focus_pane(Pane::Editor);
                    self.sync_open_file_poll_mtime();
                    self.status = format!("Opened {last} scrollback lines as a rendered log");
                    return;
                }
                Ok(()) => {
                    // The open path decided this was not a log after all:
                    // never leave the user an editable file of raw escapes,
                    // nor the file itself, which nothing will read now.
                    self.close_tabs_with_path_everywhere(&file);
                    let _ = std::fs::remove_file(&file);
                    fallback_reason = Some(String::from(
                        "Rendered scrollback unavailable; opened as text",
                    ));
                }
                Err(e) => {
                    // Fall through to the plain scratch buffer rather than
                    // lose the dump: a full disk still leaves the text. A
                    // partial file, if one was written, serves nobody.
                    let _ = std::fs::remove_file(&file);
                    fallback_reason = Some(format!(
                        "Rendered scrollback unavailable ({e}); opened as text"
                    ));
                }
            }
        }
        let text = plain_rows.join("\n");
        match self.editor.open_text_buffer(Path::new(&label), &text) {
            Ok(()) => {
                self.focus_pane(Pane::Editor);
                self.sync_open_file_poll_mtime();
                // The reason travels in a local, not in `status`: a message
                // left by an earlier action must not be mistaken for one
                // this dump produced.
                self.status = fallback_reason
                    .unwrap_or_else(|| format!("Opened {last} scrollback lines in the editor"));
            }
            Err(e) => self.status = format!("Open scrollback failed: {e}"),
        }
    }

    /// Close every tab holding `path`, in the focused group and in every
    /// other one: a tab in an unfocused group would otherwise keep reading a
    /// rewritten file through its old index, and nothing heals it. Every
    /// match goes, not the first: `push_editor` can open one path twice. A
    /// group emptied by this is pruned as every other close path prunes it;
    /// the focused group is left blank for the caller to refill.
    fn close_tabs_with_path_everywhere(&mut self, path: &Path) {
        // `close_tab` on a group's last tab leaves a blank editor with no
        // path, so the search finds nothing more and the loop ends.
        while let Some(idx) = self.editor.find_tab_with_path(path) {
            self.editor.close_tab(idx);
        }
        // The prune names the groups THIS close emptied, by position: a
        // group the user left blank on purpose (a split with one side
        // cleared) is not this command's to fold away, and a blankness
        // sweep would take it along with the emptied one.
        let pre_blank: Vec<bool> = self
            .editor_layout
            .inactive_groups()
            .iter()
            .map(|g| g.is_blank_initial())
            .collect();
        let mut doomed = Vec::new();
        for (i, group) in self
            .editor_layout
            .inactive_groups_mut()
            .into_iter()
            .enumerate()
        {
            let mut closed_here = false;
            while let Some(idx) = group.find_tab_with_path(path) {
                group.close_tab(idx);
                closed_here = true;
            }
            if closed_here && group.is_blank_initial() && !pre_blank[i] {
                doomed.push(i);
            }
        }
        if !doomed.is_empty() {
            self.editor_layout.prune_inactive_at(&doomed);
        }
    }

    /// `.http`/`.rest` (#370): send the request under the caret. The env
    /// file's values are substituted before the send; a hole with no value
    /// refuses to send rather than leaking `{{name}}` to a server. The send
    /// runs on a worker thread and [`Self::drain_http_responses`] opens the
    /// response tab when it lands.
    pub(crate) fn send_http_request_under_caret(&mut self) {
        let Some((req, resolved, path)) = self.http_request_under_caret() else {
            return;
        };
        if self.http_run.is_some() {
            self.status = String::from("An HTTP request is already in flight");
            return;
        }
        // History records the RAW line: what the user wrote, secrets still
        // folded inside their {{names}}.
        let raw_line = format!("{} {}", req.method, req.url);
        let (tx, rx) = std::sync::mpsc::channel();
        let file = path.clone();
        let line = raw_line.clone();
        let spawned = std::thread::Builder::new()
            .name(String::from("croft-http"))
            .spawn(move || {
                let result = crate::http_file::send(&resolved, crate::http_file::REQUEST_TIMEOUT);
                let _ = tx.send(HttpRunOutcome {
                    file,
                    raw_line: line,
                    result,
                });
            });
        if spawned.is_err() {
            self.status = String::from("HTTP: could not start the request worker");
            return;
        }
        self.http_run = Some(rx);
        self.status = format!("Sending {raw_line}");
    }

    /// `.http` (#370): put the request under the caret on the clipboard as
    /// a curl command, variables substituted — the clipboard is the user's
    /// own hand, unlike history and the response tab.
    pub(crate) fn copy_http_request_as_curl(&mut self) {
        let Some((_, resolved, _)) = self.http_request_under_caret() else {
            return;
        };
        copy_to_clipboard(&crate::http_file::to_curl(&resolved));
        self.status = String::from("curl command copied");
    }

    /// The parsed and variable-resolved request under the caret, or a
    /// status naming why there is none (wrong file, no block, or a
    /// `{{name}}` with no value in `.http.env.json` / the environment).
    fn http_request_under_caret(
        &mut self,
    ) -> Option<(
        crate::http_file::HttpRequest,
        crate::http_file::ResolvedRequest,
        PathBuf,
    )> {
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("No file open");
            return None;
        };
        if !crate::http_file::is_http_file(&path) {
            self.status = String::from("Not a .http/.rest file");
            return None;
        }
        let text = self.editor.lines.join("\n");
        let requests = crate::http_file::parse_requests(&text);
        let Some(req) = crate::http_file::request_at(&requests, self.editor.cursor_row).cloned()
        else {
            self.status = String::from("No request under the caret");
            return None;
        };
        let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
        let vars = crate::http_file::load_env(&dir);
        let (resolved, missing) = crate::http_file::resolve(&req, &vars);
        if !missing.is_empty() {
            let holes: Vec<String> = missing.iter().map(|m| format!("{{{{{m}}}}}")).collect();
            self.status = format!(
                "HTTP: no value for {} (add it to {} beside the file, or $env)",
                holes.join(", "),
                crate::http_file::ENV_FILE
            );
            return None;
        }
        Some((req, resolved, path))
    }

    /// Fold in a finished `.http` request (#370): record it in the durable
    /// command history (raw line, status as the exit, elapsed as the
    /// duration), materialise the response under the cache, and open it —
    /// a text document with status/headers as comments, or the image
    /// itself. Returns whether a repaint is due.
    pub fn drain_http_responses(&mut self) -> bool {
        let Some(rx) = self.http_run.as_ref() else {
            return false;
        };
        let outcome = match rx.try_recv() {
            Ok(o) => o,
            Err(std::sync::mpsc::TryRecvError::Empty) => return false,
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.http_run = None;
                self.status = String::from("HTTP: the request worker died");
                return true;
            }
        };
        self.http_run = None;
        let cwd = outcome
            .file
            .parent()
            .map(|d| d.to_string_lossy().into_owned())
            .unwrap_or_default();
        let ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        match outcome.result {
            Err(e) => {
                self.command_history
                    .append(crate::command_history::HistoryEntry {
                        cmd: format!("http {}", outcome.raw_line),
                        cwd,
                        host: String::new(),
                        exit: None,
                        dur_ms: 0,
                        ts,
                    });
                self.status = format!("HTTP: {} failed: {e}", outcome.raw_line);
            }
            Ok(resp) => {
                self.command_history
                    .append(crate::command_history::HistoryEntry {
                        cmd: format!("http {}", outcome.raw_line),
                        cwd,
                        host: String::new(),
                        exit: Some(i32::from(resp.status)),
                        dur_ms: resp.elapsed_ms,
                        ts,
                    });
                let dir = croft_cache_dir().join("http");
                if let Err(e) = std::fs::create_dir_all(&dir) {
                    self.status = format!("HTTP: cannot write the response: {e}");
                    return true;
                }
                let slug: String = outcome
                    .raw_line
                    .chars()
                    .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
                    .collect::<String>()
                    .trim_matches('-')
                    .chars()
                    .take(48)
                    .collect();
                let stamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_millis())
                    .unwrap_or(0);
                let (file, bytes): (PathBuf, Vec<u8>) =
                    match crate::http_file::response_kind(&resp.content_type()) {
                        crate::http_file::ResponseKind::Image(ext) => {
                            (dir.join(format!("{slug}-{stamp}.{ext}")), resp.body.clone())
                        }
                        crate::http_file::ResponseKind::Text(_) => {
                            let (ext, doc) =
                                crate::http_file::response_doc(&outcome.raw_line, &resp);
                            (dir.join(format!("{slug}-{stamp}.{ext}")), doc.into_bytes())
                        }
                    };
                if let Err(e) = std::fs::write(&file, &bytes) {
                    self.status = format!("HTTP: cannot write the response: {e}");
                    return true;
                }
                match self.editor.open_pinned(&file) {
                    Ok(()) => {
                        self.focus_pane(Pane::Editor);
                        self.status = format!(
                            "{} \u{2192} {} {} \u{00b7} {} ms",
                            outcome.raw_line, resp.status, resp.status_text, resp.elapsed_ms
                        );
                    }
                    Err(e) => self.status = format!("HTTP: response open failed: {e}"),
                }
            }
        }
        true
    }

    /// Ctrl+Shift+H: open the durable command-history search over the
    /// active pane's context (atuin's enhanced Ctrl+R, embedded).
    fn open_command_history(&mut self) {
        let mut pop = crate::widgets::history_popup::HistoryPopup::new();
        pop.cwd = self
            .terminal()
            .shell_cwd()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        pop.host = self.terminal().shell_host().unwrap_or_default();
        pop.set_results(
            self.command_history
                .search("", pop.scope, &pop.cwd, &pop.host),
        );
        self.command_history_popup = Some(pop);
    }

    /// Re-run the store search after any query / scope change.
    fn refresh_command_history_results(&mut self) {
        let Some(pop) = self.command_history_popup.as_ref() else {
            return;
        };
        let (query, scope, cwd, host) = (
            pop.query.clone(),
            pop.scope,
            pop.cwd.clone(),
            pop.host.clone(),
        );
        let results = self.command_history.search(&query, scope, &cwd, &host);
        if let Some(pop) = self.command_history_popup.as_mut() {
            pop.set_results(results);
        }
    }

    fn handle_command_history_key(&mut self, key: KeyEvent) {
        // Ctrl+R (and the opening chord itself) cycles the scope filter:
        // all → this directory → failed only.
        if matches!(key.code, KeyCode::Char('r' | 'R'))
            && key.modifiers.contains(KeyModifiers::CONTROL)
        {
            if let Some(pop) = self.command_history_popup.as_mut() {
                pop.scope = pop.scope.next();
            }
            self.refresh_command_history_results();
            return;
        }
        match key.code {
            KeyCode::Esc => {
                self.command_history_popup = None;
            }
            KeyCode::Enter => {
                let cmd = self
                    .command_history_popup
                    .as_ref()
                    .and_then(|p| p.selected_entry())
                    .map(|e| e.cmd.clone());
                self.command_history_popup = None;
                if let Some(cmd) = cmd {
                    self.focus_pane(Pane::Terminal);
                    self.terminal_mut().paste_input(cmd.as_bytes());
                    self.status = String::from("Command typed at the prompt (Enter runs it)");
                }
            }
            KeyCode::Up => {
                if let Some(pop) = self.command_history_popup.as_mut() {
                    pop.select_prev();
                }
            }
            KeyCode::Down => {
                if let Some(pop) = self.command_history_popup.as_mut() {
                    pop.select_next();
                }
            }
            KeyCode::Left => {
                if let Some(pop) = self.command_history_popup.as_mut() {
                    pop.move_cursor_left();
                }
            }
            KeyCode::Right => {
                if let Some(pop) = self.command_history_popup.as_mut() {
                    pop.move_cursor_right();
                }
            }
            KeyCode::Backspace => {
                if let Some(pop) = self.command_history_popup.as_mut() {
                    pop.pop_char();
                }
                self.refresh_command_history_results();
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                if let Some(pop) = self.command_history_popup.as_mut() {
                    pop.push_char(c);
                }
                self.refresh_command_history_results();
            }
            _ => {}
        }
    }

    /// Jump the selected capture's pane back to the captured line: switch to
    /// the TERMINAL tab, focus the pane (found by shell pid; a closed pane
    /// falls back to the active one), locate the newest grid row matching
    /// the captured text, scroll it into view and select it. A very long
    /// captured line wraps across grid rows, so the match is prefix-based
    /// on the first wrapped row.
    pub fn captures_open_selected(&mut self) {
        let Some(entry) = self.captures.selected_entry().cloned() else {
            return;
        };
        let idx = entry
            .shell_pid
            .and_then(|pid| {
                self.terminals
                    .iter()
                    .position(|t| t.shell_pid() == Some(pid))
            })
            .unwrap_or(self.active_terminal);
        self.reveal_terminal_pane(idx);
        self.set_bottom_panel_tab(BottomPanelTab::Terminal);
        self.focus_pane(Pane::Terminal);
        let needle: String = entry.line.trim_end().chars().take(60).collect();
        let Some(line) = self.terminals[idx].find_captured_line(&needle) else {
            self.status = String::from("Captured line is no longer in the scrollback");
            return;
        };
        let (_, _, cols, _) = self.terminals[idx].grid_bounds();
        let t = &mut self.terminals[idx];
        t.set_selection(Some(crate::widgets::terminal::Selection {
            anchor: (line, 0),
            head: (line, cols.saturating_sub(1)),
            block: false,
        }));
        t.scroll_to_line(line);
        self.status = format!("Capture: {}", entry.message);
    }

    fn handle_terminal_key(&mut self, key: KeyEvent) {
        // Quick-select owns every keystroke while its labels are up.
        if self.terminal_quick_select.is_some() {
            self.handle_terminal_quick_select_key(key);
            return;
        }
        // Copy mode owns every keystroke while it is on.
        if self.terminal_copy_mode.is_some() {
            self.handle_terminal_copy_mode_key(key);
            return;
        }
        // The find bar owns every keystroke while it is open.
        if self.terminal_find.is_some() {
            self.handle_terminal_find_key(key);
            return;
        }
        // Ctrl+Shift+Space (WezTerm's quick-select): label every URL / path /
        // hash / IP on screen; typing a label copies it, UPPERCASE pastes.
        if is_quick_select_key(key) {
            self.open_terminal_quick_select();
            return;
        }
        // Ctrl+Shift+Y (WezTerm's copy mode, Y for yank): keyboard-select
        // from the grid and scrollback with vi motions.
        if is_copy_mode_key(key) {
            self.open_terminal_copy_mode();
            return;
        }
        // Ctrl+Shift+H (H for history; atuin's enhanced Ctrl+R lives on the
        // shell side): search the durable cross-session command history.
        // Plain Ctrl+R still reaches the shell's own reverse search.
        if is_command_history_key(key) {
            self.open_command_history();
            return;
        }
        // Open find-in-terminal (scrollback search). Cmd+F everywhere;
        // Ctrl+F only off macOS, matching VS Code's terminal find defaults:
        // on macOS Ctrl+F is a control byte the child owns (vim page-forward,
        // emacs forward-char) and iTerm2/VS Code pass it through, while on
        // Linux/Windows Ctrl+F opening find IS the VS Code default.
        if is_terminal_find_key(key) {
            self.open_terminal_find();
            return;
        }
        // Ctrl+Shift+T: open another terminal next to the active one.
        if is_terminal_split_key(key) {
            match self.split_terminal() {
                Ok(()) => {
                    self.terminal_status(format!(
                        "Split terminal: {} active",
                        self.terminals.len()
                    ));
                }
                Err(e) => {
                    self.status = format!("Split terminal failed: {e}");
                }
            }
            return;
        }
        // Cmd+W (or legacy Ctrl+Shift+W): close the active terminal (no-op when
        // only one is left).
        if is_terminal_close_key(key) {
            if self.close_active_terminal() {
                self.terminal_status(format!(
                    "Closed terminal: {} remaining",
                    self.terminals.len()
                ));
            } else {
                self.status = String::from("Cannot close the last terminal; press Ctrl+J to hide");
            }
            return;
        }
        // Cmd+]: next terminal. Cmd+[: previous terminal.
        if is_terminal_cycle_key(key) {
            self.cycle_terminal();
            return;
        }
        if is_terminal_cycle_back_key(key) {
            self.cycle_terminal_back();
            return;
        }
        // Cmd+Opt+Up / Cmd+Opt+Down (Linux: Ctrl+Alt): jump to the previous /
        // next prompt via the OSC 133 marks shell integration records —
        // VS Code's command navigation. (VS Code's own Cmd+Up/Down chord is
        // impossible here: bare Cmd+arrows are reserved by the user, see
        // src/iterm2.rs. The chord is already forwarded globally for the
        // editor's Add Cursor Above/Below and is unused in the terminal.)
        if key
            .modifiers
            .intersects(KeyModifiers::SUPER | KeyModifiers::CONTROL)
            && key.modifiers.contains(KeyModifiers::ALT)
            && matches!(key.code, KeyCode::Up | KeyCode::Down)
        {
            self.terminal_prompt_jump(matches!(key.code, KeyCode::Down));
            return;
        }
        // Shift+PageUp / Shift+PageDown: page through the scrollback;
        // Shift+Home / Shift+End jump to the oldest line / the live bottom
        // (xterm's keyboard-scrollback convention, leaving the plain keys
        // for the running program). In the alternate screen there is no
        // scrollback, so the chord falls through to the program instead.
        if key.modifiers.contains(KeyModifiers::SHIFT)
            && matches!(
                key.code,
                KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End
            )
        {
            let page = self.terminal().last_inner.height.max(2) as usize - 1;
            let scrolled = match key.code {
                KeyCode::PageUp => self.terminal_mut().scroll_up(page),
                KeyCode::PageDown => self.terminal_mut().scroll_down(page),
                KeyCode::Home => self.terminal_mut().scroll_to_top(),
                _ => self.terminal_mut().reset_scrollback(),
            };
            if scrolled {
                return;
            }
        }
        // Ctrl+Shift+C / Cmd+C: copy current selection.
        if is_terminal_copy_key(key) {
            self.copy_terminal_selection();
            return;
        }
        // Cmd+V / Ctrl+V / Ctrl+Shift+V: paste local clipboard into the
        // embedded shell. Without this, raw Ctrl+V bytes (\x16) just go
        // through to the shell unchanged, and Cmd+V — when not eaten by
        // the host terminal's menu shortcut — would do nothing useful.
        if is_clipboard_paste_key(key) {
            self.paste_clipboard_into_terminal();
            return;
        }
        // Any other keystroke clears the selection so the user's input is
        // sent without the previous highlight lingering on screen.
        if self.terminal().selection().is_some() {
            self.terminal_mut().clear_selection();
        }
        self.write_terminal_key(key);
    }

    /// Shell-bound keystroke from the focused terminal: normally just the
    /// active pane, mirrored to every non-excluded pane while broadcast is
    /// on. Encoded per pane because DECCKM is per-PTY state: every pane gets
    /// the form its own child asked for (a zsh pane wants SS3 arrows while a
    /// bash pane wants CSI), not the focused pane's.
    fn write_terminal_key(&mut self, key: KeyEvent) {
        if self.broadcast_input {
            let active = self.active_terminal;
            for (i, t) in self.terminals.iter_mut().enumerate() {
                if i == active || !t.broadcast_excluded {
                    let bytes = key_to_bytes(key, t.app_cursor_keys());
                    if !bytes.is_empty() {
                        t.write_input(&bytes);
                    }
                }
            }
        } else {
            let bytes = key_to_bytes(key, self.terminal().app_cursor_keys());
            if !bytes.is_empty() {
                self.terminal_mut().write_input(&bytes);
            }
        }
    }

    /// Copy the terminal pane's current selection to the user's clipboard.
    /// Selection stays visible so the user can verify what was copied.
    ///
    /// A copy that finds NOTHING now says so (#538). Inside a program that has
    /// ASKED for mouse tracking — Claude Code and most full-screen TUIs, but
    /// not a program that never requested it — a plain drag is the child's
    /// gesture and croft deliberately holds no selection of its own (#474), so
    /// the old silent return left the user pressing copy with nothing
    /// happening and no way to learn that Shift+drag selects there. The hint
    /// is keyed on `mouse_reporting`, so a pane whose child is not tracking is
    /// told to drag, which is what works there.
    fn copy_terminal_selection(&mut self) {
        if !self.terminal().selection().is_some_and(|s| s.has_area()) {
            self.status = String::from(if self.terminal().mouse_reporting() {
                "Nothing selected: Shift+drag selects inside a program that tracks the mouse"
            } else {
                "Nothing selected: drag to select first"
            });
            return;
        }
        let text = self.terminal_text_for_copy(self.terminal().selection_text());
        if text.is_empty() {
            // A real selection, but over blank cells: saying "nothing
            // selected" here would describe the wrong thing to fix.
            self.status = String::from("Selection has no text to copy");
            return;
        }
        self.deliver_copied_text(&text);
    }

    /// Put copied text where the user can actually paste it.
    ///
    /// "The clipboard" is not always this machine's. On a relay session croft
    /// runs on a remote box while the user types at another machine, and it is
    /// THAT clipboard a paste comes from — so the text goes home over the drop
    /// relay, the same road `request_remote_clipboard` uses to fetch it for a
    /// paste, travelled in the other direction (#538). Writing the remote
    /// box's clipboard instead put the text somewhere nothing could reach, and
    /// an SSH session usually has no clipboard tool to write to at all.
    ///
    /// Everywhere else it is this machine's clipboard, with the OSC 52
    /// fallback `copy_to_clipboard` already keeps for a host terminal that
    /// honours it. That fallback is reported HONESTLY: whether the sequence is
    /// acted on is the host terminal's choice, not something croft can see, so
    /// claiming a copy landed would be a claim croft cannot make.
    fn deliver_copied_text(&mut self, text: &str) {
        let n = text.chars().count();
        if self.is_relay_session && self.push_clipboard_via_relay(text) {
            self.status = format!("Copied {n} chars to the local clipboard");
            return;
        }
        if copy_to_clipboard(text) {
            self.status = format!("Copied {n} chars to clipboard");
        } else {
            self.status = format!("Copied {n} chars via OSC 52 (the host terminal decides)");
        }
    }

    /// Push copied text to the LOCAL machine's clipboard over the drop relay.
    /// Returns whether the request was queued.
    ///
    /// The payload goes in a file in the relay INBOX rather than into the
    /// request line: a request is one TAB-SEPARATED LINE, while copied text
    /// carries newlines and tabs of its own and can be megabytes of
    /// scrollback. The line names only the request id — the pump derives
    /// `<inbox>/<id>.txt` from the inbox it already owns, so no path from
    /// this side is ever handed to a remote shell.
    ///
    /// An oversized copy is REFUSED here rather than truncated there. The pump
    /// caps what it will read into the local machine's memory and drops
    /// anything past it, and a selection that pastes back half-formed is worse
    /// than falling through to the ordinary clipboard route and saying so.
    fn push_clipboard_via_relay(&mut self, text: &str) -> bool {
        if text.len() > crate::remote::MAX_COPY_PAYLOAD_BYTES {
            return false;
        }
        let (Some(log_path), Some(inbox)) = (self.relay_log_path(), self.relay_inbox_path()) else {
            return false;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("copy");
        if std::fs::write(inbox.join(format!("{request_id}.txt")), text).is_err() {
            return false;
        }
        append_to_relay_log(&log_path, &format!("copy\t{request_id}\n")).is_ok()
    }

    /// Paste the host clipboard into the terminal: the chord (Cmd+V /
    /// Ctrl+V / Ctrl+Shift+V) and the pane menu's "Paste" both land here, so
    /// bracketed paste, broadcast fan-out and the remote-clipboard fallback
    /// behave identically whichever one the user reached for.
    ///
    /// The messages name the ACTION rather than the chord: the menu route has
    /// no Cmd+V in it, and a status line quoting a key the user never pressed
    /// reads as a bug report about the wrong thing.
    fn paste_clipboard_into_terminal(&mut self) {
        match crate::clipboard::read_string() {
            Some(text) if !text.is_empty() => {
                self.paste_terminal_input(text.as_bytes());
            }
            Some(_) => {
                self.status = String::from("Paste: clipboard is empty");
            }
            None if self.drop_relay_active() => {
                self.request_remote_clipboard();
            }
            None => {
                self.status =
                    String::from("Paste: clipboard read failed (no pbpaste / NSPasteboard)");
            }
        }
    }

    /// Start a mouse selection over a rendered ANSI log (#257).
    ///
    /// Mirrors `begin_preview_selection`: a log tab's `lines` is a one-line
    /// stub, so the editor's own selection coordinates cannot describe it and
    /// the view carries its own, in absolute (line, char column).
    fn begin_log_selection(&mut self, col: u16, row: u16) -> bool {
        let scroll = self.editor.scroll;
        let Some(log) = self.editor.log.as_mut() else {
            return false;
        };
        if !rect_contains(log.last_body, col, row) {
            if log.has_selection() {
                log.selection = None;
                log.dragging = false;
            }
            return false;
        }
        let cell = log_cell_at(log, scroll, col, row);
        log.selection = Some((cell, cell));
        log.dragging = true;
        self.focus_pane(Pane::Editor);
        true
    }

    /// Ctrl+click a `path:line` printed in a RENDERED log (#257).
    ///
    /// Scanned against the escape-free text, not the raw bytes: the
    /// reference's column in the file is not its column on screen once SGR
    /// sequences are stripped, and a path can sit inside an escape entirely.
    /// `log_cell_at` already maps a screen cell to that text's column.
    ///
    /// Dispatched ahead of `begin_log_selection`, which runs before the
    /// editor's own Ctrl handling and would otherwise swallow the gesture
    /// into a selection drag. Relative paths resolve against the workspace
    /// root - a log has no shell cwd to consult, unlike a terminal pane.
    fn log_file_click(&mut self, col: u16, row: u16) -> bool {
        let scroll = self.editor.scroll;
        let Some(log) = self.editor.log.as_ref() else {
            return false;
        };
        if !rect_contains(log.last_body, col, row) {
            return false;
        }
        let (line, column) = log_cell_at(log, scroll, col, row);
        let Some(text) = log.visible_text(line).map(str::to_string) else {
            return false;
        };
        let Some(fr) = crate::file_ref::file_ref_at(&text, column) else {
            return false;
        };
        let raw = std::path::PathBuf::from(&fr.path);
        let abs = if let Some(rest) = fr.path.strip_prefix("~/") {
            match std::env::var_os("HOME") {
                Some(h) => std::path::PathBuf::from(h).join(rest),
                None => return false,
            }
        } else if raw.is_absolute() {
            raw
        } else {
            self.tree.root.join(raw)
        };
        // Only when it resolves to a real file, which is also what filters
        // lookalikes like `host.com:443`.
        if !abs.is_file() {
            return false;
        }
        self.open_resolved_file_ref(&abs, fr.line, fr.column)
    }

    /// Extend a live log drag and finish it on release.
    fn update_log_selection(&mut self, m: MouseEvent) -> bool {
        let scroll = self.editor.scroll;
        let copy_on_select = self.copy_on_select;
        let Some(log) = self.editor.log.as_mut() else {
            return false;
        };
        if !log.dragging {
            return false;
        }
        match m.kind {
            MouseEventKind::Drag(MouseButton::Left) => {
                let body = log.last_body;
                // Clamp to the body: dragging past an edge extends to it
                // rather than dropping the gesture.
                let col = m
                    .column
                    .clamp(body.x, body.x + body.width.saturating_sub(1));
                let row = m.row.clamp(body.y, body.y + body.height.saturating_sub(1));
                let head = log_cell_at(log, scroll, col, row);
                if let Some((anchor, _)) = log.selection {
                    log.selection = Some((anchor, head));
                }
                true
            }
            MouseEventKind::Up(MouseButton::Left) => {
                log.dragging = false;
                if copy_on_select {
                    self.copy_log_selection();
                }
                true
            }
            _ => false,
        }
    }

    /// Put the log selection on the clipboard, saying so when the copy was
    /// clamped rather than leaving the user with silently less than they
    /// selected.
    fn copy_log_selection(&mut self) -> bool {
        let Some(log) = self.editor.log.as_ref() else {
            return false;
        };
        if !log.has_selection() {
            return false;
        }
        let (text, clamped) = log.selection_text();
        if text.is_empty() {
            return false;
        }
        let bytes = text.len();
        copy_to_clipboard(&text);
        // Say what was actually copied. `clamped` is true for the byte CAP
        // and for a sweep that ran out of budget on escape-heavy text, and in
        // the second case the copy can be far short of the cap: naming the
        // cap then tells the user they got four megabytes when they got a
        // fraction of one.
        self.status = if clamped {
            format!("Copied {bytes} bytes; the selection was larger than one copy allows")
        } else {
            format!("Copied {bytes} bytes")
        };
        true
    }

    /// Start a drag-selection in the rendered Markdown/document preview
    /// when `(col, row)` lands inside it. Returns true when the press was
    /// consumed, so the normal editor click path is skipped: the source
    /// buffer is not visible, and a caret there would serve nobody.
    fn begin_preview_selection(&mut self, col: u16, row: u16) -> bool {
        if let Some(idx) = self.preview_runnable_at(col, row) {
            self.run_markdown_block(idx);
            return true;
        }
        let Some(md) = self.editor.markdown_preview.as_mut() else {
            return false;
        };
        if !rect_contains(md.last_area, col, row) {
            // A press elsewhere drops the selection, like the editor's.
            if md.has_selection() {
                md.selection = None;
                md.dragging = false;
            }
            return false;
        }
        let cell = (row - md.last_area.y, col - md.last_area.x);
        md.selection = Some((cell, cell));
        md.dragging = true;
        self.focus_pane(Pane::Editor);
        true
    }

    /// The runnable fence whose play glyph sits under screen `(col, row)`
    /// (#353): the glyph cell itself, the first column of the block's first
    /// visual row - one column, so a drag-selection starting beside it is
    /// still a selection.
    fn preview_runnable_at(&self, col: u16, row: u16) -> Option<usize> {
        let md = self.editor.markdown_preview.as_ref()?;
        if !rect_contains(md.last_area, col, row) || col != md.last_area.x {
            return None;
        }
        let visual = (row - md.last_area.y) as usize + md.scroll as usize;
        md.run_rows.iter().position(|r| *r == visual)
    }

    /// The confirm popup for runnable fence `idx` of the current document.
    /// EVERY block confirms (#353): a README from a cloned repo is untrusted
    /// input, and a substring matcher cannot tell a benign block from a
    /// disguised one; the matcher only decides whether the popup is red.
    fn pending_run_block_for(
        &self,
        idx: usize,
        block: &crate::markdown::MdRunnable,
    ) -> PendingRunBlock {
        let doc = self.editor.path.clone();
        // The pane is named by the document's path under the workspace, so
        // two READMEs in one tree do not share `README.md:1`.
        let root = self.active_workspace_root();
        let file = doc
            .as_ref()
            .map(|p| {
                p.strip_prefix(&root)
                    .map(|rel| rel.display().to_string())
                    .unwrap_or_else(|_| {
                        p.file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_else(|| String::from("doc"))
                    })
            })
            .unwrap_or_else(|| String::from("doc"));
        let cwd = if block.cwd_root {
            self.active_workspace_root()
        } else {
            doc.as_ref()
                .and_then(|p| p.parent())
                .map(Path::to_path_buf)
                .unwrap_or_else(|| self.active_workspace_root())
        };
        PendingRunBlock {
            pane_name: format!("{file}:{}", idx + 1),
            cwd,
            command: fence_command(block.interpreter, &block.code),
            code: block.code.clone(),
            destructive: block.destructive,
            doc: doc.clone(),
            block_line: block.lines.0,
            persist: block.persist,
            capture_timeout: block.capture_timeout.map(std::time::Duration::from_secs),
        }
    }

    /// A click on runnable fence `idx` of the open preview: park it behind
    /// the confirm popup.
    fn run_markdown_block(&mut self, idx: usize) {
        let Some(md) = self.editor.markdown_preview.as_ref() else {
            return;
        };
        let Some(block) = md.runnables.get(idx).cloned() else {
            return;
        };
        self.pending_run_block = Some(self.pending_run_block_for(idx, &block));
    }

    /// Cmd+Enter in a Markdown SOURCE buffer (#353): the fence under the
    /// caret, found by the parser's own source ranges (the same walk the
    /// preview uses, so the block number - and its pane - agree).
    fn run_fence_at_cursor(&mut self) -> bool {
        let is_markdown = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension().and_then(|e| e.to_str()))
            .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "md" | "markdown"));
        if self.editor.markdown_preview.is_some() || !is_markdown {
            return false;
        }
        let text = self.editor.lines.join("\n");
        let (_, _, runnables) = crate::markdown::render_markdown_full(
            &text,
            self.theme,
            &mut crate::highlight::LangRegistry::new(),
            None,
            crate::markdown::BlockOutputs::new(),
        );
        let row = self.editor.cursor_row;
        let Some((idx, block)) = runnables
            .iter()
            .enumerate()
            .find(|(_, r)| row >= r.lines.0 && row < r.lines.1)
        else {
            self.status = String::from(
                "Cmd+Enter: put the caret inside a runnable shell fence (sh/bash/zsh/fish; not {run=false})",
            );
            return true;
        };
        self.pending_run_block = Some(self.pending_run_block_for(idx, block));
        true
    }

    /// Type a fence into its pane (#353): the pane named after the document
    /// and block, reused when it sits idle at a prompt in the block's
    /// directory, else a fresh one there. The block is typed, not spawned,
    /// so the user sees it and shell history records it.
    fn run_block_in_pane(&mut self, block: PendingRunBlock) {
        // Ctrl-E + Ctrl-U first, as tasks do: an idle shell's line editor
        // may hold a half-typed command.
        let bytes = format!("\x05\x15{}", block.command);
        // Same guard as `run_project_task`, and the SAME predicate rather
        // than a second copy: `README.md:1` is a likely name across two
        // repos opened in sequence, and a pane whose shell still sits in
        // the other repo must not receive this one's block (#430).
        let root = block
            .cwd
            .canonicalize()
            .unwrap_or_else(|_| block.cwd.clone());
        // `pane_is_idle_at` is main's shared predicate (#430): one
        // definition for tasks and for runnable blocks, so a correction to
        // the cwd rule cannot land on one and miss the other.
        if let Some(idx) = self
            .terminals
            .iter()
            .position(|t| pane_is_idle_at(t, &block.pane_name, &root))
        {
            self.arm_block_capture(&block, idx);
            self.reveal_terminal_pane(idx);
            self.terminals[idx].write_input(bytes.as_bytes());
            self.show_terminal = true;
            self.focus_pane(Pane::Terminal);
            self.status = format!("Running {}", block.pane_name);
            return;
        }
        match crate::widgets::terminal::PtyTerminal::new(&block.cwd) {
            Ok(mut term) => {
                term.set_manual_name(Some(block.pane_name.clone()));
                term.write_input(bytes.as_bytes());
                self.insert_terminal(term);
                // A fresh pane has no decorations yet, so the capture arms
                // at zero and the block's own command is the first to
                // finish. Armed AFTER the insert, since that is what puts
                // the pane in `self.terminals` for the settle to find.
                if let Some(idx) = self
                    .terminals
                    .iter()
                    .position(|t| t.label() == block.pane_name)
                {
                    self.arm_block_capture(&block, idx);
                }
                self.status = format!("Running {}", block.pane_name);
            }
            Err(e) => {
                self.status = format!("Could not start a pane for {}: {e}", block.pane_name);
            }
        }
    }

    fn confirm_pending_run_block(&mut self) {
        if let Some(block) = self.pending_run_block.take() {
            self.run_block_in_pane(block);
        }
    }

    fn cancel_pending_run_block(&mut self) {
        self.pending_run_block = None;
        self.status = String::from("Block not run");
    }

    /// Start waiting for `block`'s output on pane `idx` (#354).
    ///
    /// The pane's CURRENT decoration count is recorded, so the capture is
    /// the first command to finish after this moment rather than whatever
    /// the pane happened to run before. Re-running a block replaces its
    /// pending capture: the newest run is the one the preview describes.
    fn arm_block_capture(&mut self, block: &PendingRunBlock, idx: usize) {
        // The newest id the pane has already finished. Ids are monotonic,
        // so "greater than this" is exactly "after the block was typed",
        // and it stays true however many marks are collected in between.
        let after = self.terminals[idx]
            .command_decorations()
            .iter()
            .map(|d| d.id)
            .max();
        self.pending_captures
            .retain(|c| c.pane_name != block.pane_name || c.block_line != block.block_line);
        self.pending_captures.push(PendingCapture {
            pane_name: block.pane_name.clone(),
            doc: block.doc.clone(),
            block_line: block.block_line,
            after,
            started: std::time::Instant::now(),
            timeout: block.capture_timeout,
            persist: block.persist,
        });
    }

    /// Write a capture into the document as an output fence (#354).
    ///
    /// The fence goes immediately after the block's closer, marked with an
    /// HTML comment so a later run can find and REPLACE it rather than
    /// stacking a new one each time. Exactly one output fence per block, and
    /// no other fence is touched: the search starts at the block's closer
    /// and stops at the first line that is not part of the marked pair.
    ///
    /// This writes to the user's file from a preview action, so it is
    /// deliberately narrow. It refuses rather than guesses when the document
    /// on disk no longer looks like the one the block came from, since the
    /// block's line numbers are only meaningful against the text that
    /// produced them.
    fn persist_block_output(
        &mut self,
        path: &Path,
        block_line: usize,
        out: &crate::markdown::BlockOutput,
    ) {
        let Ok(text) = std::fs::read_to_string(path) else {
            self.status = format!("Could not read {} to persist the output", path.display());
            return;
        };
        let Some(updated) = crate::markdown::replace_output_fence(&text, block_line, &out.text)
        else {
            self.status =
                String::from("The document changed since the block ran; output not saved");
            return;
        };
        if std::fs::write(path, &updated).is_err() {
            self.status = format!("Could not write the captured output to {}", path.display());
        }
    }

    /// Settle any capture whose command has finished, or whose
    /// `{timeout=N}` has elapsed. Returns true when something changed, so
    /// the caller knows to repaint.
    ///
    /// Deliberately its own pass rather than a branch inside
    /// `drain_terminal_bells`: that function is about notifying, this one
    /// is about recording, and they answer to different pane states.
    fn settle_block_captures(&mut self) -> bool {
        if self.pending_captures.is_empty() {
            return false;
        }
        let mut settled: Vec<(
            String,
            usize,
            crate::markdown::BlockOutput,
            Option<PathBuf>,
            bool,
        )> = Vec::new();
        self.pending_captures.retain_mut(|c| {
            let Some(term) = self.terminals.iter().find(|t| t.label() == c.pane_name) else {
                // The pane is gone, so nothing will ever finish on it.
                return false;
            };
            let decorations = term.command_decorations();
            // The first command to finish AFTER the block was typed, by id
            // rather than by position (#440). Ids are monotonic and never
            // renumbered, so this survives any amount of mark collection:
            // an evicted command is simply absent rather than silently
            // replaced by its neighbour, which is what the old positional
            // index could not distinguish.
            // The EARLIEST command to finish after the block was typed.
            // Earliest rather than latest because a block that finishes
            // while a later one is still running must not be described by
            // the later one - but see `PendingCapture::after`: earliest is
            // also what makes a foreign command completing in the
            // arm-to-keystroke gap win, which is this rule's residual and
            // not `after`'s.
            let mine = decorations
                .iter()
                .filter(|d| c.after.is_none_or(|a| d.id > a))
                .min_by_key(|d| d.id);
            if let Some(d) = mine {
                settled.push((
                    c.pane_name.clone(),
                    c.block_line,
                    crate::markdown::BlockOutput {
                        text: term.command_output_text(d),
                        exit: d.exit,
                        timed_out: false,
                    },
                    c.doc.clone(),
                    // Unconditional now. The gate existed because a
                    // positional index could name a stranger; an id cannot.
                    c.persist,
                ));
                return false;
            }
            // The TIMEOUT stops the capture, never the process: the block
            // keeps running in its pane and the box says the wait gave up.
            if c.timeout.is_some_and(|t| c.started.elapsed() >= t) {
                settled.push((
                    c.pane_name.clone(),
                    c.block_line,
                    crate::markdown::BlockOutput {
                        text: String::new(),
                        exit: None,
                        timed_out: true,
                    },
                    c.doc.clone(),
                    c.persist,
                ));
                return false;
            }
            true
        });
        if settled.is_empty() {
            return false;
        }
        for (pane, line, out, doc, persist) in settled {
            if persist
                && !out.timed_out
                && let Some(path) = doc.as_ref()
            {
                self.persist_block_output(path, line, &out);
            }
            self.block_outputs.insert((pane, line), out);
        }
        self.publish_block_outputs();
        true
    }

    /// Hand the editor the captures for the document it is showing (#354).
    ///
    /// The editor has no view of which pane ran what, so the app narrows
    /// `block_outputs` to the current document's pane prefix and copies the
    /// result in. Called after a capture settles and when the preview is
    /// rebuilt, so a box appears without the user touching anything.
    fn publish_block_outputs(&mut self) {
        // The common case by far: nothing has been run, so there is nothing
        // to narrow and nothing to compare. Checked before the map is built
        // rather than after, since this runs every tick.
        if self.block_outputs.is_empty() && self.editor.md_outputs.is_empty() {
            return;
        }
        let prefix = self.block_pane_prefix();
        let narrowed: crate::markdown::BlockOutputs = self
            .block_outputs
            .iter()
            .filter(|((pane, _), _)| pane.starts_with(&prefix))
            .map(|((_, line), out)| (*line, out.clone()))
            .collect();
        // Idempotent, so the tick can call it unconditionally and a
        // DOCUMENT SWITCH is picked up without every switch path having to
        // remember to. Keying only by source line meant `B.md`'s line-12
        // fence rendered `A.md`'s capture until something else rebuilt the
        // preview; narrowing by pane prefix fixes that only if it actually
        // re-runs, which is what this comparison buys.
        if narrowed == self.editor.md_outputs {
            return;
        }
        self.editor.md_outputs = narrowed;
        if self.editor.markdown_preview.is_some() {
            self.editor.rebuild_markdown_preview();
        }
    }

    /// The pane-name prefix for the document the editor is showing: the
    /// same `<file>:` the run path builds its pane names from, so a capture
    /// from another document cannot appear under this one's fences.
    fn block_pane_prefix(&self) -> String {
        let root = self.active_workspace_root();
        let file = self
            .editor
            .path
            .as_ref()
            .map(|p| {
                p.strip_prefix(&root)
                    .map(|rel| rel.display().to_string())
                    .unwrap_or_else(|_| {
                        p.file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_else(|| String::from("doc"))
                    })
            })
            .unwrap_or_else(|| String::from("doc"));
        format!("{file}:")
    }

    /// Extend a live preview drag and finish it on release. Returns true
    /// when the event was consumed.
    fn update_preview_selection(&mut self, m: MouseEvent) -> bool {
        let Some(md) = self.editor.markdown_preview.as_mut() else {
            return false;
        };
        if !md.dragging {
            return false;
        }
        match m.kind {
            MouseEventKind::Drag(MouseButton::Left) => {
                // Clamp to the view: dragging past an edge extends to it
                // rather than dropping the gesture.
                let area = md.last_area;
                let row = m.row.clamp(area.y, area.y + area.height.saturating_sub(1)) - area.y;
                let col = m
                    .column
                    .clamp(area.x, area.x + area.width.saturating_sub(1))
                    - area.x;
                if let Some((anchor, _)) = md.selection {
                    md.selection = Some((anchor, (row, col)));
                }
                true
            }
            MouseEventKind::Up(MouseButton::Left) => {
                md.dragging = false;
                // Mirror the editor's copy-on-select setting so a finished
                // drag lands on the clipboard when the user asked for that.
                if self.copy_on_select {
                    let text = self
                        .editor
                        .markdown_preview
                        .as_ref()
                        .map(|md| md.selection_text())
                        .unwrap_or_default();
                    if !text.is_empty() {
                        copy_to_clipboard(&text);
                    }
                }
                true
            }
            _ => false,
        }
    }

    fn copy_editor_selection(&mut self) {
        // The rendered preview hides the source buffer, so its selection
        // is the only one the user can see (#215).
        if let Some(md) = self.editor.markdown_preview.as_ref() {
            let text = md.selection_text();
            if !text.is_empty() {
                copy_to_clipboard(&text);
                self.status = format!("Copied {} chars to clipboard", text.chars().count());
            }
            return;
        }
        // A rendered log likewise hides its own text behind a stub buffer,
        // and the return is unconditional: falling through when there is no
        // selection would run the editor's copy over that stub and put its
        // placeholder content on the clipboard, which is worse than copying
        // nothing.
        if self.editor.log.is_some() {
            self.copy_log_selection();
            return;
        }
        if let Some(diff) = self.editor.diff.as_ref() {
            if let Some(text) = diff.selection_text()
                && !text.is_empty()
            {
                copy_to_clipboard(&text);
                self.status = format!("Copied {} chars to clipboard", text.chars().count());
            }
            return;
        }
        let Some(sel) = self.editor.selection else {
            return;
        };
        if !sel.has_area() {
            return;
        }
        let text = self.editor.selection_text();
        if text.is_empty() {
            return;
        }
        copy_to_clipboard(&text);
        self.status = format!("Copied {} chars to clipboard", text.chars().count());
    }

    fn cut_editor_selection(&mut self) {
        let Some(sel) = self.editor.selection else {
            return;
        };
        if !sel.has_area() {
            return;
        }
        let text = self.editor.selection_text();
        if text.is_empty() {
            self.editor.clear_selection();
            return;
        }
        copy_to_clipboard(&text);
        let n = text.chars().count();
        self.editor.delete_selection();
        self.status = format!("Cut {n} chars to clipboard");
    }

    fn paste_clipboard_into_search(&mut self, text: Option<&str>) {
        let Some(s) = text else {
            self.status = String::from("Cmd+V: clipboard read failed");
            return;
        };
        if s.is_empty() {
            self.status = String::from("Cmd+V: clipboard is empty");
            return;
        }
        self.search.insert_str(s);
        // Replace text doesn't change which files match, so only re-run the
        // scan when the paste landed in a search-affecting field.
        if self.search.field != crate::widgets::search::SearchField::Replace {
            self.submit_search_query();
        }
        self.status = format!(
            "Cmd+V: pasted into {} field",
            search_field_name(self.search.field)
        );
    }

    fn paste_clipboard_into_editor(&mut self, text: Option<&str>) {
        let Some(s) = text else {
            self.status = String::from("Cmd+V: clipboard read failed");
            return;
        };
        if s.is_empty() {
            self.status = String::from("Cmd+V: clipboard is empty");
            return;
        }
        self.editor.insert_str(s);
        self.status = format!("Pasted {} chars", s.chars().count());
    }

    fn handle_paste(&mut self, s: &str) {
        // Modal overlays own paste entirely while open — paste lands in
        // the modal's input field, never in the editor / tree / terminal
        // behind it. Without this, hitting Cmd+V right after Cmd+P pastes
        // into whatever pane was last focused instead of into the finder
        // query, which makes the "open + paste a filename" path that the
        // VS Code Quick Open is meant to support unusable.
        if let Some(prompt) = self.input_prompt.as_mut() {
            for c in s.chars() {
                if !c.is_control() {
                    prompt.push_char(c);
                }
            }
            return;
        }
        if let Some(palette) = self.command_palette.as_mut() {
            for c in s.chars() {
                if !c.is_control() {
                    palette.push_char(c);
                }
            }
            return;
        }
        if let Some(picker) = self.go_to_symbol.as_mut() {
            for c in s.chars() {
                if !c.is_control() {
                    picker.push_char(c);
                }
            }
            return;
        }
        if let Some(picker) = self.workspace_symbols.as_mut() {
            for c in s.chars() {
                if !c.is_control() {
                    picker.push_char(c);
                }
            }
            self.workspace_symbols_requery();
            return;
        }
        if let Some(finder) = self.file_finder.as_mut() {
            for c in s.chars() {
                if !c.is_control() {
                    finder.push_char(c);
                }
            }
            return;
        }
        // The in-file find bar is a pane-scoped widget, not a modal: it only
        // owns the paste while the editor itself is focused. Without the focus
        // guard, an open find bar would swallow a paste meant for the terminal
        // (or tree) the user has since clicked into — the keystroke path is
        // already focus-gated via `match self.focus`, so paste must match it.
        if self.focus == Pane::Editor && self.editor_find.is_some() {
            let mut new_q = self
                .editor_find
                .as_ref()
                .map(|st| st.query.clone())
                .unwrap_or_default();
            for c in s.chars() {
                if !c.is_control() {
                    new_q.push(c);
                }
            }
            self.editor_find_set_query(new_q);
            return;
        }
        // Finder drag-and-drop into croft arrives via the host terminal as
        // a bracketed paste containing absolute filesystem path(s). The
        // drop in iTerm2 does NOT shift mouse focus, so we cannot require
        // `self.focus == Pane::Tree` for the gesture: the user can have
        // last clicked into the editor or the embedded terminal and still
        // expect the drop on the sidebar to import.
        //
        //   * Remote view: any path-shaped paste is an scp upload. There
        //     is no other reasonable thing the user could want, since the
        //     visible UI is a host list.
        //   * Explorer view: a path-shaped paste is an import only when
        //     focus is on the tree, otherwise we keep the current
        //     behaviour (typing a path string into the focused editor or
        //     terminal command line) because that is a legitimate use.
        // iTerm2's inline-image drag artefact ALWAYS short-circuits the
        // paste pipeline: a stray click-and-microdrag on an OSC-1337 cell
        // (activity-bar icon, welcome wordmark, no-repo / run-debug / SSH
        // hero) makes iTerm2 write the decoded PNG to $TMPDIR/iTerm2.<rand>.png
        // and re-inject the path as a bracketed paste. parse_dropped_paths
        // already filters those paths out of the import list, but without
        // an early-return here the fallthrough would still paste the raw
        // path string into the editor body (the user reported this as
        // "Pasted 67 chars" appearing in a freshly-opened CLAUDE.local.md
        // tab while they were trying to resize the sidebar near the
        // Explorer icon). Detect the artefact at the payload level and
        // silently drop the entire paste — no text, no import, no status.
        if parsed_drop_tokens(s)
            .iter()
            .any(|p| p.is_absolute() && is_iterm2_inline_image_drop(p))
        {
            return;
        }
        let dropped = parse_dropped_paths(s);
        if !dropped.is_empty() {
            match self.sidebar_view {
                SidebarView::Remote if self.focus == Pane::Tree => {
                    self.import_paths_into_remote(&dropped);
                    return;
                }
                SidebarView::Explorer if self.focus == Pane::Tree => {
                    self.import_paths_into_explorer(&dropped);
                    return;
                }
                _ => {}
            }
        }
        // Remote-launched croft case: the path the user dragged from
        // their local Finder doesn't exist on this remote box, so the
        // strict parser above returned nothing. If the drop-relay env
        // is plumbed (set by the local-croft parent over the SSH
        // session) and the paste shape is path-like, request a reverse
        // pull through the relay.
        //
        // Two triggers gate the relay pull. Tree focus is the explicit one,
        // matching the strict branch above. The second, `is_pure_path_payload`,
        // recovers a genuine Finder drag: a drop arrives as a bracketed paste
        // and does NOT move keyboard focus to the tree, so a focus-only gate
        // silently dropped every drag where the user had last clicked the
        // terminal or editor. A real drop is nothing but absolute-path tokens,
        // whereas the text pastes the focus guard protects — a shell command or
        // code snippet that merely contains a `/...` token — always carry a
        // non-path token, so they still fall through to a normal paste rather
        // than being hijacked into a relay pull with no local file to fetch
        // (the regression seen on remote sessions opened from Termux).
        if self.drop_relay_active()
            && self.sidebar_view == SidebarView::Explorer
            && (self.focus == Pane::Tree || is_pure_path_payload(s))
        {
            let foreign = parse_foreign_dropped_paths(s);
            if !foreign.is_empty() {
                self.request_remote_pulls(&foreign);
                return;
            }
        }
        if self.sidebar_view == SidebarView::Search && self.focus == Pane::Tree {
            self.search.insert_str_into_query(s);
            self.submit_search_query();
            self.status = format!("Pasted {} chars", s.chars().count());
            return;
        }
        // Source Control commit message box: bracketed paste must
        // populate it the same way Cmd+V via the key path does
        // (`handle_source_control_key` -> `source_control.insert_str`).
        // Without this branch, in the production setup where iTerm2
        // emits Cmd+V as a bracketed paste rather than a key event,
        // the payload silently vanishes when the user has the SC
        // sidebar focused.
        if self.sidebar_view == SidebarView::SourceControl
            && self.focus != Pane::Editor
            && self.focus != Pane::Terminal
        {
            self.source_control.insert_str(s);
            self.status = format!("Pasted {} chars", s.chars().count());
            return;
        }
        match self.focus {
            Pane::Editor => {
                self.editor.insert_str(s);
                self.status = format!("Pasted {} chars", s.chars().count());
            }
            Pane::Terminal => {
                if self.terminal_find.is_some() {
                    let mut q = self
                        .terminal_find
                        .as_ref()
                        .map(|st| st.query.clone())
                        .unwrap_or_default();
                    for c in s.chars() {
                        if !c.is_control() {
                            q.push(c);
                        }
                    }
                    self.terminal_find_set_query(q);
                } else {
                    self.paste_terminal_input(s.as_bytes());
                }
            }
            Pane::Tree => {}
        }
    }

    /// Move every dropped path into the directory the explorer is
    /// currently pointing at. Files outside the workspace are *moved* in
    /// (matching the user's Finder-drop expectation), not copied — they
    /// disappear from the source location and re-appear in the explorer.
    fn import_paths_into_explorer(&mut self, paths: &[PathBuf]) {
        let dest_dir = self.paste_target_dir();
        let total = paths.len();
        let mut placed: Vec<PathBuf> = Vec::new();
        let mut errors: Vec<String> = Vec::new();
        let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
        affected.insert(dest_dir.clone());
        for src in paths {
            if let Some(parent) = src.parent() {
                affected.insert(parent.to_path_buf());
            }
            match crate::widgets::file_tree::move_into(&dest_dir, src) {
                Ok(p) => placed.push(p),
                Err(e) => errors.push(format!("{}: {e}", src.display())),
            }
        }
        for dir in &affected {
            if let Some(idx) = self.tree.index_of_dir(dir) {
                self.tree.refresh_children(idx);
            }
        }
        self.tree.marked.clear();
        for p in &placed {
            self.tree.marked.insert(p.clone());
        }
        if let Some(first) = placed.first()
            && let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
        {
            self.tree.selected = idx;
            self.tree.anchor = idx;
        }
        self.status = if !errors.is_empty() {
            format!(
                "Imported {}/{}; failed: {}",
                placed.len(),
                total,
                errors.join("; ")
            )
        } else if total == 1 {
            format!(
                "Imported {} into {}",
                paths[0].display(),
                dest_dir.display()
            )
        } else {
            format!(
                "Imported {total} items into {}",
                self.status_path(&dest_dir)
            )
        };
    }

    /// Queue every dropped path for an interactive SCP upload to the
    /// currently selected SSH target. The actual scp invocation happens
    /// in `main_loop` after suspending the alt-screen, so scp inherits
    /// the host shell's stdin / stdout / stderr — that means password
    /// prompts, FIDO touch requests, and host-key confirmations all work
    /// the way the user expects, and the user sees scp's progress and
    /// errors directly. After all uploads finish (success or failure),
    /// croft prompts for Enter and resumes the TUI.
    fn import_paths_into_remote(&mut self, paths: &[PathBuf]) {
        let Some(target) = self.remote.selected_target().cloned() else {
            self.status = String::from("Drop ignored: no Remote Explorer host selected");
            return;
        };
        if paths.is_empty() {
            return;
        }
        for src in paths {
            self.pending_scp_uploads.push(ScpUpload {
                alias: target.alias.clone(),
                src: src.clone(),
            });
        }
        self.status = format!(
            "Queued {} item(s) for scp copy to {} (you'll see scp's prompts next)",
            paths.len(),
            target.alias,
        );
    }

    pub fn take_pending_scp_uploads(&mut self) -> Vec<ScpUpload> {
        std::mem::take(&mut self.pending_scp_uploads)
    }

    /// Service edge auto-scroll while a terminal drag-selection is held
    /// past the top/bottom edge. Called every main-loop wakeup; advances
    /// the viewport by one row at ~30 ms intervals (a readable ~33 rows/s)
    /// and re-pins the selection head to the new edge. Returns true when a
    /// scroll happened so the caller knows it owes a redraw.
    pub fn tick_terminal_autoscroll(&mut self) -> bool {
        let Some(state) = self.terminal_select_autoscroll else {
            return false;
        };
        if state.last.elapsed() < std::time::Duration::from_millis(30) {
            return false;
        }
        // A forwarded click-only drag (#474) may be on a pane other than the
        // active one: Cmd+] moves the active pane mid-drag, and no further
        // Drag event arrives while the pointer rests past the edge to
        // re-check. This tick scrolls the ACTIVE pane, so it stands down
        // rather than walk the wrong pane's scrollback -- HELD, not dropped:
        // the parked pointer sends nothing to re-arm, so cycling back to the
        // origin pane must resume the scroll on its own (and the untouched
        // `last` stamp makes that first tick fire at once).
        if let Some(fp) = self.terminal_pointer_forwarded {
            let Some(idx) = self.forwarded_pane_index(fp) else {
                // The origin pane is gone (closed by its button while the
                // pointer was parked): nothing can ever resume this, so
                // drop the gesture rather than hold it to the release.
                self.terminal_pointer_forwarded = None;
                self.terminal_select_autoscroll = None;
                return false;
            };
            if idx != self.active_terminal {
                return false;
            }
        }
        self.terminal_mut().autoscroll_select(state.dir, state.col);
        self.terminal_select_autoscroll = Some(TerminalSelectAutoScroll {
            last: std::time::Instant::now(),
            ..state
        });
        true
    }

    /// True when this croft is a remote-launched session whose local parent is
    /// running a drop pump. Gated on `CROFT_RELAY_KEY`, set only by a `croft
    /// remote` launch command. The key is the deterministic `hash(launch arg)`
    /// shared with the local pump; because it's deterministic, dtach freezing it
    /// at first launch is harmless — every reconnect recomputes the same value,
    /// so the running croft and a fresh pump always agree on one relay dir. A
    /// session predating this var (an old long-lived dtach session) simply has
    /// no key and reports the relay unavailable rather than timing out.
    fn drop_relay_active(&self) -> bool {
        self.relay_dir().is_some()
    }

    /// `$HOME/.cache/croft/relay-<CROFT_RELAY_KEY>/` on this remote box. The key
    /// is `hash(launch arg)` — the same id the dtach socket uses — computed by
    /// the local launcher and the local pump and carried here in env. Keying on
    /// the launch identity (not `workspace_root`) keeps the rendezvous stable
    /// across an in-session workspace change and the F9 self-re-exec, both of
    /// which move `workspace_root` away from where the pump's `pwd` lands.
    /// `None` when no `CROFT_RELAY_KEY` is set (not a relay-capable session).
    fn relay_dir(&self) -> Option<PathBuf> {
        let id = std::env::var("CROFT_RELAY_KEY")
            .ok()
            .filter(|s| !s.is_empty())?;
        Some(croft_cache_dir().join(format!("relay-{id}")))
    }

    fn relay_log_path(&self) -> Option<PathBuf> {
        self.relay_dir().map(|d| d.join("requests.log"))
    }

    fn relay_inbox_path(&self) -> Option<PathBuf> {
        self.relay_dir().map(|d| d.join("inbox"))
    }

    /// Ensure the relay dir + inbox exist before writing a request. On the first
    /// drop after a dtach reattach (or on a fresh box) the local pump's
    /// `tail -F` may have started against a path this croft hadn't created yet;
    /// `tail -F` retries, so a lazy mkdir here is enough. Idempotent and cheap.
    fn ensure_relay_dir(&self) {
        if let Some(inbox) = self.relay_inbox_path() {
            let _ = std::fs::create_dir_all(inbox);
        }
    }

    fn request_remote_pulls(&mut self, paths: &[PathBuf]) {
        let dest_dir = self.paste_target_dir();
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Drop relay not available on this remote session");
            return;
        };
        self.ensure_relay_dir();
        let mut lines = String::new();
        let mut staged: Vec<PendingRemotePull> = Vec::new();
        let now = std::time::Instant::now();
        for src in paths {
            let request_id = Self::relay_request_id("pull");
            let basename = src
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| String::from("dropped"));
            lines.push_str("pull\t");
            lines.push_str(&request_id);
            lines.push('\t');
            lines.push_str(&src.to_string_lossy());
            lines.push('\n');
            staged.push(PendingRemotePull {
                request_id,
                src_display: src.to_string_lossy().into_owned(),
                basename,
                dest_dir: dest_dir.clone(),
                started_at: now,
                kind: RemotePullKind::File,
            });
        }
        match append_to_relay_log(&log_path, &lines) {
            Ok(()) => {
                self.status = format!(
                    "Fetching {} item(s) from your local Mac via croft relay",
                    staged.len(),
                );
                self.pending_remote_pulls.extend(staged);
            }
            Err(e) => {
                self.status = format!("Drop relay write failed: {e}");
            }
        }
    }

    /// Ask the local-croft drop pump to fetch the user's macOS clipboard
    /// and stage it on this remote box. The drained pull resolves to a
    /// `paste_input` call on the embedded terminal — see `drain_remote_pulls`.
    fn request_remote_clipboard(&mut self) {
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Cmd+V: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("clip");
        let mut line = String::from("clipboard\t");
        line.push_str(&request_id);
        line.push('\n');
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: String::from("clipboard"),
                    basename: String::from("clipboard.txt"),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Clipboard,
                });
                self.status = String::from("Cmd+V: fetching local Mac clipboard via croft relay");
            }
            Err(e) => {
                self.status = format!("Cmd+V: relay write failed: {e}");
            }
        }
    }

    /// Bind this croft's `croft view` socket and publish it to panes.
    ///
    /// Keyed by pid so two crofts on one box never contend, and published
    /// through [`crate::view_ipc::SOCK_PATH`], which `apply_pane_env` reads
    /// at spawn time so no spawn site has to remember it. Not the process
    /// env: `set_var` is unsound with threads running, and the body below
    /// says so at length. Under `cfg(test)` the bind is skipped, since a test
    /// that stood up an App would otherwise leave a live socket in the real
    /// cache dir and set the one-shot global for every OTHER test in the same
    /// process.
    fn bind_view_socket() -> Option<std::os::unix::net::UnixListener> {
        if cfg!(test) {
            return None;
        }
        let dir = croft_cache_dir();
        // Latched, not swallowed. "A full or read-only `$HOME`" is one of the
        // causes VIEW_BIND_ERROR's own doc names, and it fails HERE, one line
        // above the `map_err` that would have reported it. Returning `None`
        // quietly left `status` on "Ready" and told the user to run from a
        // pane inside croft, which is what they were already doing.
        if let Err(e) = std::fs::create_dir_all(&dir) {
            *VIEW_BIND_ERROR.lock().unwrap() = Some(format!("{e}"));
            return None;
        }
        // ABSOLUTE, always. `croft_cache_dir` falls back to `.` when `HOME`
        // is unset, and the client resolves what it is handed against the
        // PANE's cwd - so a relative socket path published here reports "the
        // croft that opened this pane is gone" from any pane that has `cd`'d,
        // while the croft is running. The module's own invariant is that the
        // server only ever sees absolute paths; this is where that starts.
        let path = crate::view_ipc::socket_path(&dir, std::process::id());
        let path = std::path::absolute(&path).unwrap_or(path);
        sweep_dead_view_sockets(&dir);
        // A bind failure is reported, not swallowed. The reachable causes are
        // real - `AddrInUse` from the liveness check, a full or read-only
        // `$HOME`, or the 104-byte `AF_UNIX` path budget with a long home
        // directory on macOS - and the client's message for an unset socket
        // tells the user to run from a pane inside croft, which is exactly
        // what they were doing. Saying so once at startup is the difference
        // between a feature that is off and a feature that lies about why.
        let listener = prepare_view_listener(&path)
            .map_err(|e| {
                // Latched rather than dropped. The reachable causes are real -
                // `AddrInUse` from the liveness check, a full or read-only
                // `$HOME`, the 104-byte `AF_UNIX` path budget with a long home
                // on macOS - and the client's message for an unset socket
                // tells the user to run from a pane inside croft, which is
                // what they were already doing. `App::new` puts this on the
                // status line, so a feature that is off says why once instead
                // of misdirecting every time it is used.
                *VIEW_BIND_ERROR.lock().unwrap() = Some(format!("{e}"));
            })
            .ok()?;
        // Published through a `OnceLock` read at SPAWN time rather than
        // `std::env::set_var` (#362). Two things were wrong with the env:
        //
        // portable-pty snapshots `std::env::vars_os()` inside
        // `CommandBuilder::new` and then clears the child's environment before
        // applying only that snapshot, so a variable set after a pane was
        // constructed never reached its shell. This call happens while
        // `App::new` runs, which is AFTER the first pane exists, so `croft
        // view` was broken in the startup pane and working everywhere else.
        //
        // And `set_var` is unsafe in edition 2024 because a concurrent
        // `getenv` in another thread is a data race. By this point croft has
        // the highlight prewarm, the DAP reaper, a PTY reader, the git worker,
        // the MCP index refresh and the FS watcher all running, which is
        // exactly the condition `src/gui_path.rs` and `src/session.rs` both
        // document when they place their own `set_var` calls at startup.
        let _ = crate::view_ipc::SOCK_PATH.set(path);
        Some(listener)
    }

    /// Accept whatever `croft view` clients have queued and open their files.
    ///
    /// Returns whether anything changed, so the frame loop redraws. Every
    /// connection is answered before the next is accepted, which is right
    /// here: a request is one path and the work is opening a tab, so a
    /// thread per client would buy nothing and cost the editor's `&mut self`.
    pub fn drain_view_requests(&mut self) -> bool {
        // The drain is bounded by TIME rather than by a connection count.
        // A per-frame cap of N clients still bounds the frame at N times the
        // per-read timeout; a deadline bounds it at the deadline however many
        // clients stall. Whatever is left is accepted on the next frame,
        // which costs a stalled client latency and costs the user nothing.
        //
        // The per-stream timeout below is taken from what REMAINS of this
        // deadline, which is the half that actually bounds a stalled client.
        // `SO_RCVTIMEO` applies per `recv`, and `read_line` loops until it
        // sees a newline, so a flat 50ms is reset on every byte that arrives:
        // a client dribbling one byte every 40ms and never a newline holds
        // the frame loop for as long as it likes. Bounding the BYTES does not
        // fix that either - 50 bytes trickled over a second is under any cap
        // and still costs the second. Only a deadline the client cannot push
        // forward does.
        // A croft whose bind failed has no listener and never gets one, so it
        // must not pay two clock reads and a loop entry every frame forever.
        // The per-iteration binding below stays: it cannot be hoisted, since
        // holding that borrow across `answer_view_client`'s `&mut self` does
        // not compile.
        if self.view_listener.is_none() {
            return false;
        }
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(20);
        let mut changed = false;
        loop {
            // Do not accept what we cannot serve. `read_line_by_deadline`
            // checks its budget BEFORE the first read, so a well-behaved
            // client accepted at deadline-minus-epsilon is refused without a
            // single read attempt, and the client does not retry. Deferring it
            // to the next frame costs that client one frame and costs the user
            // nothing, which is the same trade the deadline itself makes.
            if deadline.saturating_duration_since(std::time::Instant::now())
                < std::time::Duration::from_millis(3)
            {
                return changed;
            }
            let Some(listener) = self.view_listener.as_ref() else {
                return changed;
            };
            match listener.accept() {
                Ok((stream, _)) => {
                    // The reply is returned so a TEST can assert on it; the
                    // drain only needs to know whether a file was opened.
                    let (_, opened) = self.answer_view_client(stream, deadline);
                    changed |= opened;
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return changed,
                Err(_) => return changed,
            }
        }
    }

    /// Open one requested path, answering with what the user should see.
    ///
    /// The path arrives absolute (the client resolved it against the pane's
    /// own cwd, which croft only approximates), so the checks here are about
    /// whether the file can be shown, not about where it is.
    fn apply_view_request(&mut self, path: &Path) -> crate::view_ipc::ViewReply {
        use crate::view_ipc::ViewReply;
        // The invariant `view_ipc`'s header states, actually enforced. The
        // client resolves against ITS cwd before sending, so a relative path
        // here came from something that is not `croft view`; resolving it
        // against croft's own cwd would silently open a different file than
        // the sender named. Same-uid, so this is not a trust boundary, but
        // an invariant no code checks is a comment rather than an invariant.
        if !path.is_absolute() {
            return ViewReply::Err {
                message: format!(
                    "the request must carry an absolute path, got {}",
                    path.display()
                ),
            };
        }
        // A REGULAR file, not merely something that exists and is not a
        // directory. `File::open` on a FIFO blocks until a writer appears, so
        // `mkfifo /tmp/f && croft view /tmp/f` from any pane froze the whole
        // editor permanently; `/dev/zero` took the same route and read until
        // the machine ran out of memory. Neither is reachable through the
        // Explorer without a deliberate human gesture, and this is reachable
        // by any process in any pane.
        //
        // The 20ms drain deadline does not cover it: that bounds the READ of
        // the request, and this is the step after. Bounding one stage of a
        // pipeline says nothing about the next.
        //
        // `metadata` follows symlinks, so a symlink to a real file still
        // opens (and a symlink to a FIFO is refused on the target's kind);
        // one stat answers all three questions the old `exists` + `is_dir`
        // pair asked in two.
        //
        // This bounds the file's KIND, not the time. `metadata` is itself a
        // blocking syscall on a client-supplied path, so `croft view` naming
        // something on a hung NFS mount still parks the frame loop here,
        // before the type check runs. A real bound needs the stat off this
        // thread.
        //
        // The OPEN below is the larger half of the same problem, and it is
        // not bounded either: `open_pinned` reaches `Editor::open`, which for
        // a PDF shells out to `pdftoppm` with no timeout (#493), and walks
        // archives and documents on this thread for their own formats. A
        // build script running `croft view out.pdf` on a large document parks
        // the editor for the render. Filed rather than fixed here: moving the
        // open off the frame loop changes how every viewer reports failure,
        // which is a bigger change than the channel that exposed it.
        //
        // There is also a TOCTOU window between this and the open,
        // which is same-uid and so inside the trust boundary the module
        // already argues from - noted so a later reader does not mistake the
        // check for airtight.
        let meta = match std::fs::metadata(path) {
            Ok(m) => m,
            Err(e) => {
                // Not necessarily absence: EACCES and ELOOP land here too,
                // and the old text claimed "no such file" over an errno that
                // said otherwise.
                return ViewReply::Err {
                    message: format!("cannot read {}: {e}", path.display()),
                };
            }
        };
        if meta.is_dir() {
            return ViewReply::Err {
                message: format!("{} is a directory", path.display()),
            };
        }
        if !meta.is_file() {
            return ViewReply::Err {
                message: format!("{} is not a regular file", path.display()),
            };
        }
        // Staged pipe input is stamped with THIS croft's pid before it opens,
        // so the staging sweep can spare a file a live croft is showing
        // instead of deleting it on age alone. `croft view -` input cannot be
        // produced again by re-running anything, and the tab re-opens the
        // path (a SQLite page turn does it on every page), so a sweep that
        // wins that race breaks a working tab and loses the only copy.
        // Returns None for an ordinary file, which is then opened as named.
        let claimed = crate::view_ipc::claim_staged(path, std::process::id());
        let path = claimed.as_deref().unwrap_or(path);
        match self.editor.open_pinned(path) {
            Ok(()) => {
                // Same route as an Explorer click, focus included: the user
                // asked for this from a prompt and expects to be looking at
                // it, not to find it filed behind the pane they typed in.
                self.focus_pane(Pane::Editor);
                self.sync_open_file_poll_mtime();
                self.status = format!("Opened {}", path.display());
                ViewReply::Ok
            }
            Err(e) => ViewReply::Err {
                message: format!("could not open {}: {e}", path.display()),
            },
        }
    }

    /// Check the relay inbox for completed pulls and surface them in the
    /// explorer. Returns true if any pending pull resolved (success,
    /// failure, or timeout) so the main loop knows to redraw.
    pub fn drain_remote_pulls(&mut self) -> bool {
        if self.pending_remote_pulls.is_empty() {
            return false;
        }
        let Some(inbox) = self.relay_inbox_path() else {
            self.pending_remote_pulls.clear();
            self.status = String::from("Drop relay vanished mid-pull");
            return true;
        };
        let mut still_pending: Vec<PendingRemotePull> = Vec::new();
        let mut placed: Vec<PathBuf> = Vec::new();
        let mut opened_urls: Vec<String> = Vec::new();
        let mut forwarded: Vec<(u16, u16)> = Vec::new();
        let mut errors: Vec<String> = Vec::new();
        let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
        let pulls = std::mem::take(&mut self.pending_remote_pulls);
        let mut clipboard_payload: Option<Vec<u8>> = None;
        for pull in pulls {
            let request_dir = inbox.join(&pull.request_id);
            let ok = request_dir.join(".ok");
            let err = request_dir.join(".err");
            if ok.exists() {
                match pull.kind {
                    RemotePullKind::File => {
                        let staged_src = request_dir.join(&pull.basename);
                        affected.insert(pull.dest_dir.clone());
                        match crate::widgets::file_tree::move_into(&pull.dest_dir, &staged_src) {
                            Ok(p) => placed.push(p),
                            Err(e) => errors.push(format!("{}: {e}", pull.src_display)),
                        }
                    }
                    RemotePullKind::Clipboard => {
                        let staged = request_dir.join("clipboard.txt");
                        match std::fs::read(&staged) {
                            Ok(bytes) => clipboard_payload = Some(bytes),
                            Err(e) => errors.push(format!("clipboard relay: {e}")),
                        }
                    }
                    RemotePullKind::Open => {
                        opened_urls.push(pull.src_display.clone());
                    }
                    RemotePullKind::Forward { remote_port } => {
                        let local_port = std::fs::read_to_string(&ok)
                            .ok()
                            .and_then(|s| s.trim().parse::<u16>().ok())
                            .unwrap_or(remote_port);
                        forwarded.push((remote_port, local_port));
                    }
                }
                let _ = std::fs::remove_dir_all(&request_dir);
            } else if err.exists() {
                let msg =
                    std::fs::read_to_string(&err).unwrap_or_else(|_| String::from("relay error"));
                errors.push(format!("{}: {}", pull.src_display, msg.trim()));
                let _ = std::fs::remove_dir_all(&request_dir);
            } else if pull.started_at.elapsed() > REMOTE_PULL_TIMEOUT {
                errors.push(format!("{}: timed out after 120s", pull.src_display));
                let _ = std::fs::remove_dir_all(&request_dir);
            } else {
                still_pending.push(pull);
            }
        }
        if let Some(bytes) = clipboard_payload
            && !bytes.is_empty()
        {
            self.paste_terminal_input(&bytes);
        }
        let resolved_any = !placed.is_empty()
            || !opened_urls.is_empty()
            || !forwarded.is_empty()
            || !errors.is_empty();
        for (remote_port, local_port) in &forwarded {
            self.ports.mark_forwarded(*remote_port, *local_port);
        }
        self.pending_remote_pulls = still_pending;
        for dir in &affected {
            if let Some(idx) = self.tree.index_of_dir(dir) {
                self.tree.refresh_children(idx);
            }
        }
        if !placed.is_empty() {
            self.tree.marked.clear();
            for p in &placed {
                self.tree.marked.insert(p.clone());
            }
            if let Some(first) = placed.first()
                && let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
            {
                self.tree.selected = idx;
                self.tree.anchor = idx;
            }
        }
        if resolved_any {
            self.status = if errors.is_empty() {
                if !forwarded.is_empty() && placed.is_empty() && opened_urls.is_empty() {
                    let (remote, local) = forwarded[0];
                    if local == remote {
                        format!("Forwarded port {remote} to your machine")
                    } else {
                        format!("Forwarded remote port {remote} to local {local}")
                    }
                } else if !opened_urls.is_empty() && placed.is_empty() {
                    if opened_urls.len() == 1 {
                        format!("Opened {} in your local browser", opened_urls[0])
                    } else {
                        format!("Opened {} URL(s) in your local browser", opened_urls.len())
                    }
                } else if placed.len() == 1 {
                    format!("Pulled {} from your Mac", placed[0].display())
                } else {
                    format!("Pulled {} item(s) from your Mac", placed.len())
                }
            } else if placed.is_empty() && opened_urls.is_empty() {
                format!("Drop relay failed: {}", errors.join("; "))
            } else {
                format!(
                    "Pulled {} / opened {}; failures: {}",
                    placed.len(),
                    opened_urls.len(),
                    errors.join("; "),
                )
            };
        }
        resolved_any
    }

    pub fn report_scp_results(
        &mut self,
        moved: usize,
        total: usize,
        errors: usize,
        affected_dirs: &[PathBuf],
    ) {
        for dir in affected_dirs {
            if let Some(idx) = self.tree.index_of_dir(dir) {
                self.tree.refresh_children(idx);
            }
        }
        self.status = if errors == 0 {
            format!("Uploaded {moved}/{total} via scp")
        } else {
            format!("Uploaded {moved}/{total} via scp; {errors} error(s)")
        };
    }

    /// Origin to stamp on a newly detected port: a remote session's ports are
    /// forwardable (and carry the host label), a local session's are already
    /// reachable.
    fn port_origin(&self) -> crate::widgets::ports::PortOrigin {
        use crate::widgets::ports::PortOrigin;
        if self.is_remote {
            PortOrigin::Remote(remote_host_label())
        } else {
            PortOrigin::Local
        }
    }

    /// Drain freshly scraped ports from every terminal and, on a low cadence,
    /// poll the socket table. Output-scrape hits are browser-facing
    /// announcements, so a new one raises the toast; socket-poll hits populate
    /// the PORTS tab silently. Returns whether anything changed (for redraw).
    /// Surface BEL rings and OSC 9 notifications from any pane in the status
    /// bar (VS Code shows a bell on the terminal tab; croft's status line is
    /// its equivalent). Returns true when either arrived so the loop redraws.
    fn drain_terminal_bells(&mut self) -> bool {
        self.reap_closed_terminals();
        // Long-command completion notice, the Ghostty/Warp behaviour: only
        // when the pane isn't the focused one (the user watching a pane sees
        // the command end themselves).
        const LONG_COMMAND_NOTIFY: std::time::Duration = std::time::Duration::from_secs(10);
        let mut rang: Option<String> = None;
        let mut notes: Vec<String> = Vec::new();
        let mut finished: Option<String> = None;
        let mut trigger_note: Option<String> = None;
        let mut captured: Vec<crate::widgets::captures::CapturedLine> = Vec::new();
        // Finished-command outputs to run through the build matchers after
        // the immutable pane sweep (#119): (pane uid, cwd, command, output).
        let mut build_scans: Vec<(u64, Option<PathBuf>, String, String)> = Vec::new();
        // Watch-matcher batches published mid-run (#252): (pane uid, cwd,
        // the cycle's diagnostics — empty clears the pane's entries).
        let mut watch_installs: Vec<(u64, Option<PathBuf>, Vec<crate::build_matchers::BuildDiag>)> =
            Vec::new();
        // A preLaunchTask completing settles the parked debug launch (#250);
        // recorded here and acted on after the sweep (launching mutates self).
        let mut settled_launch: Option<Option<i32>> = None;
        for t in &self.terminals {
            // Keep every pane on the current trigger set, wherever it was
            // created (a ptr-eq no-op when already current).
            t.set_triggers(self.triggers.clone());
            t.set_watch_set(self.watch_set.clone());
            for (cwd, batch) in t.drain_watch_batches() {
                watch_installs.push((t.uid(), cwd, batch));
            }
            for h in t.drain_trigger_hits() {
                match h.action {
                    crate::triggers::TriggerAction::Capture => {
                        captured.push(crate::widgets::captures::CapturedLine {
                            pane: t.label().to_string(),
                            shell_pid: t.shell_pid(),
                            message: h.message,
                            line: h.line,
                        });
                    }
                    crate::triggers::TriggerAction::Bell => {
                        trigger_note =
                            Some(format!("Trigger bell in {}: {}", t.label(), h.message));
                    }
                    _ => {
                        trigger_note = Some(format!("Trigger in {}: {}", t.label(), h.message));
                    }
                }
            }
            if t.take_bell() {
                rang = Some(t.label().to_string());
            }
            for msg in t.drain_notifications() {
                let cwd = t.local_shell_cwd();
                self.notifier.emit(
                    crate::notifications::Event::Osc9 {
                        pane: t.label().to_string(),
                        message: msg.clone(),
                    },
                    self.root_for_path(cwd.as_deref()),
                    &remote_host_label(),
                );
                notes.push(msg);
            }
            // Always drain so completions never pile up unseen.
            for f in t.drain_finished_commands() {
                if !f.output.is_empty() {
                    build_scans.push((t.uid(), f.cwd.clone(), f.cmd.clone(), f.output.clone()));
                }
                // Durable command history: every finished command with a
                // known text is recorded (cwd, exit, duration, timestamp)
                // for the Ctrl+Shift+R cross-session search.
                if !f.cmd.trim().is_empty() {
                    let ts = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs())
                        .unwrap_or(0);
                    self.command_history
                        .append(crate::command_history::HistoryEntry {
                            // The durable history is on disk and cross-
                            // session: a typed `export KEY=…` is masked
                            // like any other persisted text (#360).
                            cmd: crate::triggers::mask_text(f.cmd.trim(), &self.triggers, false),
                            cwd: f
                                .cwd
                                .as_deref()
                                .map(|p| p.display().to_string())
                                .unwrap_or_default(),
                            host: f.host.clone().unwrap_or_default(),
                            exit: f.exit,
                            dur_ms: f.dur.as_millis() as u64,
                            ts,
                        });
                }
                if let Some(p) = self.pending_debug_launch.as_ref()
                    && finished_settles_pending(t.uid(), &f.cmd, p.pane, &p.command)
                {
                    settled_launch = Some(f.exit);
                }
                if t.focused {
                    continue;
                }
                // The sinks decide by their own threshold (#358); the
                // status-bar notice keeps the fixed one below.
                self.notifier.emit(
                    crate::notifications::Event::CommandFinished {
                        pane: t.label().to_string(),
                        cmd: crate::triggers::mask_text(f.cmd.trim(), &self.triggers, false),
                        exit: f.exit,
                        dur: f.dur,
                        cwd: f.cwd.clone(),
                        host: f.host.clone(),
                    },
                    self.root_for_path(f.cwd.as_deref()),
                    &remote_host_label(),
                );
                if f.dur < LONG_COMMAND_NOTIFY {
                    continue;
                }
                let code = f.exit.map_or_else(|| String::from("?"), |c| c.to_string());
                finished = Some(format!(
                    "Command in {} finished: exit {code} in {}",
                    t.label(),
                    crate::widgets::terminal::human_duration(f.dur)
                ));
            }
        }
        if let Some(exit) = settled_launch
            && let Some(pending) = self.pending_debug_launch.take()
        {
            self.resume_pending_launch(exit, pending.step);
        }
        // Liveness fallback for a still-parked launch: the FinishedCommand
        // match depends on OSC 133 marks, and a pane without integration (or
        // one the user closed) would otherwise park the launch forever.
        let mut pending_aborted = false;
        if settled_launch.is_none()
            && let Some(p) = self.pending_debug_launch.as_ref()
        {
            let pane = self.terminals.iter().find(|t| t.uid() == p.pane);
            if let Some(reason) = pending_abort_reason(
                pane.is_some(),
                pane.is_some_and(|t| t.foreground_is_shell()),
                p.started.elapsed(),
            ) {
                self.pending_debug_launch = None;
                self.debug_error(format!(
                    "preLaunchTask abandoned: {reason} — debug launch aborted"
                ));
                pending_aborted = true;
            }
        }
        let mut build_changed = false;
        // Watch publishes first: a batch replaces the pane's entries
        // wholesale, and marks the pane so the watcher's own eventual
        // FinishedCommand rescan cannot resurrect stale cycles.
        for (pane, cwd, diags) in watch_installs {
            self.watch_published_panes.insert(pane);
            build_changed |= self.install_build_diags(pane, cwd.as_deref(), diags);
        }
        for (pane, cwd, cmd, output) in build_scans {
            build_changed |= self.apply_build_scan(pane, cwd.as_deref(), &cmd, &output);
        }
        // Captures collect silently (iTerm2's model: the panel is the
        // surface, not the status bar), but still trigger a redraw.
        let had_captures =
            !captured.is_empty() || build_changed || settled_launch.is_some() || pending_aborted;
        for c in captured {
            self.captures.push(c);
        }
        if let Some(msg) = trigger_note {
            self.status = msg;
            return true;
        }
        if had_captures {
            return true;
        }
        if let Some(msg) = notes.pop() {
            self.status = format!("Terminal notification: {msg}");
            return true;
        }
        if let Some(msg) = finished {
            self.status = msg;
            return true;
        }
        let Some(label) = rang else {
            return false;
        };
        self.status = format!("Bell in terminal: {label}");
        true
    }

    /// Cmd+Opt+Up / Cmd+Opt+Down in the terminal: scroll the previous / next
    /// OSC 133 prompt mark to the top of the pane.
    fn terminal_prompt_jump(&mut self, forward: bool) {
        let prompts = self.terminal().prompt_lines();
        let top = self.terminal().viewport_top_line();
        let Some(target) = crate::widgets::terminal::pick_prompt_jump(&prompts, top, forward)
        else {
            self.status = String::from(if prompts.is_empty() {
                "No command marks yet (shell integration needs a zsh prompt)"
            } else if forward {
                "No next command"
            } else {
                "No previous command"
            });
            return;
        };
        self.terminal_mut().scroll_line_to_top(target);
    }

    /// The most recent finished command in the active pane, for the
    /// `⌘K ⇧C`/`⇧S`/`⇧R` keyboard forms of the decoration-menu actions.
    fn last_command_decoration(&self) -> Option<crate::widgets::terminal::CommandDecoration> {
        self.terminal().command_decorations().last().copied()
    }

    /// The command decoration dot under the pointer, when the panel shows
    /// the terminal. Used both to open the decoration menu and to exempt
    /// dot cells from the resize-seam grab zones they can overlap.
    fn decoration_dot_at(
        &self,
        col: u16,
        row: u16,
    ) -> Option<(usize, crate::widgets::terminal::CommandDecoration)> {
        if !self.show_terminal || self.bottom_panel_tab != BottomPanelTab::Terminal {
            return None;
        }
        let idx = self.terminal_at_pos(col, row)?;
        self.terminals[idx]
            .decoration_at_screen(col, row)
            .map(|d| (idx, d))
    }

    fn copy_command_output(&mut self, idx: usize, d: crate::widgets::terminal::CommandDecoration) {
        let Some(t) = self.terminals.get(idx) else {
            return;
        };
        // Same clipboard rule as a selection copy (#360): rules marked
        // copy=masked keep their mask.
        let text = self.terminal_text_for_copy(t.command_output_text(&d));
        if text.is_empty() {
            self.status = String::from("Command produced no output");
            return;
        }
        let lines = text.lines().count();
        copy_to_clipboard(&text);
        self.status = if lines == 1 {
            String::from("Copied command output (1 line)")
        } else {
            format!("Copied command output ({lines} lines)")
        };
    }

    fn select_command_output(
        &mut self,
        idx: usize,
        d: crate::widgets::terminal::CommandDecoration,
    ) {
        let Some(t) = self.terminals.get_mut(idx) else {
            return;
        };
        t.select_command_output(&d);
        self.status = String::from(if t.selection().is_some_and(|s| s.has_area()) {
            "Command output selected"
        } else {
            "Command produced no output"
        });
    }

    fn rerun_command(&mut self, idx: usize, d: crate::widgets::terminal::CommandDecoration) {
        let Some(t) = self.terminals.get(idx) else {
            return;
        };
        let cmd = t.command_input_text(&d);
        if cmd.is_empty() {
            self.status = String::from("No command text recorded at that prompt");
            return;
        }
        self.terminals[idx].write_input(format!("{cmd}\r").as_bytes());
        self.status = format!("Re-running: {cmd}");
    }

    /// The context menu a click on a command decoration dot opens: a header
    /// with the outcome, then the VS Code decoration actions.
    fn open_command_decoration_menu(
        &mut self,
        origin: (u16, u16),
        d: crate::widgets::terminal::CommandDecoration,
    ) {
        let idx = self.active_terminal;
        let code = d.exit.map_or_else(|| String::from("?"), |c| c.to_string());
        let header = match d.duration {
            Some(dur) => format!(
                "exit {code} in {}",
                crate::widgets::terminal::human_duration(dur)
            ),
            None => format!("exit {code}"),
        };
        self.context_menu = Some(ContextMenu {
            origin,
            items: vec![
                MenuEntry::header(header),
                MenuEntry::Item {
                    label: String::from("Copy Output"),
                    action: MenuAction::CopyCommandOutput(idx, d),
                },
                MenuEntry::Item {
                    label: String::from("Select Output"),
                    action: MenuAction::SelectCommandOutput(idx, d),
                },
                MenuEntry::Item {
                    label: String::from("Re-run Command"),
                    action: MenuAction::RerunCommand(idx, d),
                },
            ],
            selected: 1,
            open_submenu: None,
            submenu_selected: 0,
            target_dir: self.tree.root.clone(),
        });
    }

    fn drain_ports_and_poll(&mut self) -> bool {
        let mut changed = false;
        if self
            .port_toast
            .as_ref()
            .is_some_and(|t| t.shown_at.elapsed() > PORT_TOAST_TTL)
        {
            self.port_toast = None;
            changed = true;
        }
        let origin = self.port_origin();
        let scraped: Vec<crate::port_detect::PortHit> = self
            .terminals
            .iter()
            .flat_map(|t| t.drain_ports())
            .collect();
        for hit in scraped {
            let port = hit.port;
            let process = hit.process.clone();
            if self
                .ports
                .upsert(port, hit.url, hit.process, origin.clone())
            {
                changed = true;
            }
            // Toast on the scrape confirmation, not on first insert: the silent
            // socket poll may have added the port first (common on a remote
            // session), which must not swallow the toast.
            if self.ports.note_scrape_toast(port) {
                self.show_port_toast(port, process);
                changed = true;
            }
        }
        // Latest background-poll snapshot (a complete listener set): add new
        // ports, then reconcile so ports that stopped listening go not-live and
        // eventually drop. Only the newest queued snapshot matters.
        if let Some(poll) = self.port_poll_rx.try_iter().last() {
            for hit in poll.hits {
                if self
                    .ports
                    .upsert(hit.port, hit.url, hit.process, origin.clone())
                {
                    changed = true;
                }
            }
            // Reconcile only against the unscoped listener set. `None` means
            // neither `lsof` nor `ss` ran, which is no evidence at all — far
            // better to leave every row alone than to retire live ports and
            // cancel their tunnels on a failed probe.
            if let Some(live) = poll.listening {
                let outcome = self.ports.reconcile_live(&live);
                if outcome.changed {
                    changed = true;
                }
                // A dropped forward's tunnel is no longer needed — cancel it.
                for (local, remote) in outcome.torn_down {
                    self.request_remote_unforward(local, remote);
                }
            }
        }
        // On cadence, kick off a fresh poll off-thread — `lsof`/`ps` block for
        // tens of ms and must never run on the event loop. One in flight max.
        if self.last_port_poll.elapsed() >= PORT_POLL_INTERVAL
            && !self
                .port_poll_inflight
                .load(std::sync::atomic::Ordering::Relaxed)
        {
            self.last_port_poll = std::time::Instant::now();
            let pids: Vec<i32> = self
                .terminals
                .iter()
                .filter_map(|t| t.pid().map(|p| p as i32))
                .collect();
            if !pids.is_empty() {
                let tx = self.port_poll_tx.clone();
                let inflight = self.port_poll_inflight.clone();
                inflight.store(true, std::sync::atomic::Ordering::Relaxed);
                std::thread::spawn(move || {
                    // Two questions, two scans. The subtree scan says what to
                    // SURFACE (a system daemon is not the user's dev server);
                    // the unscoped one says what is still UP, which the subtree
                    // cannot answer for a port nobody in it owns.
                    let mut hits: Vec<crate::port_detect::PortHit> = Vec::new();
                    for pid in pids {
                        for hit in crate::port_detect::poll_listeners(pid) {
                            if !hits.iter().any(|h| h.port == hit.port) {
                                hits.push(hit);
                            }
                        }
                    }
                    let listening = crate::port_detect::poll_all_listening();
                    let _ = tx.send(PortPoll { hits, listening });
                    inflight.store(false, std::sync::atomic::Ordering::Relaxed);
                });
            }
        }
        changed
    }

    /// A click on one of the update popup's buttons (#333). Update stages
    /// the build and leaves the popup up as a progress line; Later and
    /// Relaunch both take it down. A click elsewhere returns false.
    fn handle_update_toast_click(&mut self, x: u16, y: u16) -> bool {
        let Some(toast) = self.update_toast.as_ref() else {
            return false;
        };
        let Some(action) = toast
            .buttons
            .iter()
            .find(|(r, _)| rect_contains(*r, x, y))
            .map(|(_, a)| *a)
        else {
            return false;
        };
        let version = toast.version.clone();
        match action {
            UpdateToastAction::Update => {
                if self.staged_install.is_none() && self.self_install.is_none() {
                    self.start_staged_update(version);
                }
            }
            UpdateToastAction::Later => {
                self.update_toast = None;
                self.dismiss_update_offer(&version);
            }
            UpdateToastAction::Relaunch => {
                self.update_toast = None;
                // The popup describes the staged release: only ITS
                // readiness may fire it, never a drift rebuild's.
                if self.staged_update_binary().is_some() {
                    self.pending_reexec = true;
                    self.quit = true;
                }
            }
        }
        true
    }

    fn show_port_toast(&mut self, port: u16, process: Option<String>) {
        self.port_toast = Some(PortToast {
            port,
            process,
            origin_remote: self.is_remote,
            shown_at: std::time::Instant::now(),
            buttons: Vec::new(),
        });
    }

    /// Seat, re-judge, or unseat the agent in EVERY pane (#344), from the
    /// `(shell_pid, process_name)` samples the pill uses, and queue the
    /// transitions. Driven over panes rather than over samples: a pane whose
    /// foreground did not resolve this round (the agent exited and took the
    /// shell with it, a pid `sysinfo` missed) has no sample, and that must
    /// unseat it rather than leave the badge on forever. `quiet_after` is
    /// the working/quiet threshold ([`crate::agents::QUIET_AFTER`]; tests
    /// pass zero). Returns whether any pane's lane changed.
    pub(crate) fn apply_agent_samples(
        &mut self,
        samples: &[(i32, String)],
        quiet_after: std::time::Duration,
    ) -> bool {
        let by_pid: std::collections::HashMap<i32, &str> = samples
            .iter()
            .map(|(pid, name)| (*pid, name.as_str()))
            .collect();
        let mut changed = false;
        for t in &mut self.terminals {
            let next = t
                .shell_pid()
                .and_then(|pid| by_pid.get(&pid))
                .and_then(|name| self.agents.classify(name))
                .map(|kind| crate::agents::AgentLane {
                    name: kind.name.clone(),
                    status: crate::agents::judge(kind, t.quiet_for(), &t.tail_rows(6), quiet_after),
                });
            let prev = t.agent().cloned();
            if prev == next {
                continue;
            }
            let pane = t.label().to_string();
            self.agent_events.extend(crate::agents::transition(
                &pane,
                prev.as_ref(),
                next.as_ref(),
            ));
            t.set_agent(next);
            changed = true;
        }
        changed
    }

    /// Consume the agent transitions the last sample queued: a waiting agent
    /// is announced in the status bar (the chip and the pill already show
    /// it). Returns whether anything was said.
    fn drain_agent_events(&mut self) -> bool {
        let mut said = false;
        while let Some(ev) = self.agent_events.pop_front() {
            // A gone agent with nothing left to review takes its lane with
            // it; one with a queue keeps it, since the files it changed
            // still need looking at (#345). The event is per PANE while the
            // lane is per NAME, so a second pane still running the same
            // agent — or an agent swap in one pane, which fires Gone then
            // Seated — must not take the shared lane down with it.
            if let crate::agents::AgentEvent::Gone { agent, .. } = &ev
                && self.agent_ledger.unreviewed_count(agent) == 0
                && !self
                    .terminals
                    .iter()
                    .any(|t| t.agent().is_some_and(|a| a.name == *agent))
            {
                let agent = agent.clone();
                // No decoration sync needed here, and deliberately so: the
                // guard above only lets this run when the lane has NOTHING
                // unreviewed, so it removes no row the Explorer is drawing
                // a dot for (#345).
                self.agent_ledger.forget(&agent);
            }
            if let crate::agents::AgentEvent::Waiting { pane, agent } = ev {
                self.status = format!("{agent} in {pane} is waiting for your input");
                said = true;
            }
        }
        said
    }

    /// `(agents seated, of which waiting)` across every pane, for the chip.
    fn agent_counts(&self) -> (usize, usize) {
        let seated = self
            .terminals
            .iter()
            .filter(|t| t.agent().is_some())
            .count();
        let waiting = self
            .terminals
            .iter()
            .filter(|t| {
                t.agent()
                    .is_some_and(|a| a.status == crate::agents::AgentStatus::Waiting)
            })
            .count();
        (seated, waiting)
    }

    /// The agents whose panes are producing output right now (#345). A
    /// merely SEATED agent does not count: a quiet agent's pane is no
    /// reason to blame it for the user's own save.
    fn working_agents(&self) -> Vec<String> {
        let mut names: Vec<String> = self
            .terminals
            .iter()
            .filter_map(|t| t.agent())
            .filter(|lane| lane.status == crate::agents::AgentStatus::Working)
            .map(|lane| lane.name.clone())
            .collect();
        names.sort();
        names.dedup();
        names
    }

    /// Record each changed file against every working agent, hashing its
    /// current content. A file that cannot be read right now is skipped
    /// rather than recorded at a stale hash.
    ///
    /// A DELETION is processed whether or not an agent is working: a file
    /// can be removed after its agent goes idle, and the row would
    /// otherwise sit in the queue forever pointing at a file that is not
    /// there (its lane staying visible with it). Only attribution — adding
    /// or updating a row — needs a working agent to attribute to.
    fn attribute_writes_to_working_agents(
        &mut self,
        changed: &std::collections::BTreeSet<PathBuf>,
    ) -> bool {
        let working = self.working_agents();
        let mut any = false;
        // Resolved once: the roots cannot change inside this loop, and on a
        // symlinked root the direct check never hits, so leaving it inside
        // would pay `files x roots` canonicalisations on every drain.
        let root_canons = self.root_canons();
        for path in changed {
            // Only workspace files: an agent editing its own config under
            // $HOME is not part of this workspace's review queue. ANY root
            // counts, not just the primary — a secondary folder's files are
            // as much this session's work as the first folder's (#345).
            // Compare in the same spelling on both sides. The watcher reports
            // the realpath, while a root is stored as the user gave it — so on
            // macOS a workspace under /var arrives as /private/var and matches
            // no root. Every agent write was silently dropped and the queue
            // stayed empty with nothing failing. Any root reached through a
            // symlink has the same shape, which is ordinary on Linux too.
            //
            // The path is recorded in the form the ROOT uses, so the ledger's
            // keys match what the Explorer's rows are keyed on and a later
            // "mark reviewed" finds the row instead of adding a second.
            let Some(under_root) = self.path_under_roots(&root_canons, path) else {
                continue;
            };
            let path = &under_root;
            match crate::agent_lane::read_baseline(path) {
                // Attribution needs someone to attribute to; a quiet
                // agent's pane is no reason to blame it for the user's
                // own save.
                crate::agent_lane::Baseline::Hash(hash) if !working.is_empty() => {
                    any |= self.agent_ledger.record_write(path, hash, &working);
                }
                crate::agent_lane::Baseline::Hash(_) => {}
                // The agent deleted it: the row goes, rather than sitting in
                // the queue forever pointing at a file that is not there.
                crate::agent_lane::Baseline::Gone => {
                    any |= self.agent_ledger.forget_path(path);
                }
                // Unreadable this instant; the next write re-reports it.
                crate::agent_lane::Baseline::Unreadable => {}
            }
        }
        any
    }

    /// `path` expressed under whichever workspace root owns it, or `None`
    /// when no root does.
    ///
    /// Tries the path as given first — the common case, costing nothing —
    /// then compares canonicalised, which is what a file watcher's realpath
    /// needs to match a root the user spelled with a symlink in it. The
    /// returned path is rooted the way the ROOT is spelled, so everything
    /// keyed on it agrees with the Explorer's rows.
    ///
    /// A DELETED path still resolves. `canonicalize` stats the final
    /// component and fails with `ENOENT` on a path that is gone — which is
    /// exactly what a deletion event carries, so resolving the whole path
    /// would make the ledger's `forget_path` arm unreachable and strand rows
    /// on files that no longer exist. The walk therefore resolves the
    /// deepest ancestor that DOES exist and re-attaches the tail: a deleted
    /// file's parent directory is almost always still there, and when it is
    /// not the walk keeps climbing.
    ///
    /// Longest prefix wins, mirroring `WorkspaceRoots::owning_root`: with
    /// nested roots the deeper one owns the path, and picking the first
    /// match instead would make the ledger's key depend on the order the
    /// user added folders.
    /// The roots are resolved by the CALLER so a loop over many changed
    /// paths can hoist the canonicalisation, which depends only on the root
    /// set and cannot change between iterations. Not a cache — there is
    /// nothing to invalidate, because the value does not outlive the loop
    /// that computes it.
    fn path_under_roots(&self, root_canons: &[(PathBuf, PathBuf)], path: &Path) -> Option<PathBuf> {
        // The direct check FIRST, and that ordering is load-bearing rather
        // than merely quick. If an intermediate directory is itself a
        // symlink pointing outside the workspace, resolving the whole path
        // would land the result outside the root; hitting on the spelled
        // path here means the walk below never sees that case.
        if self.roots.owning_root(path).is_some() {
            return Some(path.to_path_buf());
        }
        let canon = canonicalize_existing_ancestor(path)?;
        root_canons
            .iter()
            .cloned()
            .filter_map(|(spelled, canon_root)| {
                let rel = canon.strip_prefix(&canon_root).ok()?;
                Some((canon_root.components().count(), spelled.join(rel)))
            })
            .max_by_key(|(depth, _)| *depth)
            .map(|(_, joined)| joined)
    }

    /// Each root as `(spelling, canonical)`.
    ///
    /// Recomputed per call rather than cached on `App`: the set is one or
    /// two entries in practice, and this runs only when a path failed the
    /// direct check — i.e. on a symlinked root, where it is the price of the
    /// feature working at all. A cache here would need invalidating from
    /// every root mutation, which is more ways to be wrong than it saves.
    fn root_canons(&self) -> Vec<(PathBuf, PathBuf)> {
        self.roots
            .iter()
            .map(|r| {
                (
                    r.to_path_buf(),
                    std::fs::canonicalize(r).unwrap_or_else(|_| r.to_path_buf()),
                )
            })
            .collect()
    }

    /// Called from every place the ledger's CONTENT changes, rather than on
    /// a schedule: a decoration that lags the thing it describes is worse
    /// than none, because "no dot" is exactly what a reviewed file looks
    /// like, so a stale one says the user reviewed something they did not.
    ///
    /// Every site that mutates the ledger's content calls this, and here is
    /// why that is all of them. `record_write`
    /// and `forget_path` both run under the fs-watch drain, behind
    /// `attribute_writes_to_working_agents`'s return; `mark_reviewed` under
    /// `mark_agent_file_reviewed`; `mark_lane_reviewed` under
    /// `mark_agent_lane_reviewed`; `forget_path` again from
    /// `remove_workspace_folder`. Of the ledger's other `&mut self`
    /// methods, `note_dropped_events` and `settle_if_empty` move only the
    /// incomplete flag and cannot change the set, and `forget` is reachable
    /// only behind a guard that requires the lane to be empty already.
    fn sync_agent_lane_decorations(&mut self) {
        let paths = self.agent_ledger.unreviewed_paths();
        // Skip the Arc swap when both sides are empty, which is the common
        // shape early in a session and after a review clears the queue.
        if paths.is_empty() && self.tree.agent_touched.is_empty() {
            return;
        }
        self.tree.agent_touched = std::sync::Arc::new(paths);
    }

    /// Snapshot `bytes` as `path`'s review baseline and return the millis
    /// that names it (#345).
    ///
    /// The store is only ever written by croft's OWN saves; the agent-write
    /// path that creates lane rows records nothing. So adopting whatever
    /// snapshot happened to be newest anchored the review to an unrelated
    /// earlier save and then labelled the diff "(reviewed)" — the exact
    /// "baseline other than the one claimed" the diff refuses elsewhere.
    /// Recording here is what makes the anchor name the reviewed content.
    ///
    /// `record_in` dedupes identical content and, inside the merge window,
    /// REPLACES the newest entry instead of appending — so the snapshot that
    /// ends up holding these bytes need not be at `millis`. Read the store
    /// back rather than assuming, and return `None` when nothing holds them:
    /// history is best-effort, and a row with no anchor is still reviewed,
    /// it just cannot show a diff.
    fn record_review_baseline(history_root: &Path, path: &Path, bytes: &[u8]) -> Option<u64> {
        let millis = now_millis();
        let _ = crate::history::record_in(history_root, path, bytes, millis);
        crate::history::entries_in(history_root, path)
            .into_iter()
            .find(|s| std::fs::read(&s.file).is_ok_and(|held| held == bytes))
            .map(|s| s.millis)
    }

    /// Diff one agent-lane row against the snapshot that was its baseline
    /// when the user last marked it reviewed (#345), rather than against
    /// HEAD.
    ///
    /// Refuses rather than falling back to a different baseline. A row with
    /// no recorded snapshot (never reviewed, or reviewed before the store
    /// had one) and a row whose snapshot has since been PRUNED — the store
    /// keeps 50 per file against a 1s autosave, so this is a live case, not
    /// only a legacy one — both say so. A diff against a baseline other than
    /// the one claimed is worse than no diff, because the user cannot see
    /// which one they got.
    pub(crate) fn diff_agent_lane_row(&mut self, agent: &str, path: &Path) {
        // "Restore Snapshot" writes to the path recorded here, and only
        // `open_timeline_diff` cleared it. Browsing a.txt's timeline and then
        // opening this diff on b.txt left restore armed at a.txt, so the
        // command would overwrite a file the user was not even looking at.
        // Disarm on every exit below, including the refusals: a refused diff
        // leaves the PREVIOUS diff on screen, and arming restore to that is
        // exactly the stale pairing this guards.
        self.history_restore = None;
        let Some(row) = self
            .agent_ledger
            .lane(agent)
            .into_iter()
            .find(|f| f.path == path)
        else {
            self.status = format!("{} is not in {agent}'s lane", path.display());
            return;
        };
        let Some(millis) = row.reviewed_millis else {
            self.status = if row.reviewed_hash.is_some() {
                format!(
                    "{} was reviewed before a snapshot existed - nothing to diff against",
                    path.display()
                )
            } else {
                format!("{} has not been reviewed yet", path.display())
            };
            return;
        };
        let Some(snap_file) = crate::history::snapshot_file_in(&self.history_root, path, millis)
        else {
            self.status = format!(
                "The snapshot {} was reviewed against is no longer available",
                path.display()
            );
            return;
        };
        let Ok(content) = std::fs::read(&snap_file) else {
            self.status = format!("Could not read the reviewed snapshot of {}", path.display());
            return;
        };
        // Snapshots hold raw bytes; decode like the local-history diff above
        // so a UTF-16 file diffs as text rather than mojibake.
        let enc = encoding_rs::Encoding::for_bom(&content)
            .map(|(e, _)| e)
            .unwrap_or(encoding_rs::UTF_8);
        let text = enc.decode(&content).0.into_owned();
        let rel = match path.strip_prefix(&self.tree.root) {
            Ok(r) => r.to_string_lossy().into_owned(),
            Err(_) => path.display().to_string(),
        };
        let label = std::path::PathBuf::from(format!("{rel} (reviewed)"));
        if let Err(e) = self
            .editor
            .open_head_diff_with_text(label, &text, path, false)
        {
            self.status = format!("Could not open the reviewed diff: {e}");
            return;
        }
        self.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft { left_text: text });
        // Armed to the snapshot now on screen, matching `open_timeline_diff`:
        // "Restore Snapshot" puts back the version the user reviewed.
        self.history_restore = Some((path.to_path_buf(), millis, content));
        self.focus_pane(Pane::Editor);
        self.status = format!("{rel}: changes since you last reviewed it");
    }

    /// Mark one file reviewed in one agent's lane (#345): the content on
    /// DISK now becomes the baseline, so the row returns only on a later
    /// write.
    pub(crate) fn mark_agent_file_reviewed(&mut self, agent: &str, path: &Path) -> bool {
        let changed = self.mark_agent_file_reviewed_inner(agent, path);
        if changed {
            self.sync_agent_lane_decorations();
        }
        changed
    }

    fn mark_agent_file_reviewed_inner(&mut self, agent: &str, path: &Path) -> bool {
        // A file too big to hash is too big to snapshot: `read_baseline`
        // stamps those from metadata rather than slurping 4 MiB+, and
        // copying one into the history store on every review would be worse.
        // It reviews with NO anchor - honest, and the diff then says it has
        // nothing to compare against.
        if std::fs::metadata(path).is_ok_and(|m| m.len() > crate::agent_lane::MAX_HASH_BYTES) {
            return match crate::agent_lane::read_baseline(path) {
                crate::agent_lane::Baseline::Hash(hash) => {
                    self.agent_ledger.mark_reviewed(agent, path, hash, None)
                }
                crate::agent_lane::Baseline::Gone => self.agent_ledger.forget_path(path),
                crate::agent_lane::Baseline::Unreadable => {
                    self.status = format!("Could not read {} to mark it reviewed", path.display());
                    false
                }
            };
        }
        // One read, used for BOTH the hash and the snapshot: reading twice
        // lets a write land in between, and the baseline would then be a hash
        // of content the anchor does not hold.
        match std::fs::read(path) {
            Ok(bytes) => {
                let hash = crate::agent_lane::content_hash(&bytes);
                let snap = Self::record_review_baseline(&self.history_root, path, &bytes);
                self.agent_ledger.mark_reviewed(agent, path, hash, snap)
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                self.agent_ledger.forget_path(path)
            }
            // Unreadable right now is NOT reviewed: say so instead of
            // clearing content the user has not seen.
            Err(_) => {
                self.status = format!("Could not read {} to mark it reviewed", path.display());
                false
            }
        }
    }

    /// Mark an agent's whole lane reviewed (#345).
    pub(crate) fn mark_agent_lane_reviewed(&mut self, agent: &str) -> usize {
        let root = self.history_root.clone();
        // Same contract as the single-file path: the anchor must hold the
        // bytes that were hashed, so read once and snapshot THOSE. Reading
        // separately in the two closures would let a write land between them.
        let (reviewed, dropped) = self.agent_ledger.mark_lane_reviewed(agent, |path| {
            // Too big to hash is too big to snapshot: stamp it and
            // review with no anchor, as the single-file path does.
            if std::fs::metadata(path).is_ok_and(|m| m.len() > crate::agent_lane::MAX_HASH_BYTES) {
                return (crate::agent_lane::read_baseline(path), None);
            }
            match std::fs::read(path) {
                Ok(bytes) => (
                    crate::agent_lane::Baseline::Hash(crate::agent_lane::content_hash(&bytes)),
                    Self::record_review_baseline(&root, path, &bytes),
                ),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                    (crate::agent_lane::Baseline::Gone, None)
                }
                Err(_) => (crate::agent_lane::Baseline::Unreadable, None),
            }
        });
        // A file that vanished was not REVIEWED; saying so would tell the
        // user they looked at something that is not there.
        let gone = match dropped {
            0 => String::new(),
            1 => String::from(", 1 gone"),
            n => format!(", {n} gone"),
        };
        self.status = match reviewed {
            0 if dropped == 0 => format!("{agent}: nothing waiting for review"),
            0 => format!("{agent}: nothing to review{gone}"),
            1 => format!("{agent}: 1 file marked reviewed{gone}"),
            n => format!("{agent}: {n} files marked reviewed{gone}"),
        };
        if reviewed + dropped > 0 {
            self.sync_agent_lane_decorations();
        }
        reviewed + dropped
    }

    /// Focus the first waiting agent's pane, else the first seated one. Goes
    /// through `set_bottom_panel_tab` like `captures_open_selected`, so a
    /// click from the editor with the panel collapsed reveals the pane
    /// rather than focusing something the user cannot see.
    fn focus_agent_pane(&mut self) {
        let pick = self
            .terminals
            .iter()
            .position(|t| {
                t.agent()
                    .is_some_and(|a| a.status == crate::agents::AgentStatus::Waiting)
            })
            .or_else(|| self.terminals.iter().position(|t| t.agent().is_some()));
        match pick {
            Some(idx) => {
                self.reveal_terminal_pane(idx);
                self.set_bottom_panel_tab(BottomPanelTab::Terminal);
            }
            // The chip is showing a review queue whose agents have all gone:
            // a click that silently did nothing was the worst of the three
            // options (#345 review).
            None => self.run_command(crate::widgets::command_palette::Command::ShowAgentLane),
        }
    }

    /// The workspace root a path belongs to, for a notification's title and
    /// deep link (#358): in a multi-root session an event from a pane in a
    /// secondary root must name that root, not the primary. The primary is
    /// the fallback for a path outside every root, or no path at all.
    fn root_for_path(&self, path: Option<&Path>) -> &Path {
        path.and_then(|p| self.roots.iter().find(|r| p.starts_with(r)))
            .unwrap_or_else(|| self.roots.primary())
    }

    /// Refresh each pane's auto-label from its live foreground process. The
    /// `tcgetpgrp` reads are cheap and stay on the loop; the `sysinfo` name
    /// lookups (the slow part) run on a one-shot background thread, keyed by
    /// shell pid so results land on the right pane even if panes moved. Returns
    /// whether any label changed (for redraw).
    fn refresh_terminal_labels(&mut self) -> bool {
        let mut changed = false;
        // Apply whatever the last background lookup resolved.
        if let Some(samples) = self.ssh_rx.try_iter().last() {
            self.apply_ssh_samples(samples);
        }
        if let Some(labels) = self.label_rx.try_iter().last() {
            for (shell_pid, name) in &labels {
                if let Some(t) = self
                    .terminals
                    .iter_mut()
                    .find(|t| t.shell_pid() == Some(*shell_pid))
                    && t.label() != name
                {
                    t.set_auto_label(name.clone());
                    changed = true;
                }
            }
            changed |= self.apply_agent_samples(&labels, crate::agents::QUIET_AFTER);
        }
        if self.last_label_refresh.elapsed() >= TERMINAL_LABEL_INTERVAL
            && !self
                .label_inflight
                .load(std::sync::atomic::Ordering::Relaxed)
        {
            self.last_label_refresh = std::time::Instant::now();
            // (shell_pid, foreground_pid) gathered cheaply on the loop.
            let targets: Vec<(i32, i32)> = self
                .terminals
                .iter()
                .filter_map(|t| match (t.shell_pid(), t.foreground_pid()) {
                    (Some(sp), Some(fg)) => Some((sp, fg)),
                    _ => None,
                })
                .collect();
            if targets.is_empty() {
                // No pane has a foreground process to sample: any seated
                // agent is gone, and only an empty sample says so.
                changed |= self.apply_agent_samples(&[], crate::agents::QUIET_AFTER);
            }
            if !targets.is_empty() {
                let tx = self.label_tx.clone();
                let ssh_tx = self.ssh_tx.clone();
                let sample_ssh = !self.remote_offer_disabled;
                let inflight = self.label_inflight.clone();
                inflight.store(true, std::sync::atomic::Ordering::Relaxed);
                std::thread::spawn(move || {
                    let named: Vec<(i32, i32, String)> = targets
                        .into_iter()
                        .filter_map(|(sp, fg)| {
                            crate::widgets::terminal::process_name(fg).map(|n| (sp, fg, n))
                        })
                        .collect();
                    // The ssh-pane offer (#364) rides this thread: only a
                    // pane whose foreground IS ssh pays the argv read (a
                    // whole-process-table enumeration), and the config
                    // parse runs once per pass and only when one does. The
                    // verdicts themselves are `remote::ssh_pane_samples`,
                    // kept pure so the gate is testable without a pane.
                    if sample_ssh {
                        let _ = ssh_tx.send(crate::remote::ssh_pane_samples(
                            &named,
                            crate::remote::discover_ssh_targets,
                            crate::widgets::terminal::process_cmdline,
                        ));
                    }
                    let resolved: Vec<(i32, String)> =
                        named.into_iter().map(|(sp, _, n)| (sp, n)).collect();
                    let _ = tx.send(resolved);
                    inflight.store(false, std::sync::atomic::Ordering::Relaxed);
                });
            }
        }
        changed
    }

    /// `⏎` on a port: open it. A local (or already-forwarded) port opens
    /// straight away; a remote port that isn't forwarded yet is forwarded first,
    /// then opened.
    fn ports_open_selected(&mut self) {
        let Some(entry) = self.ports.selected() else {
            return;
        };
        match plan_port_open(entry, self.drop_relay_active()) {
            PortOpenAction::Forward(port) => self.request_remote_forward(port, true),
            PortOpenAction::OpenViaRelay(url) => {
                self.request_remote_url_open(url.clone());
                self.status = format!("Opening {url} in your local browser");
            }
            PortOpenAction::OpenDirect(url) => match open_url(&url) {
                Ok(()) => self.status = format!("Opened {url}"),
                Err(e) => self.status = format!("Open failed: {e}"),
            },
            PortOpenAction::Nothing => {}
        }
    }

    fn ports_forward_selected(&mut self) {
        use crate::widgets::ports::PortOrigin;
        let Some(entry) = self.ports.selected() else {
            return;
        };
        if !matches!(entry.origin, PortOrigin::Remote(_)) || entry.forwarded {
            self.status = String::from("Port is already reachable locally");
            return;
        }
        let port = entry.port;
        self.request_remote_forward(port, false);
    }

    fn ports_copy_selected(&mut self) {
        let Some(entry) = self.ports.selected() else {
            return;
        };
        let addr = entry
            .open_url()
            .unwrap_or_else(|| format!("localhost:{}", entry.port));
        if copy_to_clipboard(&addr) {
            self.status = format!("Copied {addr}");
        } else {
            self.status = String::from("Copy failed");
        }
    }

    fn ports_stop_selected(&mut self) {
        use crate::widgets::ports::PortOrigin;
        let Some(entry) = self.ports.selected() else {
            return;
        };
        let port = entry.port;
        let forwarded = matches!(
            (&entry.origin, entry.forwarded, entry.local_port),
            (PortOrigin::Remote(_), true, Some(_))
        );
        // Two different gestures share `x`. Stopping a forward leaves the
        // server running and the row in place, so the port must stay
        // detectable; dismissing the row is the one that suppresses it.
        if forwarded {
            if let Some((local, remote)) = self.ports.stop_forwarding(port) {
                self.request_remote_unforward(local, remote);
            }
            self.status = format!("Stopped forwarding port {port} (the server keeps running)");
        } else {
            self.ports.remove(port);
            self.status = format!("Dismissed port {port} from the list (the server keeps running)");
        }
    }

    /// Cmd/Ctrl+click in the active terminal: if a printed http(s) URL sits
    /// under the cursor, act on it (forward a remote dev-server port and open,
    /// or open the link) and return true so the click doesn't start a
    /// selection. Returns false when there's no URL there.
    /// Whether the built-in Ctrl/Cmd+click would open something at this cell.
    ///
    /// Pure: the lookups [`Self::terminal_url_click`] and
    /// [`Self::terminal_file_click`] perform, with the opening left out. The
    /// swallow branch needs to know whether declining a prefix click COSTS the
    /// user anything, and it cannot find out by calling the acting versions.
    ///
    /// BOTH arms of the built-in's `||` are covered deliberately: checking
    /// only the URL half would let a Ctrl+click on a file reference be
    /// swallowed and its jump-to-file lost, which is the same defect one
    /// branch over.
    ///
    /// Deliberately conservative on the file half. `terminal_file_click`
    /// resolves relative paths against the shell's cwd and touches the
    /// filesystem; reproducing that here would duplicate logic that then
    /// drifts. A file REFERENCE under the cursor is enough to defer to the
    /// built-in — at worst the prefix click is not swallowed, which costs a
    /// stray built-in action rather than a lost one.
    ///
    /// Takes the CLICKED pane's index rather than reading `self.terminal()`.
    /// The built-in activates the clicked pane before it looks for a link, so
    /// a predicate reading the ACTIVE pane answers about different content
    /// whenever the two differ — which is any split layout where the click
    /// lands outside the focused pane.
    fn terminal_would_open_something_at(&self, idx: usize, col: u16, row: u16) -> bool {
        let Some(t) = self.terminals.get(idx) else {
            return false;
        };
        if t.hyperlink_at_screen(col, row).is_some() {
            return true;
        }
        t.line_text_at(col, row).is_some_and(|(text, c)| {
            crate::port_detect::url_at(&text, c).is_some()
                || crate::file_ref::file_ref_at(&text, c).is_some()
        })
    }

    /// Cmd/Ctrl+click in the active terminal: if a printed http(s) URL sits
    /// under the cursor, act on it (forward a remote dev-server port and open,
    /// or open the link) and return true so the click doesn't start a
    /// selection. Returns false when there's no URL there.
    fn terminal_url_click(&mut self, col: u16, row: u16) -> bool {
        // A real OSC 8 hyperlink stored in the cell wins over text sniffing —
        // the visible text of a linked cell often isn't the URI at all.
        if let Some(uri) = self.terminal().hyperlink_at_screen(col, row) {
            self.open_detected_url(&uri);
            return true;
        }
        let Some((text, c)) = self.terminal().line_text_at(col, row) else {
            return false;
        };
        let Some(url) = crate::port_detect::url_at(&text, c) else {
            return false;
        };
        self.open_detected_url(&url);
        true
    }

    /// Seed the Search sidebar from the last `grep`/`rg` command run in the
    /// focused terminal, then run it. The Search panel already has multi-file
    /// replace-all, so this turns a terminal search into an editable,
    /// replace-across-every-match buffer (the `:cdo` loop) with one command.
    fn search_from_last_terminal_command(&mut self) {
        let input = {
            let term = self.terminal();
            let decs = term.command_decorations();
            match decs.last() {
                Some(d) => term.command_input_text(d),
                None => {
                    self.status = String::from("No terminal command yet to search from");
                    return;
                }
            }
        };
        if !self.seed_search_from_command(input.trim()) {
            self.status =
                String::from("Last terminal command wasn't a grep/rg search — nothing to seed");
        }
    }

    /// Populate and run the Search panel from a parsed terminal search
    /// command line. Returns false when `input` isn't a recognisable search.
    fn seed_search_from_command(&mut self, input: &str) -> bool {
        let Some(sc) = crate::quickfix::parse_search_command(input) else {
            return false;
        };
        self.search.seed(
            sc.pattern.clone(),
            sc.include.unwrap_or_default(),
            sc.exclude.unwrap_or_default(),
        );
        self.search.opts.case_sensitive = sc.case_sensitive;
        self.search.opts.whole_word = sc.whole_word;
        self.search.opts.use_regex = sc.use_regex;
        self.set_sidebar_view(SidebarView::Search);
        self.submit_search_query();
        self.status = format!("Search seeded from terminal: {}", sc.pattern);
        true
    }

    /// Cmd/Ctrl+click on a printed `path:line[:col]` reference (compiler
    /// errors, test failures, grep hits, tracebacks) jumps the editor
    /// there. Relative paths resolve against the pane shell's live cwd,
    /// then the workspace root; `~` against $HOME. The click only lands
    /// when the resolved file exists, which also filters lookalikes such
    /// as `host.com:443`.
    fn terminal_file_click(&mut self, col: u16, row: u16) -> bool {
        let Some((text, c)) = self.terminal().line_text_at(col, row) else {
            return false;
        };
        let Some(fr) = crate::file_ref::file_ref_at(&text, c) else {
            return false;
        };
        let Some(abs) = self.resolve_pane_path(self.active_terminal, &fr.path) else {
            return false;
        };
        self.open_resolved_file_ref(&abs, fr.line, fr.column)
    }

    /// A path printed in pane `idx`, made absolute: `~` against $HOME, a
    /// relative path against the pane shell's live cwd, then the workspace
    /// root. Shared by the file-ref click and the captures ask.
    fn resolve_pane_path(&self, idx: usize, raw: &str) -> Option<std::path::PathBuf> {
        let path = std::path::PathBuf::from(raw);
        if let Some(rest) = raw.strip_prefix("~/") {
            return std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(rest));
        }
        if path.is_absolute() {
            return Some(path);
        }
        let cwd = self
            .terminals
            .get(idx)
            .and_then(|t| t.pid())
            .and_then(cwd_of_pid)
            .filter(|p| p.is_dir())
            .unwrap_or_else(|| self.workspace_root().to_path_buf());
        let joined = cwd.join(&path);
        Some(if joined.is_file() {
            joined
        } else {
            self.workspace_root().join(&path)
        })
    }

    /// CAPTURES: ask the resident Navigator about the selected captured line
    /// (#372). The line, the trigger that caught it, and the pane rows around
    /// it (redacted like any text that leaves a pane, #360) ride the ask. A
    /// `path:line` in the line opens that file first so the reply lands as
    /// a comment box at the referenced line; otherwise the ask is anchored
    /// on the active file, and with no file at all it says so.
    pub(crate) fn ask_navigator_about_capture(&mut self) {
        let Some(entry) = self.captures.selected_entry().cloned() else {
            self.status = String::from("No captured line is selected");
            return;
        };
        let Some(host) = &self.pair_host else {
            self.status =
                String::from("Navigator is not active (run croft pair in this workspace)");
            return;
        };
        if host.is_busy() {
            self.status = format!("{} is mid-turn; wait for it to finish", host.name());
            return;
        }
        let name = host.name().to_string();
        let idx = entry
            .shell_pid
            .and_then(|pid| {
                self.terminals
                    .iter()
                    .position(|t| t.shell_pid() == Some(pid))
            })
            .unwrap_or(self.active_terminal);
        // The rows around the line, if it is still in the scrollback; the
        // line alone otherwise.
        let needle: String = entry.line.trim_end().chars().take(60).collect();
        let context: Vec<String> = match self.terminals.get(idx) {
            Some(t) => match t.find_captured_line(&needle) {
                Some(line) => {
                    let (lines, top) = t.grid_lines();
                    let hit = usize::try_from(line - top).unwrap_or(0);
                    crate::widgets::captures::context_window(
                        &lines,
                        hit,
                        crate::widgets::captures::ASK_CONTEXT_ROWS,
                    )
                }
                None => vec![entry.line.clone()],
            },
            None => vec![entry.line.clone()],
        };
        // Anchor: the file the line names, else the active file.
        let referenced = crate::widgets::captures::first_file_ref(&entry.line)
            .and_then(|fr| self.resolve_pane_path(idx, &fr.path).map(|abs| (abs, fr)))
            .filter(|(abs, _)| abs.is_file());
        let opened = match referenced {
            Some((abs, fr)) => self.open_resolved_file_ref(&abs, fr.line, fr.column),
            None => false,
        };
        let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
        else {
            self.status = String::from(
                "Ask Navigator: the captured line names no workspace file and none is open",
            );
            return;
        };
        let row = self.editor.cursor_row;
        let range = (row, row);
        // Every part of the ask is masked here, the line and the trigger
        // message included: a capture is stored raw (#360).
        let triggers = self.triggers.clone();
        let (instruction, selection) =
            crate::widgets::captures::ask_prompt(&entry, &context, |t| {
                crate::triggers::mask_text(t, &triggers, false)
            });
        let content = self.editor.lines.join("\n");
        let Some(host) = &self.pair_host else {
            // Unreachable today (nothing above touches the host), but a
            // silent return would leave the jump's status reading as success.
            self.status = String::from("Navigator is not active");
            return;
        };
        match host.send_ask_turn(&file, range, &selection, &instruction, &content) {
            Ok(()) => {
                // Always name the anchor: when the line's own file did not
                // open, the ask went to the active file and the user must
                // see which.
                self.status = format!(
                    "Asked {name} about the captured line, anchored at {file}:{}{}",
                    row + 1,
                    if opened { "" } else { " (the active file)" }
                );
                self.pair_turn_origin = Some((file, row));
            }
            Err(e) => self.status = format!("Ask Navigator failed: {e}"),
        }
    }

    /// PROBLEMS: Fix with Navigator (#374). Opens the file at the diagnostic
    /// and sends the navigator an ask turn built from the diagnostic
    /// (message, source, position) with the server's quick fixes as
    /// `hints`, anchored on the diagnostic's line. The navigator's edit
    /// streams into the buffer under its caret exactly as any ask does, so
    /// every safety property of that path holds: visible, cancellable with
    /// `Cmd+K X` (which reverts the streamed text), never written to disk by
    /// the navigator. The row wears a spinner until the turn ends, and the
    /// server's next publish clears or updates it.
    ///
    /// With no navigator seated the action says so rather than doing
    /// nothing; the menu model has no disabled state (#372's shape).
    pub(crate) fn fix_problem_with_navigator(
        &mut self,
        path: PathBuf,
        item: crate::widgets::problems::ProblemItem,
        hints: Vec<String>,
    ) {
        let Some(host) = &self.pair_host else {
            self.status =
                String::from("Navigator is not active (run croft pair in this workspace)");
            return;
        };
        if host.is_busy() {
            self.status = format!("{} is mid-turn; wait for it to finish", host.name());
            return;
        }
        let name = host.name().to_string();
        // Land on the diagnostic first: the turn is anchored on the active
        // file, and the navigator's caret parks where the user is looking.
        let opened = if item.col_utf16 {
            self.open_at_utf16(&path, item.line, item.col)
        } else {
            self.open_at(&path, item.line as usize, item.col as usize)
        };
        if let Err(e) = opened {
            self.status = format!("Fix with Navigator: open failed: {e}");
            return;
        }
        let Some(file) = self
            .editor
            .path
            .as_ref()
            .and_then(|p| collab_file_key(&self.tree.root, p))
        else {
            self.status = String::from("Fix with Navigator: the file is outside the workspace");
            return;
        };
        let row = (item.line as usize).min(self.editor.lines.len().saturating_sub(1));
        let selection = self.editor.lines.get(row).cloned().unwrap_or_default();
        let instruction = crate::widgets::problems::fix_prompt(&item, &file, &hints);
        let content = self.editor.lines.join("\n");
        let Some(host) = &self.pair_host else {
            // Unreachable today (the open above does not touch the seat),
            // but a silent return would leave the jump's status as success.
            self.status = String::from("Navigator is not active");
            return;
        };
        match host.send_ask_turn(&file, (row, row), &selection, &instruction, &content) {
            Ok(()) => {
                let what: String = item
                    .message
                    .lines()
                    .next()
                    .unwrap_or("")
                    .chars()
                    .take(60)
                    .collect();
                self.status = format!(
                    "Asked {name} to fix {file}:{}: {what} (Cmd+K X cancels)",
                    row + 1
                );
                self.pair_turn_origin = Some((file, row));
                self.problems.fixing = Some((path, item.line));
                self.problems_fix_started = Some(std::time::Instant::now());
            }
            Err(e) => self.status = format!("Fix with Navigator failed: {e}"),
        }
    }

    /// The diagnostic under the caret in the active file, as a PROBLEMS
    /// item, for the `Cmd+.` and palette entry points of Fix with Navigator
    /// (#374). The first diagnostic covering the caret row wins; its source
    /// is recovered from the per-server store, since the editor's overlay
    /// does not carry it.
    pub(crate) fn navigator_fix_candidate(
        &self,
    ) -> Option<(PathBuf, crate::widgets::problems::ProblemItem)> {
        let path = self.editor.path.clone()?;
        let row = self.editor.cursor_row as u32;
        let d = self
            .editor
            .diagnostics_in_line_range(row, row)
            .into_iter()
            .next()?;
        let source = self
            .lsp_diagnostics
            .get(&path)
            .and_then(|by_server| {
                by_server.iter().find_map(|(server, diags)| {
                    diags
                        .iter()
                        .any(|x| {
                            x.start_line == d.start_line
                                && x.start_char == d.start_char
                                && x.message == d.message
                        })
                        .then(|| server.clone())
                })
            })
            .unwrap_or_default();
        Some((
            path,
            crate::widgets::problems::ProblemItem {
                line: d.start_line,
                col: d.start_char,
                col_utf16: true,
                severity: d.severity,
                message: d.message,
                source,
            },
        ))
    }

    /// Stop the PROBLEMS-row spinner: the fix turn ended, was cancelled, or
    /// the seat is gone (#374).
    fn clear_problem_fix(&mut self) {
        self.problems.fixing = None;
        self.problems_fix_started = None;
    }

    /// Monotonic phase while a Fix with Navigator turn streams, so the loop
    /// repaints its spinner; `0` otherwise, so it never wakes the renderer
    /// idle (the same contract as the update spinner).
    fn problems_fix_spinner_phase(&self) -> u128 {
        match self.problems_fix_started {
            Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
            None => 0,
        }
    }

    /// Jump the editor to an absolute `path:line[:col]`, recording where the
    /// user was so Back returns to it, exactly like go-to-definition. False
    /// when the file doesn't exist or won't open.
    fn open_resolved_file_ref(
        &mut self,
        abs: &std::path::Path,
        line: u32,
        column: Option<u32>,
    ) -> bool {
        self.open_resolved_file_ref_inner(abs, line, column, true)
    }

    /// [`Self::open_resolved_file_ref`], but `record_nav` false skips the jump
    /// history. A side-by-side open is ONE jump for the user even though it
    /// opens two files, so it records the origin itself and opens both halves
    /// without recording (otherwise the first Back lands on the left half).
    fn open_resolved_file_ref_inner(
        &mut self,
        abs: &std::path::Path,
        line: u32,
        column: Option<u32>,
        record_nav: bool,
    ) -> bool {
        if !abs.is_file() {
            return false;
        }
        if record_nav && let Some(from) = self.editor.path.clone() {
            self.nav.record(NavLoc {
                path: from,
                row: self.editor.cursor_row,
                col: self.editor.cursor_col,
            });
        }
        let line0 = (line as usize).saturating_sub(1);
        let col0 = column.map(|c| c as usize).unwrap_or(1).saturating_sub(1);
        match self.open_at(abs, line0, col0) {
            Ok(()) => {
                // `explorer.autoReveal` analogue, as quick-open does: sync
                // the tree to the landed file without stealing editor focus.
                self.tree.reveal_path(abs);
                self.status = format!("{}:{}", self.status_path(abs), line);
                true
            }
            Err(_) => false,
        }
    }

    /// Open a `diff://` group link's two files side by side: left lands in
    /// the leftmost editor group, right in the rightmost — splitting first
    /// when the editor is a single group, reusing the existing pair when it
    /// is already split (so repeated clicks swap the comparison in place
    /// instead of accreting columns).
    fn open_side_by_side(
        &mut self,
        left: &crate::file_ref::FileRef,
        right: &crate::file_ref::FileRef,
    ) -> bool {
        // Both sides absolute by construction (diff_uri refuses relative
        // paths); gated on is_file like every terminal file click.
        let lp = std::path::PathBuf::from(&left.path);
        let rp = std::path::PathBuf::from(&right.path);
        if !lp.is_file() || !rp.is_file() {
            return false;
        }
        // One click, one Back entry: record the origin once here, then open
        // both halves with recording off.
        if let Some(from) = self.editor.path.clone() {
            self.nav.record(NavLoc {
                path: from,
                row: self.editor.cursor_row,
                col: self.editor.cursor_col,
            });
        }
        self.focus_editor_group(true);
        if !self.open_resolved_file_ref_inner(&lp, left.line, left.column, false) {
            return false;
        }
        if self.editor_layout.is_split() {
            self.focus_editor_group(false);
        } else {
            // The split duplicates the left file into the new focused group
            // as a preview tab; opening the right file swaps into it.
            self.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
        }
        if !self.open_resolved_file_ref_inner(&rp, right.line, right.column, false) {
            return false;
        }
        self.status = format!(
            "Side by side: {} | {}",
            self.status_path(&lp),
            self.status_path(&rp)
        );
        true
    }

    /// Open a URL discovered in the terminal. On a remote session a loopback
    /// dev-server URL is forwarded home and opened; any other link opens on the
    /// local Mac through the drop relay (with the usual confirm gate). On a
    /// local session everything opens directly.
    ///
    /// Editor deep links (`vscode://file/…:line`, and the same shape from
    /// Cursor/Windsurf/Zed, plus plain `file://`) name a file and line, and
    /// Croft is an editor: they open in the editor pane right here, never
    /// through the OS. Beyond those, web links only: an OSC 8 cell carries
    /// whatever URI the printing program chose while showing unrelated text,
    /// so any other custom-scheme URI would hand `open`/`xdg-open` an
    /// arbitrary target (app launch, protocol handler) off one disguised
    /// click. The refusal surfaces the real destination in the status line.
    fn open_detected_url(&mut self, url: &str) {
        // A diff:// group link names two files; open them side by side.
        // Same trust story as single-file deep links: consumed internally,
        // gated on is_file, never handed to the OS.
        if let Some((left, right)) = crate::file_ref::diff_uri(url)
            && self.open_side_by_side(&left, &right)
        {
            return;
        }
        if let Some(fr) = crate::file_ref::editor_file_uri(url) {
            // Absolute by construction; gated on is_file like every terminal
            // file click. An unresolvable link falls through to the web-only
            // rule so its refusal still shows the real URI.
            let path = std::path::PathBuf::from(&fr.path);
            if self.open_resolved_file_ref(&path, fr.line, fr.column) {
                return;
            }
        }
        let scheme_ok = {
            let l = url.trim_start().to_ascii_lowercase();
            l.starts_with("http://") || l.starts_with("https://")
        };
        if !scheme_ok {
            self.status = format!("Refused to open non-web link: {url}");
            return;
        }
        let loopback = crate::port_detect::loopback_url_port(url);
        if self.drop_relay_active() {
            if let Some(port) = loopback {
                self.request_remote_forward(port, true);
            } else if self.trust_local_browser {
                self.request_remote_url_open(url.to_string());
                self.status = format!("Opening {url} on your local Mac");
            } else {
                self.pending_local_open = Some(url.to_string());
            }
            return;
        }
        match open_url(url) {
            Ok(()) => self.status = format!("Opened {url}"),
            Err(e) => self.status = format!("Open link failed: {e}"),
        }
    }

    /// Click on a port-detection toast button. Returns whether a button was hit
    /// (and the action taken); a click elsewhere returns false so it falls
    /// through to normal handling.
    fn handle_port_toast_click(&mut self, x: u16, y: u16) -> bool {
        let Some(toast) = self.port_toast.as_ref() else {
            return false;
        };
        let Some(action) = toast
            .buttons
            .iter()
            .find(|(r, _)| rect_contains(*r, x, y))
            .map(|(_, a)| *a)
        else {
            return false;
        };
        let port = toast.port;
        self.port_toast = None;
        match action {
            PortToastAction::ForwardAndOpen => self.request_remote_forward(port, true),
            PortToastAction::ForwardOnly => self.request_remote_forward(port, false),
            PortToastAction::Open => match open_url(&format!("http://127.0.0.1:{port}/")) {
                Ok(()) => self.status = format!("Opened http://localhost:{port}/"),
                Err(e) => self.status = format!("Open failed: {e}"),
            },
            PortToastAction::Dismiss => {}
        }
        true
    }

    /// A relay request id: the kind, this process, and a per-process counter.
    /// The relay keys its remote inbox directory by this id, so two requests
    /// raised in the same instant must not share one — the first reply would
    /// satisfy both pending pulls and delete the directory out from under the
    /// second, which then times out with its tunnel already up.
    fn relay_request_id(kind: &str) -> String {
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        format!("{kind}-{}-{n}", std::process::id())
    }

    /// Ask the local launcher (via the drop relay) to forward `port` home over
    /// the live SSH master, optionally opening the local browser once it's up.
    fn request_remote_forward(&mut self, port: u16, open: bool) {
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Forward port: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("forward");
        let line = format!("forward\t{request_id}\t{port}\t{}\n", u8::from(open));
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: format!("port {port}"),
                    basename: String::new(),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Forward { remote_port: port },
                });
                self.status = format!("Forwarding port {port}…");
            }
            Err(e) => self.status = format!("Forward port: relay write failed: {e}"),
        }
    }

    /// Tear down a previously established forward. Fire and forget — the entry
    /// is already gone from the panel, so there's no completion to await.
    fn request_remote_unforward(&mut self, local: u16, remote: u16) {
        let Some(log_path) = self.relay_log_path() else {
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("unforward");
        let line = format!("unforward\t{request_id}\t{local}\t{remote}\n");
        let _ = append_to_relay_log(&log_path, &line);
    }

    fn request_remote_url_open(&mut self, url: String) {
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Open link: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("open");
        let mut line = String::from("open\t");
        line.push_str(&request_id);
        line.push('\t');
        line.push_str(&url);
        line.push('\n');
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: url,
                    basename: String::new(),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Open,
                });
            }
            Err(e) => {
                self.status = format!("Open link: relay write failed: {e}");
            }
        }
    }

    /// Handle a key while the local-browser confirmation modal is open.
    /// `Y`/`Enter` opens this URL once. `A` opens it AND remembers
    /// "always" for the rest of the session. `N`/`Esc` cancels.
    fn handle_local_open_confirm_key(&mut self, key: KeyEvent) {
        let Some(url) = self.pending_local_open.clone() else {
            return;
        };
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                self.pending_local_open = None;
                self.request_remote_url_open(url.clone());
                self.status = format!("Opening {url} on your local Mac");
            }
            KeyCode::Char('a') | KeyCode::Char('A') => {
                self.pending_local_open = None;
                self.trust_local_browser = true;
                self.request_remote_url_open(url.clone());
                self.status = format!("Trusted local browser for this session. Opening {url}");
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                self.pending_local_open = None;
                self.status = String::from("Open link cancelled");
            }
            _ => {}
        }
    }

    fn open_shortcuts_modal(&mut self) {
        if self.shortcuts_modal.is_none() {
            self.shortcuts_modal = Some(crate::widgets::shortcuts::ShortcutsModal::default());
            self.overlays.shortcuts_clear.request();
            self.status = String::from("Shortcuts: Esc to close");
        }
    }

    fn close_shortcuts_modal(&mut self) {
        if self.shortcuts_modal.take().is_some() {
            self.overlays.shortcuts_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    pub fn consume_shortcuts_image_clear(&mut self) -> bool {
        self.overlays.shortcuts_clear.consume()
    }

    pub fn consume_file_finder_image_clear(&mut self) -> bool {
        self.overlays.file_finder_clear.consume()
    }

    /// Drain the background-build receiver into `file_finder_index`
    /// without blocking. Called from `open_file_finder` and from the
    /// main loop tick. Accepts REPLACEMENT results too: when the FS
    /// watcher or a workspace re-root has triggered a rebuild, the
    /// fresh index swaps in here and is pushed into the open finder
    /// (if any) so an in-progress Cmd+P session immediately re-ranks
    /// against the new file set. If a follow-up rebuild was queued
    /// while this one was in flight (the `file_finder_index_dirty`
    /// flag), it is re-kicked here so a long-running build on a
    /// multi-GB monorepo can never miss a later FS event.
    fn poll_file_finder_index(&mut self) {
        let Some(rx) = self.file_finder_index_rx.as_ref() else {
            return;
        };
        match rx.try_recv() {
            Ok(entries) => {
                let arc = std::sync::Arc::new(entries);
                self.file_finder_index = Some(arc.clone());
                self.file_finder_index_rx = None;
                if let Some(finder) = self.file_finder.as_mut() {
                    finder.replace_entries(arc);
                }
                if self.file_finder_index_dirty {
                    self.kick_file_finder_index_rebuild();
                }
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => {}
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.file_finder_index_rx = None;
            }
        }
    }

    /// Spawn a background walker that rebuilds the Cmd+P file index
    /// against the current `workspace_root`. If a rebuild is already
    /// in flight, sets the dirty flag instead; `poll_file_finder_index`
    /// will re-kick on completion. Called from `change_workspace_root`
    /// so Cmd+P reflects the new project, and from `drain_fs_events`
    /// so creates, deletes, and git-checkout-driven swaps land in the
    /// index without a croft restart.
    fn kick_file_finder_index_rebuild(&mut self) {
        if self.file_finder_index_rx.is_some() {
            self.file_finder_index_dirty = true;
            return;
        }
        let (tx, rx) = std::sync::mpsc::channel::<Vec<crate::widgets::file_finder::FileEntry>>();
        let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
        std::thread::spawn(move || {
            let entries = crate::widgets::file_finder::build_multi_file_index(&roots);
            let _ = tx.send(entries);
        });
        self.file_finder_index_rx = Some(rx);
        self.file_finder_index_dirty = false;
    }

    fn open_file_finder(&mut self) {
        if self.file_finder.is_some() {
            return;
        }
        // Drain the background-built index if it has landed.
        self.poll_file_finder_index();
        // Fallback: the worker thread has not finished yet AND no
        // index has ever been cached. Walk synchronously this once
        // rather than open an empty finder; this only fires when
        // Cmd+P is pressed within the first few hundred ms of launch.
        if self.file_finder_index.is_none() {
            let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
            let entries = crate::widgets::file_finder::build_multi_file_index(&roots);
            self.file_finder_index = Some(std::sync::Arc::new(entries));
            self.file_finder_index_rx = None;
        }
        let entries = self
            .file_finder_index
            .clone()
            .unwrap_or_else(|| std::sync::Arc::new(Vec::new()));
        let count = entries.len();
        self.file_finder = Some(crate::widgets::file_finder::FileFinder::new(entries));
        self.overlays.file_finder_clear.request();
        self.status = format!("Go to File: {count} files indexed — Esc to close");
    }

    fn close_file_finder(&mut self) {
        if self.file_finder.take().is_some() {
            self.overlays.file_finder_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    fn handle_file_finder_key(&mut self, key: KeyEvent) {
        // Cmd+V / Ctrl+V: paste the system clipboard into the query as if
        // each character had been typed. Hosts that route Cmd+V through
        // bracketed paste (iTerm2 default) deliver an `Event::Paste(s)`
        // instead, which `handle_paste` forwards to the finder — but if
        // the user re-bound Cmd+V to a CSI-u Cmd+V sequence or is running
        // in a terminal that disables bracketed paste, the chord arrives
        // here as a key event, and reading the clipboard ourselves keeps
        // the "open finder, paste a filename" gesture working everywhere.
        if is_clipboard_paste_key(key) {
            if let Some(text) = (self.clipboard_reader)()
                && let Some(finder) = self.file_finder.as_mut()
            {
                for c in text.chars() {
                    if !c.is_control() {
                        finder.push_char(c);
                    }
                }
            }
            return;
        }
        let Some(finder) = self.file_finder.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => {
                self.close_file_finder();
            }
            (KeyCode::Enter, _) => self.open_file_finder_selection(),
            (KeyCode::Up, _) => finder.select_prev(),
            (KeyCode::Down, _) => finder.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    finder.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    finder.select_next();
                }
            }
            (KeyCode::Left, _) => finder.move_cursor_left(),
            (KeyCode::Right, _) => finder.move_cursor_right(),
            (KeyCode::Home, _) => finder.move_cursor_home(),
            (KeyCode::End, _) => finder.move_cursor_end(),
            (KeyCode::Backspace, _) => finder.pop_char(),
            (KeyCode::Delete, _) => finder.delete_char(),
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                finder.push_char(c);
            }
            _ => {}
        }
        // VS Code's shared quick input: a leading `#` turns Quick Open into
        // Go to Symbol in Workspace, carrying any text after it as the query.
        let hash_query = self
            .file_finder
            .as_ref()
            .and_then(|f| f.query.strip_prefix('#'))
            .map(str::to_string);
        if let Some(q) = hash_query {
            self.close_file_finder();
            self.open_workspace_symbols(&q);
        }
    }

    /// Open the highlighted result and dismiss the finder: Enter's action,
    /// shared with a mouse click on a result row.
    fn open_file_finder_selection(&mut self) {
        let Some(finder) = self.file_finder.as_ref() else {
            return;
        };
        let path = finder.selected_entry().map(|e| e.path.clone());
        let hint = finder.line_hint();
        if let Some(path) = path {
            self.close_file_finder();
            // `alpha:236-239` (#472): land on the line, centred, and select
            // the range so it reads as highlighted; `alpha:236` lands with
            // nothing selected, since one line is a place, not a span.
            let opened = match hint {
                Some(hint) => {
                    let row = hint.line.saturating_sub(1);
                    let col = hint.col.map_or(0, |c| c.saturating_sub(1));
                    self.open_at(&path, row, col)
                }
                None => self.editor.open_preview(&path),
            };
            match opened {
                Ok(()) => {
                    self.sync_open_file_poll_mtime();
                    // A range an earlier hinted pick installed is cleared if
                    // it is still the selection in its tab, so neither
                    // `alpha:12` nor a bare `alpha` keeps showing it; a
                    // selection the user made or extended since is theirs
                    // and stays. Stale secondary carets never survive a
                    // pick, as they never survive a click: the next
                    // keystroke would edit at every one of them.
                    if let Some((prev, sel)) = self.quick_open_range.take()
                        && let Some(idx) = self.editor.find_tab_with_path(&prev)
                        && self.editor.editors[idx].selection == Some(sel)
                    {
                        self.editor.editors[idx].selection = None;
                    }
                    if hint.is_some() {
                        self.editor.clear_selection();
                    }
                    self.editor.collapse_carets();
                    if let Some(end) = hint.and_then(|h| h.end) {
                        let start = self.editor.cursor_row;
                        let last = self.editor.lines.len().saturating_sub(1);
                        let end_row = end.saturating_sub(1).clamp(start, last);
                        let end_col = self
                            .editor
                            .lines
                            .get(end_row)
                            .map_or(0, |l| l.chars().count());
                        let sel = crate::widgets::editor::EditorSelection {
                            anchor: (end_row, end_col),
                            head: (start, 0),
                        };
                        self.editor.selection = Some(sel);
                        self.quick_open_range = Some((path.to_path_buf(), sel));
                        // The landing line is the head, and the cursor sits at
                        // the head as every other selection-installing path
                        // leaves it: Shift+motion extends from the cursor, and
                        // the paint-time clamp keeps the cursor on screen, so
                        // a range taller than the viewport still shows the
                        // line the user asked for, centred by `open_at`, with
                        // the selection running down from it.
                        self.editor.cursor_row = start;
                        self.editor.cursor_col = 0;
                    }
                    // VS Code's `explorer.autoReveal` analogue:
                    // expand every parent dir of the picked file
                    // and park the cursor on its row so the user
                    // sees where in the workspace the file lives.
                    self.tree.reveal_path(&path);
                    self.focus_pane(Pane::Editor);
                    // The status names the lines landed on: a number past the
                    // file (or one that saturated in the parser) was clamped
                    // above, and the clamped truth is the useful signal.
                    let last_line = self.editor.lines.len().max(1);
                    self.status = match hint {
                        Some(hint) => match hint.end {
                            Some(end) => format!(
                                "Opened {}:{}-{}",
                                self.status_path(&path),
                                hint.line.min(last_line),
                                end.min(last_line)
                            ),
                            None => format!(
                                "Opened {}:{}",
                                self.status_path(&path),
                                hint.line.min(last_line)
                            ),
                        },
                        None => format!("Opened {}", self.status_path(&path)),
                    };
                }
                Err(e) => {
                    self.status = format!("Open failed: {e}");
                }
            }
        }
    }

    fn handle_file_finder_mouse(&mut self, m: MouseEvent) {
        let Some(finder) = self.file_finder.as_mut() else {
            return;
        };
        let inside = rect_contains(finder.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    finder.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    finder.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_file_finder();
            }
            // Click a row to open it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = finder.row_index_at(m.row) {
                    finder.selected = idx;
                    self.open_file_finder_selection();
                }
            }
            _ => {}
        }
    }

    fn render_file_finder(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let center = self.quick_input_position == QuickInputPosition::Center;
        let Some(finder) = self.file_finder.as_mut() else {
            return;
        };
        let area = frame.area();
        crate::widgets::file_finder::render_file_finder(
            finder,
            area,
            frame.buffer_mut(),
            theme,
            center,
        );
    }

    pub fn consume_command_palette_image_clear(&mut self) -> bool {
        self.overlays.command_palette_clear.consume()
    }

    /// Open the Command Palette (Cmd/Ctrl+Shift+P). The palette is built from
    /// the static command registry, so there is nothing to index — it opens
    /// instantly regardless of workspace size.
    fn open_command_palette(&mut self) {
        if self.command_palette.is_some() {
            return;
        }
        let mut palette = crate::widgets::command_palette::CommandPalette::new();
        // Inject the commands contributed by enabled MCP sidecar extensions so
        // they're discoverable alongside the built-ins (eager registration; the
        // server is only spawned when one is actually invoked).
        let ext_commands: Vec<crate::widgets::command_palette::ExtensionCommand> =
            crate::mcp::registry::contributed_commands()
                .into_iter()
                .chain(crate::mcp::registry::contributed_viewer_commands_in_dir(
                    &self.config_dir,
                ))
                .map(|c| crate::widgets::command_palette::ExtensionCommand {
                    ext_id: c.ext_id,
                    id: c.id,
                    title: c.title,
                })
                .collect();
        palette.set_extension_commands(ext_commands);
        let count = palette.results.len();
        self.command_palette = Some(palette);
        self.overlays.command_palette_clear.request();
        self.status = format!("Command Palette: {count} commands — Esc to close");
    }

    fn close_command_palette(&mut self) {
        if self.command_palette.take().is_some() {
            self.overlays.command_palette_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    fn handle_command_palette_key(&mut self, key: KeyEvent) {
        let Some(palette) = self.command_palette.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_command_palette(),
            (KeyCode::Enter, _) => self.run_command_palette_selection(),
            (KeyCode::Up, _) => palette.select_prev(),
            (KeyCode::Down, _) => palette.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    palette.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    palette.select_next();
                }
            }
            (KeyCode::Left, _) => palette.move_cursor_left(),
            (KeyCode::Right, _) => palette.move_cursor_right(),
            (KeyCode::Home, _) => palette.move_cursor_home(),
            (KeyCode::End, _) => palette.move_cursor_end(),
            (KeyCode::Backspace, _) => palette.pop_char(),
            (KeyCode::Delete, _) => palette.delete_char(),
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                palette.push_char(c);
            }
            _ => {}
        }
    }

    /// Run the highlighted command and dismiss the palette: Enter's action,
    /// shared with a mouse click on a result row.
    fn run_command_palette_selection(&mut self) {
        let Some(palette) = self.command_palette.as_ref() else {
            return;
        };
        let item = palette.selected_item();
        self.close_command_palette();
        if let Some(item) = item {
            self.run_palette_item(item);
        }
    }

    fn handle_command_palette_mouse(&mut self, m: MouseEvent) {
        let Some(palette) = self.command_palette.as_mut() else {
            return;
        };
        let inside = rect_contains(palette.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    palette.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    palette.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_command_palette();
            }
            // Click a row to run it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = palette.row_index_at(m.row) {
                    palette.selected = idx;
                    self.run_command_palette_selection();
                }
            }
            _ => {}
        }
    }

    fn render_command_palette(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let center = self.quick_input_position == QuickInputPosition::Center;
        let Some(palette) = self.command_palette.as_mut() else {
            return;
        };
        let area = frame.area();
        crate::widgets::command_palette::render_command_palette(
            palette,
            area,
            frame.buffer_mut(),
            theme,
            center,
        );
    }

    /// Open "Go to Symbol in Editor" (Cmd/Ctrl+Shift+O). Snapshots the active
    /// file's symbols from the outline (tree-sitter is populated synchronously
    /// each tick; LSP refines it). A leading `:` in the query switches to Go to
    /// Line. ponytail: snapshot at open — symbols are present for any synced
    /// file; if a slow LSP reply ever needs to land into an open picker, feed
    /// it live from `drain_lsp_document_symbols`.
    fn open_go_to_symbol(&mut self) {
        if self.go_to_symbol.is_some() {
            return;
        }
        let Some(path) = self.editor.path.clone() else {
            self.status = String::from("Go to Symbol: no file open");
            return;
        };
        let symbols = self.outline.symbols().to_vec();
        let count = symbols.len();
        self.go_to_symbol = Some(crate::widgets::symbol_picker::SymbolPicker::new(
            path, symbols,
        ));
        self.overlays.command_palette_clear.request();
        self.status = format!("Go to Symbol: {count} symbols — Esc to close");
    }

    fn close_go_to_symbol(&mut self) {
        if self.go_to_symbol.take().is_some() {
            self.overlays.command_palette_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    fn handle_go_to_symbol_key(&mut self, key: KeyEvent) {
        let Some(picker) = self.go_to_symbol.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_go_to_symbol(),
            (KeyCode::Enter, _) => {
                if picker.is_line_mode() {
                    // Resolve the target before closing (close drops the picker).
                    let target = picker.line_target().map(|n| (n as u32 - 1, 0));
                    let path = picker.path.clone();
                    self.close_go_to_symbol();
                    if let Some((line, col)) = target {
                        self.go_to_definition(path, line, col);
                    }
                } else {
                    self.jump_to_go_to_symbol_selection();
                }
            }
            (KeyCode::Up, _) => picker.select_prev(),
            (KeyCode::Down, _) => picker.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    picker.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    picker.select_next();
                }
            }
            (KeyCode::Left, _) => picker.move_cursor_left(),
            (KeyCode::Right, _) => picker.move_cursor_right(),
            (KeyCode::Home, _) => picker.move_cursor_home(),
            (KeyCode::End, _) => picker.move_cursor_end(),
            (KeyCode::Backspace, _) => picker.pop_char(),
            (KeyCode::Delete, _) => picker.delete_char(),
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                picker.push_char(c);
            }
            _ => {}
        }
    }

    /// Jump to the highlighted symbol and dismiss the picker: Enter's action
    /// outside line mode, shared with a mouse click on a result row (a click
    /// names a concrete row, so it always means the symbol, never a `:N`
    /// line query).
    fn jump_to_go_to_symbol_selection(&mut self) {
        let Some(picker) = self.go_to_symbol.as_ref() else {
            return;
        };
        // Resolve the target before closing (close drops the picker).
        let target = picker.selected_target();
        let path = picker.path.clone();
        self.close_go_to_symbol();
        if let Some((line, col)) = target {
            self.go_to_definition(path, line, col);
        }
    }

    fn handle_go_to_symbol_mouse(&mut self, m: MouseEvent) {
        let Some(picker) = self.go_to_symbol.as_mut() else {
            return;
        };
        let inside = rect_contains(picker.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    picker.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    picker.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_go_to_symbol();
            }
            // Click a row to jump to it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = picker.row_index_at(m.row) {
                    picker.selected = idx;
                    self.jump_to_go_to_symbol_selection();
                }
            }
            _ => {}
        }
    }

    fn render_go_to_symbol(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let center = self.quick_input_position == QuickInputPosition::Center;
        let Some(picker) = self.go_to_symbol.as_mut() else {
            return;
        };
        let area = frame.area();
        crate::widgets::symbol_picker::render_symbol_picker(
            picker,
            area,
            frame.buffer_mut(),
            theme,
            center,
        );
    }

    /// Open "Go to Symbol in Workspace" seeded with `initial` (the text
    /// after Quick Open's `#`). The query goes to every running language
    /// server; results stream in via [`Self::drain_lsp_workspace_symbols`].
    fn open_workspace_symbols(&mut self, initial: &str) {
        if self.workspace_symbols.is_some() {
            return;
        }
        self.workspace_symbols = Some(
            crate::widgets::workspace_symbols::WorkspaceSymbolPicker::new(
                self.tree.root.clone(),
                initial,
            ),
        );
        self.overlays.command_palette_clear.request();
        self.workspace_symbols_requery();
        self.status = String::from("Go to Symbol in Workspace: type to search — Esc to close");
    }

    fn close_workspace_symbols(&mut self) {
        if self.workspace_symbols.take().is_some() {
            self.ws_symbols_request_id = None;
            self.ws_symbols_pending = None;
            self.overlays.command_palette_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    /// Note a query change and arm the debounce; the actual LSP request
    /// fires from [`Self::workspace_symbols_dispatch_due`] once the query
    /// has been still for the window. Firing per keystroke serialized a
    /// round trip per character behind the per-client lock, starving every
    /// other LSP feature on that server for the whole burst.
    fn workspace_symbols_requery(&mut self) {
        let Some(picker) = self.workspace_symbols.as_mut() else {
            return;
        };
        let query = picker.query.trim().to_string();
        if query.is_empty() {
            picker.set_results(Vec::new());
            // A stale notice from the previous reply reads as an error;
            // an empty query should show the type-to-search hint.
            picker.unsupported = false;
            self.ws_symbols_request_id = None;
            self.ws_symbols_pending = None;
            return;
        }
        picker.loading = true;
        // Invalidate any in-flight request: its reply answers a query the
        // user has typed past and would render stale results until the
        // debounced request lands.
        self.ws_symbols_request_id = None;
        self.ws_symbols_pending = Some(std::time::Instant::now());
    }

    /// Debounced dispatch for [`Self::workspace_symbols_requery`]: called
    /// each tick from the drain loop, sends the newest query once it has
    /// been still for the window. Only the newest reply applies via
    /// `ws_symbols_request_id`.
    fn workspace_symbols_dispatch_due(&mut self) {
        const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(200);
        let Some(armed) = self.ws_symbols_pending else {
            return;
        };
        if armed.elapsed() < DEBOUNCE {
            return;
        }
        self.ws_symbols_pending = None;
        let Some(picker) = self.workspace_symbols.as_mut() else {
            return;
        };
        let query = picker.query.trim().to_string();
        if query.is_empty() {
            return;
        }
        let Some(lsp) = self.lsp.as_mut() else {
            if let Some(p) = self.workspace_symbols.as_mut() {
                p.loading = false;
                p.unsupported = true;
            }
            return;
        };
        self.ws_symbols_request_id = Some(lsp.request_workspace_symbols(query));
    }

    /// Install a `workspace/symbol` reply into the open picker. Only the
    /// newest request's reply applies; anything else is a stale answer to a
    /// query the user has already typed past. Returns true when applied.
    pub fn apply_workspace_symbols(
        &mut self,
        request_id: u64,
        symbols: Vec<crate::lsp::manager::WorkspaceSymbolItem>,
        unsupported: bool,
    ) -> bool {
        if self.ws_symbols_request_id != Some(request_id) {
            return false;
        }
        self.ws_symbols_request_id = None;
        let Some(picker) = self.workspace_symbols.as_mut() else {
            return false;
        };
        picker.unsupported = unsupported;
        picker.set_results(symbols);
        true
    }

    pub fn drain_lsp_workspace_symbols(&mut self) -> bool {
        let mut results = Vec::new();
        if let Some(lsp) = self.lsp.as_ref() {
            while let Some(r) = lsp.drain_workspace_symbols() {
                results.push(r);
            }
        }
        let mut changed = false;
        for r in results {
            changed |= self.apply_workspace_symbols(r.request_id, r.symbols, r.unsupported);
        }
        changed
    }

    fn handle_workspace_symbols_key(&mut self, key: KeyEvent) {
        let Some(picker) = self.workspace_symbols.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_workspace_symbols(),
            (KeyCode::Enter, _) => self.jump_to_workspace_symbol_selection(),
            (KeyCode::Up, _) => picker.select_prev(),
            (KeyCode::Down, _) => picker.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    picker.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    picker.select_next();
                }
            }
            (KeyCode::Left, _) => picker.move_cursor_left(),
            (KeyCode::Right, _) => picker.move_cursor_right(),
            (KeyCode::Home, _) => picker.move_cursor_home(),
            (KeyCode::End, _) => picker.move_cursor_end(),
            (KeyCode::Backspace, _) => {
                picker.pop_char();
                self.workspace_symbols_requery();
            }
            (KeyCode::Delete, _) => {
                picker.delete_char();
                self.workspace_symbols_requery();
            }
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                picker.push_char(c);
                self.workspace_symbols_requery();
            }
            _ => {}
        }
    }

    /// Jump to the highlighted workspace symbol and dismiss the picker:
    /// Enter's action, shared with a mouse click on a result row.
    fn jump_to_workspace_symbol_selection(&mut self) {
        let Some(picker) = self.workspace_symbols.as_ref() else {
            return;
        };
        let target = picker
            .selected_item()
            .map(|i| (i.path.clone(), i.line, i.character));
        self.close_workspace_symbols();
        if let Some((path, line, character)) = target {
            self.go_to_definition(path, line, character);
        }
    }

    fn handle_workspace_symbols_mouse(&mut self, m: MouseEvent) {
        let Some(picker) = self.workspace_symbols.as_mut() else {
            return;
        };
        let inside = rect_contains(picker.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    picker.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    picker.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_workspace_symbols();
            }
            // Click a row to jump to it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = picker.row_index_at(m.row) {
                    picker.selected = idx;
                    self.jump_to_workspace_symbol_selection();
                }
            }
            _ => {}
        }
    }

    fn render_workspace_symbols(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let center = self.quick_input_position == QuickInputPosition::Center;
        let Some(picker) = self.workspace_symbols.as_mut() else {
            return;
        };
        let area = frame.area();
        crate::widgets::workspace_symbols::render_workspace_symbols(
            picker,
            area,
            frame.buffer_mut(),
            theme,
            center,
        );
    }

    pub fn consume_process_picker_image_clear(&mut self) -> bool {
        self.overlays.process_picker_clear.consume()
    }

    /// Open the "Debug: Attach to Python Process" picker. Enumerates running
    /// CPython 3.14+ processes (those with PEP 768 `sys.remote_exec`); shows a
    /// status message and opens nothing when there are none.
    fn open_attach_python_picker(&mut self) {
        if self.process_picker.is_some() {
            return;
        }
        let targets = crate::dap::discovery::attachable_python_targets();
        if targets.is_empty() {
            self.run_debug.feedback = Some(String::from(
                "No attachable Python 3.14+ processes found (PEP 768 needs CPython 3.14+)",
            ));
            self.run_debug.feedback_is_error = true;
            self.status = String::from("Attach: no Python 3.14+ processes running");
            return;
        }
        let count = targets.len();
        self.process_picker = Some(crate::widgets::process_picker::ProcessPicker::new(targets));
        self.overlays.process_picker_clear.request();
        self.status = format!("Attach: {count} Python process(es) — Esc to close, Enter to attach");
    }

    fn close_process_picker(&mut self) {
        if self.process_picker.take().is_some() {
            self.overlays.process_picker_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    fn handle_process_picker_key(&mut self, key: KeyEvent) {
        let Some(picker) = self.process_picker.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_process_picker(),
            (KeyCode::Enter, _) => self.attach_process_picker_selection(),
            (KeyCode::Up, _) => picker.select_prev(),
            (KeyCode::Down, _) => picker.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    picker.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    picker.select_next();
                }
            }
            _ => {}
        }
    }

    /// Attach to the highlighted process and dismiss the picker: Enter's
    /// action, shared with a mouse click on a result row.
    fn attach_process_picker_selection(&mut self) {
        let Some(picker) = self.process_picker.as_ref() else {
            return;
        };
        let target = picker.selected_target().cloned();
        self.close_process_picker();
        if let Some(target) = target {
            self.attach_to_python_target(target);
        }
    }

    fn handle_process_picker_mouse(&mut self, m: MouseEvent) {
        let Some(picker) = self.process_picker.as_mut() else {
            return;
        };
        let inside = rect_contains(picker.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    picker.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    picker.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_process_picker();
            }
            // Click a row to attach to it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = picker.row_index_at(m.row) {
                    picker.selected = idx;
                    self.attach_process_picker_selection();
                }
            }
            _ => {}
        }
    }

    fn render_process_picker(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let Some(picker) = self.process_picker.as_mut() else {
            return;
        };
        let area = frame.area();
        crate::widgets::process_picker::render_process_picker(
            picker,
            area,
            frame.buffer_mut(),
            theme,
        );
    }

    /// Spawn `pdb -p <pid>` for the chosen target in a new PTY terminal,
    /// wrapping in `sudo` when the platform requires elevation (always on
    /// macOS; on Linux unless Yama `ptrace_scope` is relaxed). The PTY hosts
    /// both the interactive pdb prompt and any `sudo` password prompt — the
    /// edge a GUI debugger lacks.
    fn attach_to_python_target(&mut self, target: crate::dap::discovery::PyTarget) {
        use crate::dap::remote_attach::{Platform, plan_attach, read_yama_ptrace_scope};
        let pid = target.pid;
        let plan = match plan_attach(
            target.version,
            target.exe,
            pid,
            Platform::current(),
            read_yama_ptrace_scope(),
        ) {
            Ok(plan) => plan,
            Err(e) => {
                self.run_debug.feedback = Some(format!("Cannot attach to PID {pid}: {e:?}"));
                self.run_debug.feedback_is_error = true;
                return;
            }
        };
        let (program, args) = plan.command_line();
        match PtyTerminal::new_running(&program, &args, self.workspace_root()) {
            Ok(term) => {
                let slot = self.active_terminal + 1;
                self.terminals.insert(slot, term);
                self.active_terminal = slot;
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.focus_pane(Pane::Terminal);
                self.run_debug.feedback = Some(format!("Attaching debugger to PID {pid}"));
                self.run_debug.feedback_is_error = false;
            }
            Err(e) => {
                self.run_debug.feedback = Some(format!("Failed to spawn terminal: {e}"));
                self.run_debug.feedback_is_error = true;
            }
        }
    }

    /// Open `path` in an extension-contributed viewer (#465): a new terminal
    /// pane running the tool on the file, focused. `{file}` in the declared
    /// args is the file's path. A provisioned tool that is not installed yet
    /// has its managed install kicked off and the user is told to run the
    /// command again once it lands, the way a sidecar's first run behaves.
    pub fn open_in_viewer(
        &mut self,
        viewer: &crate::mcp::registry::ContributedViewer,
        path: &Path,
    ) {
        // The pane spawn takes `String` args, so a name that is not valid
        // UTF-8 could only be handed over mangled, and the tool would open a
        // different path. Refuse with the reason rather than open the wrong
        // file.
        let Some(file) = path.to_str().map(str::to_owned) else {
            self.status = format!(
                "{}: the file's name is not valid UTF-8, so it cannot be passed to the viewer",
                viewer.label
            );
            return;
        };
        // A viewer spawns a program named by a manifest, exactly what the
        // sidecar consent gate exists for, and manifests can arrive from the
        // signed remote index, not only the bundled catalog. The first run of
        // an extension's viewer shows the exact command line and spawns
        // nothing until the user allows it; allowing resumes this open.
        if !self.consented_extensions.contains(&viewer.ext_id) {
            use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
            let spawn_line = std::iter::once(viewer.command.clone())
                .chain(viewer.args.iter().map(|a| a.replace("{file}", &file)))
                .collect::<Vec<_>>()
                .join(" ");
            self.open_input_prompt(
                InputPrompt::new(
                    InputPurpose::ViewerConsent {
                        key: viewer.key(),
                        path: path.to_path_buf(),
                    },
                    format!("Allow {} to run:  {}", viewer.ext_id, spawn_line),
                    "Enter to allow · Esc to cancel",
                )
                .with_value("allow"),
            );
            return;
        }
        let install_name = viewer.install_name();
        let program = match viewer.provision.as_ref() {
            None => viewer.command.clone(),
            Some(provision) => {
                match crate::lsp::install::provisioned_command(&install_name, provision) {
                    Some((command, _extra_paths)) => command,
                    None => {
                        let name: &'static str = crate::lsp::install::static_name(&install_name);
                        let config = crate::lsp::config::ServerConfig {
                            name,
                            command: viewer.command.clone(),
                            args: viewer.args.clone(),
                            language: crate::lsp::config::Language("viewer"),
                            initialization_options: None,
                            provision: Some(provision.clone()),
                        };
                        crate::lsp::install::resolve_managed(&config, provision, true);
                        self.status =
                            format!("Installing {}; run it again once it lands", viewer.label);
                        return;
                    }
                }
            }
        };
        let args: Vec<String> = viewer
            .args
            .iter()
            .map(|a| a.replace("{file}", &file))
            .collect();
        let cwd = path
            .parent()
            .filter(|p| p.is_dir())
            .map(Path::to_path_buf)
            .unwrap_or_else(|| self.workspace_root().to_path_buf());
        match PtyTerminal::new_running(&program, &args, &cwd) {
            Ok(term) => {
                let slot = (self.active_terminal + 1).min(self.terminals.len());
                self.terminals.insert(slot, term);
                self.active_terminal = slot;
                if !self.show_terminal {
                    self.show_terminal = true;
                }
                self.focus_pane(Pane::Terminal);
                self.status = format!("{}: {}", viewer.label, self.status_path(path));
            }
            Err(e) => {
                self.status = format!("{} failed to start: {e}", viewer.label);
            }
        }
    }

    /// A palette `viewer:<extension id>/<viewer id>` row: open the active
    /// editor file in that viewer, if the file is a kind it handles.
    fn run_viewer_command(&mut self, viewer_id: &str) {
        let Some(viewer) = crate::mcp::registry::viewer_by_id_in_dir(&self.config_dir, viewer_id)
        else {
            self.status = format!("Viewer '{viewer_id}' is unavailable");
            return;
        };
        self.open_active_file_in_viewer(&viewer);
    }

    /// The palette row's work once its viewer is known: the active editor
    /// file must exist and be a kind the viewer handles, or the status line
    /// says which it is not.
    fn open_active_file_in_viewer(&mut self, viewer: &crate::mcp::registry::ContributedViewer) {
        let Some(path) = self.editor.path.clone() else {
            self.status = format!("{}: open a file first", viewer.label);
            return;
        };
        let ext = path
            .extension()
            .map(|e| e.to_string_lossy().to_lowercase())
            .unwrap_or_default();
        if !viewer.extensions.contains(&ext) {
            self.status = format!(
                "{}: the active file is not one of .{}",
                viewer.label,
                viewer.extensions.join(" / .")
            );
            return;
        }
        self.open_in_viewer(viewer, &path);
    }

    /// Dispatch a chosen palette row: a built-in command runs inline; an
    /// extension-contributed command routes through the MCP sidecar path.
    fn run_palette_item(&mut self, item: crate::widgets::command_palette::PaletteItem) {
        use crate::widgets::command_palette::PaletteItem;
        match item {
            PaletteItem::Builtin(cmd) => self.run_command(cmd),
            PaletteItem::Extension(ec) => self.run_extension_command(&ec.id),
        }
    }

    /// Invoke an MCP sidecar command by id. Gated by first-run consent (a popup
    /// showing the exact spawn command); once consented, collects the declared
    /// argument (if any) via an input popup, then spawns the server off-thread.
    fn run_extension_command(&mut self, command_id: &str) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        // Viewer rows (#465) run a terminal program on the active file; no
        // sidecar, so none of the MCP consent or argument flow below applies.
        if let Some(viewer_id) =
            command_id.strip_prefix(crate::mcp::registry::VIEWER_COMMAND_PREFIX)
        {
            self.run_viewer_command(viewer_id);
            return;
        }
        let Some(resolved) =
            crate::mcp::registry::resolve_command_in_dir(&self.config_dir, command_id)
        else {
            self.status = format!("Extension command '{command_id}' is unavailable");
            return;
        };
        // First-run consent gate: never spawn a sidecar until the user has
        // approved this extension, shown the exact command line croft will run.
        // One set answers this gate and the viewer gate alike: it is loaded
        // from prefs at startup and fed by every grant since, so the two
        // cannot disagree, whatever became of a prefs write.
        if !self.consented_extensions.contains(&resolved.ext_id) {
            let spawn_line = std::iter::once(resolved.server.command.clone())
                .chain(resolved.server.args.iter().cloned())
                .collect::<Vec<_>>()
                .join(" ");
            self.open_input_prompt(
                InputPrompt::new(
                    InputPurpose::McpConsent {
                        command_id: command_id.to_string(),
                    },
                    format!("Allow {} to run:  {}", resolved.ext_id, spawn_line),
                    "Enter to allow · Esc to cancel",
                )
                .with_value("allow"),
            );
            return;
        }
        // Collect the declared argument, if any, then run.
        if let (Some(_), Some(label)) = (resolved.arg.as_ref(), resolved.prompt.as_ref()) {
            self.open_input_prompt(InputPrompt::new(
                InputPurpose::McpArg {
                    command_id: command_id.to_string(),
                },
                resolved.title.clone(),
                label.clone(),
            ));
            return;
        }
        self.spawn_mcp_command(resolved, None);
    }

    /// Spawn the MCP server off the UI thread and run the command's tool; the
    /// result is delivered to [`poll_mcp`](Self::poll_mcp) over a channel and
    /// rendered into a markdown scratch buffer. Refuses to start a second
    /// command while one is in flight.
    fn spawn_mcp_command(
        &mut self,
        resolved: crate::mcp::registry::ResolvedCommand,
        arg: Option<String>,
    ) {
        if self.mcp_rx.is_some() {
            self.status = String::from("An extension command is already running");
            return;
        }
        let (tx, rx) = std::sync::mpsc::channel();
        self.mcp_rx = Some(rx);
        // On first use the server isn't provisioned yet; the worker installs it
        // (block-and-wait) before running, which can take a moment. Say so, so
        // the user sees install progress rather than a silent "Running".
        let installing = resolved.server.provision.as_ref().is_some_and(|p| {
            crate::lsp::install::provisioned_command(&resolved.server.id, p).is_none()
        });
        let label = if installing {
            format!(
                "Installing {} (first run, this can take a moment)",
                resolved.title
            )
        } else {
            format!("Running {}", resolved.title)
        };
        // Drive the status-bar spinner badge while the worker runs.
        self.mcp_started = Some(std::time::Instant::now());
        self.mcp_busy_label = Some(label.clone());
        self.status = label.clone();
        let cwd = self.workspace_root().to_path_buf();
        let version = env!("CARGO_PKG_VERSION").to_string();
        let _ = std::thread::Builder::new()
            .name("mcp-cmd".into())
            .spawn(move || {
                let _ = tx.send(run_mcp_command_blocking(&resolved, arg, &cwd, &version));
            });
    }

    /// On-disk path for a scratch buffer (MCP output, Git Output): anchored under
    /// the workspace root with a filesystem-safe name, so Cmd+S saves it
    /// predictably into the open project (and the Explorer tree shows it) instead
    /// of writing a bare filename to croft's working directory.
    fn scratch_buffer_path(&self, name: &str) -> PathBuf {
        let safe = name.replace(['/', '\\'], "-");
        self.workspace_root().join(safe)
    }

    /// Drain a completed MCP command: render its text into a scratch buffer on
    /// success, or surface the error in the status line. Returns whether a
    /// redraw is needed. Called each frame from the main loop.
    pub fn poll_mcp(&mut self) -> bool {
        let Some(rx) = self.mcp_rx.as_ref() else {
            return false;
        };
        let outcome = match rx.try_recv() {
            Ok(o) => o,
            Err(std::sync::mpsc::TryRecvError::Empty) => return false,
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.mcp_rx = None;
                self.mcp_started = None;
                self.mcp_busy_label = None;
                return false;
            }
        };
        self.mcp_rx = None;
        self.mcp_started = None;
        self.mcp_busy_label = None;
        match outcome.body {
            Ok(text) => {
                let label = self.scratch_buffer_path(&format!("{}.md", outcome.title));
                if self.editor.open_text_buffer(&label, &text).is_ok() {
                    // An MCP result arrives asynchronously; the user may be
                    // mid-scroll in the Explorer and did not ask for focus to
                    // move, let alone for the sidebar to close (#260).
                    self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
                    self.status = format!(
                        "{}: opened in a new tab — Cmd+S saves it into the project",
                        outcome.title
                    );
                }
            }
            Err(e) => {
                self.status = format!("{}: {e}", outcome.title);
            }
        }
        true
    }

    /// Capture one key into the live recording. Recording control keys are
    /// excluded by the callers that own them (vim's `q`, the palette
    /// commands), so a macro can never contain the gesture that ends it.
    fn record_macro_key(&mut self, key: crossterm::event::KeyEvent) {
        if let Some(rec) = self.macro_recording.as_mut() {
            rec.recorded.push_key(key);
        }
    }

    /// Start recording into `register` (vim `q{a-z}`) or into the unnamed
    /// last-recording slot (the palette command). Starting while already
    /// recording stops instead, so one gesture toggles.
    fn start_macro_recording(&mut self, register: Option<char>) {
        if self.macro_recording.is_some() {
            self.stop_macro_recording();
            return;
        }
        self.macro_recording = Some(crate::macros::Recording {
            register,
            recorded: crate::macros::Macro::default(),
        });
        // One source of truth: vim's `q` branches on this, and a copy the
        // machine kept for itself drifted whenever the palette was used.
        self.vim.set_recording(true);
        self.status = match register {
            Some(r) => format!("Recording macro into @{r}"),
            None => String::from("Recording macro"),
        };
    }

    /// Finish the live recording: it becomes the last macro either way, and
    /// a named register is also persisted. An empty recording is discarded
    /// rather than replacing a useful macro with a no-op.
    fn stop_macro_recording(&mut self) {
        let Some(rec) = self.macro_recording.take() else {
            return;
        };
        self.vim.set_recording(false);
        if rec.recorded.is_empty() {
            self.status = String::from("Macro discarded (nothing recorded)");
            return;
        }
        let len = rec.recorded.len();
        if let Some(r) = rec.register {
            let name = r.to_string();
            self.macro_registers
                .insert(name.clone(), rec.recorded.clone());
            if let Err(e) =
                crate::macros::save_register(&self.macros_path, &name, rec.recorded.clone())
            {
                crate::output::push("Macros", crate::output::OutputLevel::Warn, &e);
            }
            self.status = format!("Recorded {len} keys into @{r}");
        } else {
            self.status = format!("Recorded {len} keys");
        }
        self.macro_last = Some(rec.recorded);
    }

    /// Replay `mac` `count` times by feeding its keys back through
    /// `handle_key`. Guarded three ways: a re-entrancy flag (a macro cannot
    /// invoke itself), a total-key budget (a pathological count cannot spin
    /// the UI), and an abort on the first key that errors, which leaves the
    /// buffer at the abort point with earlier iterations intact.
    fn replay_macro(&mut self, mac: crate::macros::Macro, count: usize) {
        const MAX_REPLAY_KEYS: usize = 100_000;
        if self.macro_replaying {
            self.status = String::from("Macro is already replaying");
            return;
        }
        if mac.is_empty() {
            self.status = String::from("Macro is empty");
            return;
        }
        let count = count.max(1);
        // Budget the keys actually fed, not the recorded step count:
        // `key_events` drops steps this build cannot replay, so `len()` is an
        // upper bound rather than the real total.
        let keys = mac.key_events();
        if keys.is_empty() {
            // Every step was one this build cannot replay (a macro from a
            // newer croft). Say so rather than reporting a successful run
            // of nothing.
            self.status = String::from("Macro has no steps this version can replay");
            return;
        }
        let total = keys.len().saturating_mul(count);
        if total > MAX_REPLAY_KEYS {
            self.status =
                format!("Macro would run {total} keys (limit {MAX_REPLAY_KEYS}) — refused");
            return;
        }
        self.macro_replaying = true;
        let mut done = 0usize;
        let mut aborted = None;
        'outer: for iteration in 0..count {
            // Break coalescing so a new iteration's opening keystrokes never
            // merge into the previous iteration's typing run. This bounds
            // iterations apart; it does NOT make one iteration one undo step
            // — `push_undo` coalesces only InsertChar→InsertChar, so a macro
            // holding a delete plus an insert still undoes in two. A real
            // one-step-per-iteration guarantee needs an undo-group API the
            // editor does not have (its undo is whole-buffer snapshots).
            self.editor.break_undo_coalescing();
            for k in &keys {
                if let Err(e) = self.handle_key(*k) {
                    aborted = Some((iteration + 1, e.to_string()));
                    break 'outer;
                }
            }
            done = iteration + 1;
        }
        self.macro_replaying = false;
        self.status = match aborted {
            Some((at, e)) => format!("Macro aborted on iteration {at}: {e}"),
            None if done == 1 => String::from("Macro replayed"),
            None => format!("Macro replayed {done}×"),
        };
    }

    /// Replay the last recording (palette "Macro: Replay Last", vim `@@`).
    fn replay_last_macro(&mut self, count: usize) {
        match self.macro_last.clone() {
            Some(m) => self.replay_macro(m, count),
            None => self.status = String::from("No macro recorded yet"),
        }
    }

    /// Replay a named register (vim `@{a-z}`).
    fn replay_macro_register(&mut self, register: char, count: usize) {
        match self.macro_registers.get(&register.to_string()).cloned() {
            Some(m) => {
                self.macro_last = Some(m.clone());
                self.replay_macro(m, count);
            }
            None => self.status = format!("Register @{register} is empty"),
        }
    }

    /// Execute a Command Palette entry. Editor text commands act on the active
    /// editor buffer; view / navigation commands defer to the same methods
    /// their dedicated chords use, so the palette can never drift from the
    /// keyboard surface.
    pub(crate) fn run_command(&mut self, cmd: crate::widgets::command_palette::Command) {
        use crate::widgets::command_palette::Command as Cmd;
        use crate::widgets::editor::CaseTransform;
        match cmd {
            Cmd::MoveLineUp => self.editor.move_lines_up(),
            Cmd::MoveLineDown => self.editor.move_lines_down(),
            Cmd::ToggleLineComment => {
                if !self.editor.toggle_line_comment() {
                    self.status = String::from("Toggle Line Comment: no comment for this language");
                }
            }
            Cmd::ToggleBlockComment => {
                if !self.editor.toggle_block_comment() {
                    self.status =
                        String::from("Toggle Block Comment: no block comment for this language");
                }
            }
            Cmd::JoinLines => self.editor.join_lines(),
            Cmd::DeleteLine => self.delete_current_line(),
            Cmd::TransformUpper => self.editor.transform_selection_case(CaseTransform::Upper),
            Cmd::TransformLower => self.editor.transform_selection_case(CaseTransform::Lower),
            Cmd::TransformTitle => self.editor.transform_selection_case(CaseTransform::Title),
            Cmd::SortLinesAscending => self.editor.sort_lines(true),
            Cmd::SortLinesDescending => self.editor.sort_lines(false),
            Cmd::TrimTrailingWhitespace => {
                if self.editor.trim_trailing_whitespace() {
                    self.status = String::from("Trimmed trailing whitespace");
                }
            }
            Cmd::ExpandSelection => self.expand_selection(),
            Cmd::ShrinkSelection => self.shrink_selection(),
            Cmd::ToggleWordWrap => {
                self.editor.toggle_wrap();
                self.status = if self.editor.wrap_enabled() {
                    String::from("Word wrap: on")
                } else {
                    String::from("Word wrap: off")
                };
            }
            Cmd::AddCursorAbove => self.editor.add_cursor_above(),
            Cmd::AddCursorBelow => self.editor.add_cursor_below(),
            Cmd::AddSelectionToNextMatch => self.start_select_next_occurrence(),
            Cmd::JumpToBracket => {
                if !self.editor.jump_to_matching_bracket() {
                    self.status = String::from("Go to Bracket: no matching bracket");
                }
            }
            Cmd::SelectToBracket => {
                if !self.editor.select_to_matching_bracket() {
                    self.status = String::from("Select to Bracket: no matching bracket");
                }
            }
            Cmd::TransposeCharacters => self.editor.transpose_chars(),
            Cmd::IndentationToSpaces => {
                self.editor.indentation_to_spaces();
                self.status = String::from("Converted indentation to spaces");
            }
            Cmd::IndentationToTabs => {
                self.editor.indentation_to_tabs();
                self.status = String::from("Converted indentation to tabs");
            }
            Cmd::FormatDocument => self.start_format_document(),
            Cmd::FormatSelection => self.format_selection(),
            Cmd::ChangeColorPresentation => self.change_color_presentation(),
            Cmd::ToggleFormatOnType => self.toggle_format_on_type(),
            Cmd::ToggleFormatOnSave => self.toggle_format_on_save(),
            Cmd::ToggleAutoSave => self.toggle_auto_save(),
            Cmd::ToggleAutoSaveOnFocusChange => self.toggle_auto_save_on_focus_change(),
            Cmd::ToggleInlineBlame => self.toggle_inline_blame(),
            Cmd::ToggleProvenance => self.toggle_provenance(),
            Cmd::DiffToggleGroupBySeat => self.diff_toggle_group_by_seat(),
            Cmd::ToggleIndentGuides => self.toggle_indent_guides(),
            Cmd::ToggleBracketColors => self.toggle_bracket_colors(),
            Cmd::ToggleRenderWhitespace => self.toggle_render_whitespace(),
            Cmd::ToggleInlineValues => self.toggle_inline_values(),
            Cmd::ToggleInlayHints => self.toggle_inlay_hints(),
            Cmd::ToggleMarkdownPreview => self.toggle_markdown_preview(),
            Cmd::ToggleTerminalTimestamps => self.toggle_terminal_timestamps(),
            Cmd::ToggleLogHighlight => self.toggle_log_highlight(),
            Cmd::CollapseTerminalPane => self.collapse_active_terminal_pane(),
            Cmd::RestoreTerminalPanes => self.restore_all_terminal_panes(),
            Cmd::ToggleSecretRedaction => self.toggle_secret_redaction(),
            Cmd::RevealRedactedSecrets => self.reveal_redacted_secrets(),
            Cmd::SearchFromTerminal => self.search_from_last_terminal_command(),
            Cmd::RestoreSnapshot => self.restore_history_snapshot(),
            Cmd::QuickFix => self.start_code_action(),
            Cmd::ReplaceInFile => self.open_editor_replace(),
            // The accept/navigate commands serve both merge flows: the
            // three-way merge editor when its view is up (#253), the
            // in-buffer marker flow otherwise.
            Cmd::MergeAcceptCurrent => {
                if self.editor.merge.is_some() {
                    self.merge_apply(crate::merge_editor::ConflictState::Current);
                } else {
                    self.resolve_merge_at_cursor(crate::merge::Resolution::Current)
                }
            }
            Cmd::MergeAcceptIncoming => {
                if self.editor.merge.is_some() {
                    self.merge_apply(crate::merge_editor::ConflictState::Incoming);
                } else {
                    self.resolve_merge_at_cursor(crate::merge::Resolution::Incoming)
                }
            }
            Cmd::MergeAcceptBoth => {
                if self.editor.merge.is_some() {
                    self.merge_apply(crate::merge_editor::ConflictState::Both);
                } else {
                    self.resolve_merge_at_cursor(crate::merge::Resolution::Both)
                }
            }
            Cmd::MergeAcceptBothReverse => {
                if self.editor.merge.is_some() {
                    self.merge_apply(crate::merge_editor::ConflictState::BothReverse);
                } else {
                    self.status = String::from("Incoming-first combination needs the merge editor");
                }
            }
            Cmd::MergeIgnore => {
                if self.editor.merge.is_some() {
                    self.merge_apply(crate::merge_editor::ConflictState::Base);
                } else {
                    self.status = String::from("Ignore (keep base) needs the merge editor");
                }
            }
            Cmd::MergeAcceptAllCurrent => {
                if self.editor.merge.is_some() {
                    self.merge_accept_all(crate::merge_editor::ConflictState::Current);
                } else {
                    self.resolve_all_merge(crate::merge::Resolution::Current)
                }
            }
            Cmd::MergeAcceptAllIncoming => {
                if self.editor.merge.is_some() {
                    self.merge_accept_all(crate::merge_editor::ConflictState::Incoming);
                } else {
                    self.resolve_all_merge(crate::merge::Resolution::Incoming)
                }
            }
            Cmd::MergeNextConflict => {
                if self.editor.merge.is_some() {
                    self.merge_jump(false);
                } else {
                    self.jump_conflict(false)
                }
            }
            Cmd::MergePrevConflict => {
                if self.editor.merge.is_some() {
                    self.merge_jump(true);
                } else {
                    self.jump_conflict(true)
                }
            }
            Cmd::MergeComplete => self.complete_merge(),
            Cmd::MergeOpenEditor => match self.editor.path.clone() {
                Some(p) => {
                    self.open_merge_editor_for(&p);
                }
                None => self.status = String::from("No file in the active tab"),
            },
            Cmd::MergeToggleBase => match self.editor.merge.as_mut() {
                Some(mv) => {
                    mv.show_base = !mv.show_base;
                    self.status = if self.editor.merge.as_ref().is_some_and(|m| m.show_base) {
                        String::from("Base pane shown")
                    } else {
                        String::from("Base pane hidden")
                    };
                }
                None => self.status = String::from("Show Base needs the merge editor"),
            },
            Cmd::DebugAddWatch => self.open_add_watch_prompt(),
            Cmd::PeekDefinition => self.peek_definition_at_cursor(),
            // Position-carrying commands (#259). They read the click the
            // dispatcher set, and do nothing from the keyboard: invoked from
            // the palette there is no click to act on, and guessing the
            // caret instead would make one command mean two things.
            // All three arms refuse on a non-text view for the reason
            // `trigger_definition_at` does: `buffer_pos_at` maps cells using
            // only the text layout, so on a diff/sheet/hex/image/archive tab
            // it happily returns a position into the stub text side. Acting
            // on it moves the cursor somewhere meaningless and — for the
            // definition arm — fires an LSP request against it. The built-in
            // returns silently; a BOUND command says so instead, because the
            // user asked for it explicitly and silence reads as a broken
            // binding rather than a deliberate refusal.
            Cmd::MouseAddCursorAtClick => match self.last_mouse_pos {
                Some((col, row)) => {
                    if self.editor.has_non_text_view() {
                        self.status = String::from("No cursors in this view");
                    } else if self.editor.add_caret_at_screen(col, row) {
                        // Same as the built-in Alt+click: reset the blink
                        // phase, or a new caret can land mid-blink-off and
                        // read as "nothing happened" for up to a full period.
                        self.poke_cursor();
                    } else {
                        self.status = String::from("No place for a cursor there");
                    }
                }
                None => {
                    self.status = String::from("Mouse: Add Cursor at Click needs a mouse binding")
                }
            },
            Cmd::MouseGoToDefinitionAtClick => match self.last_mouse_pos {
                Some(_) if self.editor.has_non_text_view() => {
                    self.status = String::from("No definitions in this view");
                }
                // The outer `buffer_pos_at` exists ONLY to produce a status
                // when the click resolves to no buffer position: the built-in
                // fails silently there, which is right for a gesture the user
                // did not aim, but a command they bound deliberately should
                // say why nothing happened. `trigger_definition_at` repeats
                // the lookup internally — do not "simplify" this away, or the
                // bound command goes mute on a miss.
                Some((col, row)) => match self.editor.buffer_pos_at(col, row) {
                    // Delegate rather than re-implement: `trigger_definition_at`
                    // follows a server-resolved document link BEFORE asking for
                    // a definition (#254), and a bound gesture meant to replace
                    // the built-in must keep that precedence. Duplicating the
                    // check here would let the two drift on the next change.
                    Some(_) => self.trigger_definition_at(col, row),
                    None => self.status = String::from("Nothing to define there"),
                },
                None => {
                    self.status =
                        String::from("Mouse: Go to Definition at Click needs a mouse binding")
                }
            },
            Cmd::MouseOpenLinkAtClick => match self.last_mouse_pos {
                Some((col, row)) => {
                    // `editor` is the DEFAULT `when` region, so the most
                    // natural binding for this command lands there. Both
                    // terminal helpers hit-test the TERMINAL's `last_inner`
                    // and return false anywhere else, so consulting only them
                    // made the command a permanent no-op in its own default
                    // region -- reporting "No link there" over a link that is.
                    // The refusal belongs to the EDITOR lookup only. Its
                    // reason — `buffer_pos_at` maps cells from the TEXT
                    // layout, so a diff/sheet/hex/log view still yields a
                    // position and we would read links from a buffer the user
                    // is not looking at — says nothing about the terminal
                    // helpers below, which read `self.terminal()` alone. The
                    // built-in this command replaces guards neither, so a
                    // guard spanning both made the bound command diverge from
                    // it in the opposite direction to the one being fixed.
                    // Bound once: the refusal and the status it explains must
                    // answer the SAME question, or the status describes a
                    // lookup that never ran.
                    let editor_blocked = self.editor.has_non_text_view();
                    let followed = !editor_blocked
                        && self
                            .editor
                            .buffer_pos_at(col, row)
                            .and_then(|(line, c)| {
                                self.editor.document_link_at(line, c).map(str::to_string)
                            })
                            .inspect(|target| self.open_document_link(target))
                            .is_some();
                    if !followed
                        && !self.terminal_url_click(col, row)
                        && !self.terminal_file_click(col, row)
                    {
                        // Name the view only when the EDITOR lookup is the
                        // one that missed. A click in a terminal pane never
                        // consulted the editor — `editor_blocked` short-
                        // circuited it above — so reporting the editor's view
                        // there names something that was never searched.
                        // "a non-text view is up" and "the editor lookup is
                        // the one that missed" are different questions.
                        let in_terminal = self.terminal_at_pos(col, row).is_some();
                        self.status = String::from(if editor_blocked && !in_terminal {
                            "No links in this view"
                        } else {
                            "No link there"
                        });
                    }
                }
                None => {
                    self.status = String::from("Mouse: Open Link at Click needs a mouse binding")
                }
            },
            Cmd::ClearBuildDiagnostics => self.clear_build_diagnostics(),
            Cmd::DebugClearWatch => {
                let n = self.watch_exprs.len();
                self.watch_exprs.clear();
                self.watch_vals.clear();
                self.watch_prev.clear();
                self.status = format!(
                    "Removed {n} watch expression{}",
                    if n == 1 { "" } else { "s" }
                );
            }
            Cmd::StageHunk => self.stage_hunk_at_caret(),
            Cmd::UnstageHunk => self.unstage_hunk_at_caret(),
            Cmd::RevertHunk => self.request_revert_hunk_at_caret(),
            Cmd::ToggleFold => {
                let row = self.editor.cursor_row;
                self.editor.toggle_fold(row);
            }
            Cmd::FoldAll => self.editor.fold_all(),
            Cmd::UnfoldAll => self.editor.unfold_all(),
            Cmd::FoldAllComments => self
                .editor
                .fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Comment),
            Cmd::FoldAllRegions => self
                .editor
                .fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region),
            Cmd::UnfoldAllRegions => self
                .editor
                .unfold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region),
            Cmd::TrimFinalNewlines => {
                if self.editor.trim_final_newlines() {
                    self.status = String::from("Trimmed final newlines");
                }
            }
            Cmd::SaveFile => self.save(),
            Cmd::Undo => {
                self.status = if self.editor.undo() {
                    String::from("Undo")
                } else {
                    String::from("Nothing to undo")
                };
            }
            Cmd::Redo => {
                self.status = if self.editor.redo() {
                    String::from("Redo")
                } else {
                    String::from("Nothing to redo")
                };
            }
            Cmd::CloseEditor => {
                self.record_closed_tab_at(self.editor.active_index());
                if self.editor.close_active() {
                    self.sync_open_file_poll_mtime();
                    self.collapse_split_if_empty();
                    self.status = String::from("Closed tab");
                }
            }
            Cmd::ReopenClosedEditor => self.reopen_closed_tab(),
            Cmd::SplitEditor => self.split_editor(),
            Cmd::QuickOpen => self.open_file_finder(),
            Cmd::GoToSymbol => self.open_go_to_symbol(),
            Cmd::GoToWorkspaceSymbol => self.open_workspace_symbols(""),
            Cmd::NavigateBack => self.nav_back(),
            Cmd::NavigateForward => self.nav_forward(),
            Cmd::GoToLastEditLocation => self.goto_last_edit_location(),
            Cmd::ToggleVimMode => self.toggle_vim_mode(),
            Cmd::MacroStartStopRecording if self.macro_replaying => {}
            Cmd::MacroStartStopRecording => {
                if self.macro_recording.is_some() {
                    self.stop_macro_recording();
                } else {
                    self.start_macro_recording(None);
                }
            }
            Cmd::MacroReplayLast if self.macro_replaying => {}
            Cmd::MacroReplayLast => self.replay_last_macro(1),
            // Guarded like its siblings: `macro_replay_times` is a bindable
            // id, so a replayed key reaches it. A prompt opening mid-replay
            // swallows the macro's remaining keys into the count field, and
            // `input_prompt` is checked ABOVE the macro tap, so a later
            // Enter would submit the count and re-enter replay.
            Cmd::MacroReplayTimes if self.macro_replaying => {}
            Cmd::MacroReplayTimes => {
                use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
                self.open_input_prompt(InputPrompt::new(
                    InputPurpose::MacroReplayCount,
                    "Replay Macro N Times",
                    "count",
                ));
            }
            Cmd::ShowExplorer => self.set_sidebar_view(SidebarView::Explorer),
            Cmd::ShowSearch => self.set_sidebar_view(SidebarView::Search),
            Cmd::ShowSourceControl => self.set_sidebar_view(SidebarView::SourceControl),
            Cmd::AddWorkspaceFolder => self.open_add_folder_picker(),
            Cmd::SaveWorkspaceAs => {
                use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
                let suggestion = {
                    let name = self
                        .workspace_root()
                        .file_name()
                        .map(|s| s.to_string_lossy().into_owned())
                        .unwrap_or_else(|| String::from("workspace"));
                    self.workspace_root()
                        .join(format!("{name}.code-workspace"))
                        .display()
                        .to_string()
                };
                self.open_input_prompt(
                    InputPrompt::new(
                        InputPurpose::SaveWorkspaceAs,
                        String::from("Save Workspace As"),
                        "Enter to save · Esc to cancel",
                    )
                    .with_value(&suggestion),
                );
            }
            Cmd::OpenWorkspaceFromFile => match self.editor.path.clone() {
                Some(p) if crate::workspace::is_workspace_file(&p) => self.open_workspace_file(&p),
                _ => {
                    self.status = String::from("Open a .code-workspace file in the editor first");
                }
            },
            Cmd::ReopenAsHex => match self.editor.path.clone() {
                // A dirty buffer's edits exist only in memory; the hex
                // view reads DISK, so switching would silently show (and
                // strand) stale bytes.
                Some(_) if self.editor.dirty => {
                    self.status = String::from("Save or revert the buffer before reopening as hex");
                }
                Some(p) => {
                    // The explicit hex choice supersedes a lingering
                    // Reopen-as-Text override.
                    self.editor.force_text = false;
                    if let Err(e) = self.editor.open_hex(&p) {
                        self.status = format!("Reopen as hex: {e}");
                    }
                }
                None => self.status = String::from("No file in the active tab"),
            },
            Cmd::ReopenAsText => match self.editor.path.clone() {
                // Merge editor (#253): back to the in-buffer marker flow.
                // The Result buffer is deliberately discarded — it was
                // never saved, and the marker file on disk is the source
                // of truth the old flow works on.
                Some(p) if self.editor.merge.is_some() => {
                    self.editor.merge = None;
                    self.editor.dirty = false;
                    self.editor.force_text = true;
                    match self.editor.open(&p) {
                        Ok(()) => {
                            let n = self.editor.conflicts().len();
                            self.status = format!(
                                "Marker flow: {n} conflict{} — F7 jumps, Cmd+. accepts",
                                if n == 1 { "" } else { "s" }
                            );
                        }
                        Err(e) => self.status = format!("Reopen as text: {e}"),
                    }
                }
                // A rendered notebook/markdown preview counts (#180): the
                // command lands in the raw source.
                Some(_)
                    if !self.editor.has_non_text_view()
                        && self.editor.markdown_preview.is_none() =>
                {
                    self.status = String::from("The active tab is already a text view");
                }
                // A dirty hex tab holds unwritten byte overwrites; the
                // text route would silently drop them (#173).
                Some(_) if self.editor.dirty => {
                    self.status =
                        String::from("Save or revert the pending edits before reopening as text");
                }
                Some(p) => {
                    // Per-tab override (#175): skip every preview route —
                    // an SVG lands in its XML source, a hex tab in the
                    // text heuristic (whose binary verdict routes back to
                    // hex, reported honestly). Sticks across FS-sync
                    // reloads; cleared by opening a different file.
                    self.editor.force_text = true;
                    match self.editor.open(&p) {
                        Ok(()) if self.editor.hex.is_some() => {
                            self.status =
                                String::from("Still binary by content - staying in the hex view");
                        }
                        Ok(()) => {}
                        Err(e) => self.status = format!("Reopen as text: {e}"),
                    }
                }
                None => self.status = String::from("No file in the active tab"),
            },
            Cmd::HexFindNext => self.hex_find_next(),
            Cmd::SheetInsertRowBelow
            | Cmd::SheetDeleteRow
            | Cmd::SheetInsertColRight
            | Cmd::SheetDeleteCol => self.sheet_structure_op(cmd),
            Cmd::MediaOpenExternal => match self.editor.path.clone() {
                Some(p)
                    if self
                        .editor
                        .markdown_preview
                        .as_ref()
                        .is_some_and(|md| md.media) =>
                {
                    // A remote session has no display to hand the file
                    // to (#202 review): the opener would run on the
                    // headless host and claim success.
                    if is_remote_session() {
                        self.status = format!(
                            "Running remotely: copy {} to your machine to play it",
                            p.display()
                        );
                    } else {
                        // The OS opener takes a filesystem path directly.
                        self.status = match open_url(&p.display().to_string()) {
                            Ok(()) => format!("Handed {} to the system player", p.display()),
                            Err(e) => format!("System player failed: {e}"),
                        };
                    }
                }
                _ => {
                    self.status = String::from("The active tab is not a media info card");
                }
            },
            Cmd::ReopenAsPreview => match self.editor.path.clone() {
                Some(_) if self.editor.dirty => {
                    self.status =
                        String::from("Save or revert the buffer before reopening the preview");
                }
                Some(p) => {
                    // Undo a Reopen-as-Text: normal routing decides the
                    // view again (SVG raster, image, sheet, hex).
                    self.editor.force_text = false;
                    match self.editor.open(&p) {
                        Ok(())
                            if !self.editor.has_non_text_view()
                                && self.editor.markdown_preview.is_none() =>
                        {
                            self.status =
                                String::from("No preview for this file type; showing the text");
                        }
                        Ok(()) => {}
                        Err(e) => self.status = format!("Reopen as preview: {e}"),
                    }
                }
                None => self.status = String::from("No file in the active tab"),
            },
            Cmd::RemoveWorkspaceFolder => {
                // Operates on the Explorer's selected row when it is a
                // SECONDARY root section; anything else gets the hint.
                let target = self
                    .tree
                    .nodes
                    .get(self.tree.selected)
                    .filter(|n| n.depth == 0 && n.path != self.tree.root)
                    .map(|n| n.path.clone());
                match target {
                    Some(p) => self.remove_workspace_folder(p),
                    None => {
                        self.status =
                            String::from("Select a secondary root folder in the Explorer first");
                    }
                }
            }
            Cmd::ShowRunDebug => self.set_sidebar_view(SidebarView::RunDebug),
            Cmd::ShowRemote => self.set_sidebar_view(SidebarView::Remote),
            Cmd::ShowExtensions => self.set_sidebar_view(SidebarView::Extensions),
            Cmd::CompareExtensionsWithVscode => self.compare_extensions_with_vscode(),
            Cmd::ShowTesting => self.open_testing_view(),
            Cmd::RunTestAtCursor => self.run_test_at_cursor(),
            Cmd::DebugTestAtCursor => self.debug_test_at_cursor(),
            Cmd::ToggleSideBar => self.toggle_side_bar(),
            Cmd::ToggleAutoHideSideBar => self.toggle_sidebar_auto_hide(),
            Cmd::ToggleSecondarySideBar => self.toggle_secondary_side_bar(),
            Cmd::ToggleZenMode => self.toggle_zen_mode(),
            Cmd::ToggleTerminal => self.toggle_terminal(),
            Cmd::ToggleMinimap => self.toggle_minimap(),
            Cmd::ProblemsToggleProjectAuto => {
                // auto -> on -> off -> auto. Cycling rather than a boolean
                // because `auto` is a distinct answer from both, not a
                // default the other two override.
                let next = match Self::project_scope_mode(&self.problems_project_scope) {
                    "auto" => "on",
                    "on" => "off",
                    _ => "auto",
                };
                self.problems_project_scope = String::from(next);
                let _ = crate::prefs::save_problems_project_scope(next);
                // `on` and `off` are answers on their own. `auto` is the
                // only mode whose effect depends on a count, and counting is
                // a whole-workspace walk - which this repo runs on a
                // background thread, never on a keypress. The early stop
                // bounds the walk only ABOVE the cap; a root under it is
                // walked to completion, which is the common case.
                let effect = match next {
                    "on" => " (runs on its own)",
                    "off" => " (never runs on its own)",
                    // Deliberately not the answer: reporting it here would
                    // cost the walk. The check itself reports when it
                    // declines, at the point it actually declines.
                    _ => " (runs on its own unless the workspace is very large)",
                };
                self.status = format!("Whole-project check: {next}{effect}");
            }
            Cmd::ProblemsCheckProject => {
                // An explicit ask always runs: the cap governs UNASKED runs
                // (#256 criterion 5), and refusing what the user just
                // requested would be answering a question nobody asked.
                let root = self.workspace_root().to_path_buf();
                match Self::project_check_command(&root) {
                    None => {
                        self.status = String::from(
                            "No whole-project checker for this workspace (expected tsconfig.json)",
                        );
                    }
                    Some(_) if self.project_check_running => {
                        self.status = String::from("A whole-project check is already running");
                    }
                    Some((program, args)) => {
                        // Off the main loop: tsc on a large project takes tens
                        // of seconds, and running it inline froze input and
                        // redraw for the duration - the "Checking..." status
                        // below never even painted. Same shape as
                        // `record_history_snapshot_of`: spawn, send, drain on
                        // the tick.
                        let tx = self.project_check_tx.clone();
                        let root_for_thread = root.clone();
                        let mode = self.problems_project_scope.clone();
                        let hint_tx = self.project_hint_tx.clone();
                        // NOT set here: this fires for every explicit check,
                        // so a run under `on`, `off`, or an under-cap `auto`
                        // would consume the one-shot and a later oversized
                        // `auto` run would stay silent forever. The flag is
                        // set where the hint is RECEIVED, which is the only
                        // point that knows one was warranted.
                        let hinted = self.project_check_hinted;
                        std::thread::spawn(move || {
                            // The cap's one-time hint (#256 criterion 5).
                            // Computed HERE, on the thread already spawned
                            // for the compile, because it is a whole-
                            // workspace walk - never on the UI thread. The
                            // explicit run still proceeds either way; the
                            // cap governs UNASKED runs, and this tells the
                            // user once that automatic ones will not start.
                            if !hinted
                                && !Self::project_check_auto_enabled(
                                    &root_for_thread,
                                    &mode,
                                    Self::PROJECT_CHECK_AUTO_MAX_FILES,
                                )
                                && Self::project_scope_mode(&mode) == "auto"
                            {
                                let _ = hint_tx.send(());
                            }
                            // .output(), never .status(): the checker must not
                            // inherit croft's TTY, or its diagnostics spray
                            // over the UI.
                            let done = std::process::Command::new(&program)
                                .args(&args)
                                .current_dir(&root_for_thread)
                                .output();
                            let _ = tx.send((root_for_thread, done));
                        });
                        self.project_check_running = true;
                        self.status = String::from("Checking the whole project...");
                    }
                }
            }
            Cmd::ProblemsToggleScope => {
                self.problems.scope = self.problems.scope.next();
                let _ = crate::prefs::save_problems_scope(self.problems.scope.to_config());
                // Rebuild rather than filter in the panel: the badge counts
                // the same list, so both follow the scope from one place.
                self.rebuild_problems();
                self.refresh_problems_badge();
                self.status = format!("Problems: {}", self.problems.scope.label());
            }
            Cmd::DiffToggleIgnoreWhitespace => self.diff_cycle_whitespace_mode(),
            Cmd::NewTerminal => match self.split_terminal() {
                Ok(()) => {
                    self.terminal_status(format!(
                        "Split terminal: {} active",
                        self.terminals.len()
                    ));
                }
                Err(e) => {
                    self.status = format!("Split terminal failed: {e}");
                }
            },
            Cmd::StartDebugging => self.debug_start_or_continue(),
            Cmd::SelectDebugConfig => self.open_debug_config_picker(),
            Cmd::StopDebugging => self.debug_stop(),
            Cmd::PauseDebugging => self.debug_pause(),
            Cmd::RestartDebugging => self.debug_restart(),
            Cmd::ToggleBreakpoint => self.debug_toggle_breakpoint(),
            Cmd::EditLogpoint => self.debug_edit_logpoint(),
            Cmd::ShowIncomingCalls => self.request_call_hierarchy_at_cursor(true),
            Cmd::ShowOutgoingCalls => self.request_call_hierarchy_at_cursor(false),
            Cmd::EditBreakpointCondition => self.debug_edit_condition(),
            Cmd::StepOver => self.debug_step("next"),
            Cmd::ToggleRaisedExceptions => self.debug_toggle_raised_exceptions(),
            Cmd::AttachPythonProcess => self.open_attach_python_picker(),
            Cmd::ColorTheme => self.open_theme_picker(),
            Cmd::SessionParticipants => self.open_participants_picker(),
            Cmd::CollabCancelStream => self.collab_cancel_stream(),
            Cmd::AskNavigatorAboutCapture => self.ask_navigator_about_capture(),
            Cmd::OpenWorkspaceOnSshHost => self.open_workspace_on_ssh_host(),
            Cmd::ScrubHistory => self.scrub_history(),
            Cmd::OpenAsSymbolTab => self.open_symbol_tab(),
            Cmd::LoadReviewThreads => self.load_review_threads(),
            Cmd::ToggleSessionRecording => self.toggle_session_recording(),
            Cmd::FleetRun => {
                self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
                    crate::widgets::input_prompt::InputPurpose::FleetCommand,
                    String::from("Fleet run"),
                    String::from("hosts: command   (or  *: command  for every host)"),
                ))
            }
            Cmd::NewWorktreeLane => self.open_new_lane_prompt(),
            Cmd::DiffWorktreeLane => self.diff_worktree_lane(),
            Cmd::CloseWorktreeLane => self.close_worktree_lane(),
            Cmd::MarkAgentFileReviewed => {
                match self.editor.path.clone() {
                    None => self.status = String::from("No file open"),
                    Some(path) if !self.agent_ledger.is_unreviewed(&path) => {
                        self.status =
                            String::from("No agent change waiting for review on this file");
                    }
                    Some(path) => {
                        // Every lane holding it: a file two agents both
                        // touched is reviewed once, for both.
                        let agents: Vec<String> = self
                            .agent_ledger
                            .agents()
                            .into_iter()
                            .map(String::from)
                            .collect();
                        let mut n = 0;
                        for agent in &agents {
                            if self.mark_agent_file_reviewed(agent, &path) {
                                n += 1;
                            }
                        }
                        let name = path
                            .file_name()
                            .map(|f| f.to_string_lossy().into_owned())
                            .unwrap_or_default();
                        self.status = format!(
                            "{name} marked reviewed in {n} agent lane{}",
                            if n == 1 { "" } else { "s" }
                        );
                    }
                }
            }
            Cmd::ShowAgentLane => {
                let rows = self.agent_lane_rows();
                self.status = if rows.is_empty() {
                    String::from("No agent has changed anything yet")
                } else if self.agent_ledger.may_be_incomplete() {
                    format!(
                        "{} \u{b7} at least: the file watcher overflowed",
                        rows.join(" \u{b7} ")
                    )
                } else {
                    rows.join(" \u{b7} ")
                };
            }
            Cmd::DiffAgentFileSinceReview => {
                match self.editor.path.clone() {
                    None => self.status = String::from("No file open"),
                    Some(path) => {
                        // The first lane holding it. A file two agents both
                        // touched has one baseline per lane, and diffing
                        // against an arbitrary second one would silently
                        // answer a different question than the row shows.
                        let agent = self
                            .agent_ledger
                            .agents()
                            .into_iter()
                            .map(String::from)
                            .find(|a| self.agent_ledger.lane(a).iter().any(|f| f.path == path));
                        match agent {
                            None => {
                                self.status = String::from("No agent has changed this file");
                            }
                            Some(agent) => self.diff_agent_lane_row(&agent, &path),
                        }
                    }
                }
            }
            Cmd::MarkAgentLaneReviewed => {
                let agents: Vec<String> = self
                    .agent_ledger
                    .agents()
                    .into_iter()
                    .map(String::from)
                    .collect();
                match agents.len() {
                    0 => self.status = String::from("No agent has changed anything yet"),
                    _ => {
                        let mut total = 0;
                        for agent in &agents {
                            total += self.mark_agent_lane_reviewed(agent);
                        }
                        // Each lane set its own status; the summary is the
                        // one the user is left with.
                        self.status = match total {
                            0 => String::from("Nothing waiting for review"),
                            1 => String::from("1 file marked reviewed"),
                            n => format!("{n} files marked reviewed"),
                        };
                    }
                }
            }
            Cmd::FixProblemWithNavigator => match self.navigator_fix_candidate() {
                Some((path, item)) => self.fix_problem_with_navigator(path, item, Vec::new()),
                None => self.status = String::from("No diagnostic at the caret to fix"),
            },
            Cmd::SendHttpRequest => self.send_http_request_under_caret(),
            Cmd::CopyHttpRequestAsCurl => self.copy_http_request_as_curl(),
            Cmd::AskNavigator => {
                let (range, selection) = match self.editor.selection_rows() {
                    Some(rows) => (rows, self.editor.selection_text()),
                    None => {
                        let row = self.editor.cursor_row;
                        ((row, row), String::new())
                    }
                };
                self.open_ask_navigator(range, selection);
            }
            Cmd::YieldToNavigator => self.yield_to_navigator(),
            Cmd::ToggleNavigator => self.toggle_navigator(),
            Cmd::ClearNavigatorNotes => self.clear_navigator_notes(),
            Cmd::ToggleProactiveNavigator => self.toggle_proactive_navigator(),
            Cmd::NextComment => self.cycle_comment_box(),
            Cmd::IgnoreComment => self.ignore_focused_comment(),
            Cmd::RunTask => self.open_run_task_picker(),
            Cmd::RunBuildTask => self.run_build_task(),
            Cmd::RerunLastTask => self.rerun_last_task(),
            Cmd::KeyboardShortcuts => self.open_shortcuts_modal(),
            Cmd::OpenSettings => self.open_settings_view(),
            Cmd::OpenSettingsJson => self
                .open_config_file_in_editor(crate::prefs::config_path(), ConfigFileSeed::Settings),
            Cmd::OpenWorkspaceSettingsJson => self.open_workspace_settings(false),
            Cmd::OpenWorkspaceSettingsLocalJson => self.open_workspace_settings(true),
            Cmd::OpenKeybindingsJson => self.open_config_file_in_editor(
                crate::keymap::keybindings_path(),
                ConfigFileSeed::Keybindings,
            ),
            Cmd::ConfigureSnippets => self.open_config_file_in_editor(
                crate::snippets::snippets_path(),
                ConfigFileSeed::Snippets,
            ),
            Cmd::OpenAgentsJson => self
                .open_config_file_in_editor(crate::agents::agents_path(), ConfigFileSeed::Agents),
            Cmd::OpenTriggersJson => self.open_config_file_in_editor(
                crate::triggers::triggers_path(),
                ConfigFileSeed::Triggers,
            ),
            Cmd::OpenMatchersJson => self.open_config_file_in_editor(
                crate::problem_matchers::matchers_path(),
                ConfigFileSeed::Matchers,
            ),
        }
    }

    /// Open one of the JSON config files in the editor, creating it seeded with
    /// a helpful starter when it doesn't exist yet, then reload the in-memory
    /// copy so a subsequent save takes effect without a relaunch.
    fn open_config_file_in_editor(&mut self, path: std::path::PathBuf, seed: ConfigFileSeed) {
        if !path.exists() {
            if let Some(parent) = path.parent() {
                let _ = std::fs::create_dir_all(parent);
            }
            let contents = match seed {
                ConfigFileSeed::Settings => {
                    let prefs = crate::prefs::Prefs::load_or_default();
                    serde_json::to_string_pretty(&prefs).unwrap_or_else(|_| String::from("{}\n"))
                }
                ConfigFileSeed::SettingsLayer => SETTINGS_LAYER_TEMPLATE.to_string(),
                ConfigFileSeed::Keybindings => crate::keymap::TEMPLATE.to_string(),
                ConfigFileSeed::Snippets => crate::snippets::TEMPLATE.to_string(),
                ConfigFileSeed::Triggers => crate::triggers::TEMPLATE.to_string(),
                ConfigFileSeed::Agents => crate::agents::TEMPLATE.to_string(),
                ConfigFileSeed::Matchers => crate::problem_matchers::TEMPLATE.to_string(),
            };
            if let Err(e) = std::fs::write(&path, contents) {
                self.status = format!("Could not create {}: {e}", path.display());
                return;
            }
        }
        if let Some(idx) = self.editor.find_tab_with_path(&path) {
            self.editor.select(idx);
        } else if self.editor.open(&path).is_err() {
            self.status = format!("Could not open {}", path.display());
            return;
        }
        self.focus_pane(Pane::Editor);
        self.sync_open_file_poll_mtime();
        self.status = match seed {
            ConfigFileSeed::Settings => {
                String::from("Editing settings — save to apply (theme and editor toggles live)")
            }
            ConfigFileSeed::SettingsLayer => {
                String::from("Editing a settings layer — save to apply")
            }
            ConfigFileSeed::Keybindings => String::from(
                "Editing keybindings.json — save, then reload keybindings from the palette",
            ),
            ConfigFileSeed::Snippets => {
                String::from("Editing snippets.json — save to apply immediately")
            }
            ConfigFileSeed::Triggers => {
                String::from("Editing triggers.json — save to apply immediately")
            }
            ConfigFileSeed::Agents => {
                String::from("Editing agents.json — save to apply immediately")
            }
            ConfigFileSeed::Matchers => {
                String::from("Editing matchers.json — save to apply immediately")
            }
        };
    }

    pub fn consume_zoxide_jump_image_clear(&mut self) -> bool {
        self.overlays.zoxide_jump_clear.consume()
    }

    /// Open the zoxide jump popup and seed it with the full frecency list
    /// (`zoxide query -l`), so it shows the user's top directories before
    /// they type anything — like pressing `j<Tab>` in the shell.
    fn open_zoxide_jump(&mut self) {
        if self.zoxide_jump.is_some() {
            return;
        }
        let mut jump = crate::widgets::zoxide_jump::ZoxideJump::new();
        jump.install_state = crate::zoxide::install_state();
        jump.termux = crate::iterm2_inline::detect_termux();
        jump.set_results(crate::zoxide::query(""));
        // Snapshot the full frecency list so the typo-tolerant fuzzy
        // fallback can rank against it without re-spawning zoxide on every
        // missed keystroke.
        jump.set_all_dirs(jump.results.clone());
        let status = if jump.available {
            format!(
                "Jump: {} directories — type to filter, Esc to close",
                jump.results.len()
            )
        } else {
            // Same honest copy as the popup body (single source of truth).
            format!(
                "Jump: {}",
                crate::widgets::zoxide_jump::unavailable_message(jump.install_state, jump.termux)
                    .trim_start()
            )
        };
        self.zoxide_jump = Some(jump);
        self.overlays.zoxide_jump_clear.request();
        self.status = status;
    }

    fn close_zoxide_jump(&mut self) {
        self.zoxide_add_folder = false;
        if self.zoxide_jump.take().is_some() {
            self.overlays.zoxide_jump_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    /// Re-run `zoxide query` for the popup's current text and feed the
    /// ranked matches back to the widget. The one subprocess per keystroke
    /// is cheap (zoxide reads a small frecency DB; single-digit ms) and
    /// fires only on input, never on the render hot path.
    ///
    /// Two layers: the strict `zoxide query` is authoritative and handles
    /// the common case. Only when it returns zero matches for a non-empty
    /// needle does the typo-tolerant `fuzzy_rank` fallback run, ranking the
    /// cached frecency DB by edit distance so a transposition like `spilt`
    /// still finds `pr-split` (zoxide's own subsequence matcher cannot).
    /// The fallback is purely in-memory, so it never spawns zoxide twice.
    fn refresh_zoxide_results(&mut self) {
        let Some(jump) = self.zoxide_jump.as_mut() else {
            return;
        };
        let needle = jump.query.clone();
        // The background install may have advanced (Running -> Done/Failed)
        // since the popup opened; keep the unavailable message current.
        jump.install_state = crate::zoxide::install_state();
        match crate::zoxide::query(&needle) {
            Some(paths) if paths.is_empty() && !needle.trim().is_empty() => {
                let ranked = crate::zoxide::fuzzy_rank(&needle, &jump.all_dirs);
                if ranked.is_empty() {
                    jump.set_results(Some(Vec::new()));
                } else {
                    jump.set_approximate_results(ranked);
                }
            }
            other => jump.set_results(other),
        }
    }

    fn handle_zoxide_jump_key(&mut self, key: KeyEvent) {
        let Some(jump) = self.zoxide_jump.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => {
                self.close_zoxide_jump();
            }
            (KeyCode::Enter, _) => self.apply_zoxide_jump_selection(),
            (KeyCode::Up, _) => jump.select_prev(),
            (KeyCode::Down, _) => jump.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    jump.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    jump.select_next();
                }
            }
            (KeyCode::Left, _) => jump.move_cursor_left(),
            (KeyCode::Right, _) => jump.move_cursor_right(),
            (KeyCode::Home, _) => jump.move_cursor_home(),
            (KeyCode::End, _) => jump.move_cursor_end(),
            (KeyCode::Backspace, _) => {
                jump.pop_char();
                self.refresh_zoxide_results();
            }
            (KeyCode::Delete, _) => {
                jump.delete_char();
                self.refresh_zoxide_results();
            }
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                jump.push_char(c);
                self.refresh_zoxide_results();
            }
            _ => {}
        }
    }

    /// Jump to (or add) the highlighted directory and dismiss the popup:
    /// Enter's action, shared with a mouse click on a result row.
    fn apply_zoxide_jump_selection(&mut self) {
        let Some(jump) = self.zoxide_jump.as_ref() else {
            return;
        };
        let path = jump.selected_path().map(|p| p.to_path_buf());
        if let Some(path) = path {
            let add = self.zoxide_add_folder;
            self.close_zoxide_jump();
            // A zoxide row is a bare line from its database, so it can name a
            // directory in a spelling nothing else in croft uses (a symlinked
            // `/var/…` for `/private/var/…`). Normalise it here, where the
            // untrusted path enters, so both branches agree: the folder store
            // keys on `roots.primary().display()`, and two spellings of one
            // directory would file and restore under different keys.
            // `add_workspace_folder` canonicalises internally; the re-root
            // path must not, since its callers rely on the root being exactly
            // what they passed.
            let path = path.canonicalize().unwrap_or(path);
            if add {
                self.add_workspace_folder(path);
            } else {
                self.change_workspace_root(path);
            }
        }
    }

    fn handle_zoxide_jump_mouse(&mut self, m: MouseEvent) {
        let Some(jump) = self.zoxide_jump.as_mut() else {
            return;
        };
        let inside = rect_contains(jump.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    jump.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    jump.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_zoxide_jump();
            }
            // Click a row to jump to it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = jump.row_index_at(m.row) {
                    jump.selected = idx;
                    self.apply_zoxide_jump_selection();
                }
            }
            _ => {}
        }
    }

    fn render_zoxide_jump(&mut self, frame: &mut ratatui::Frame) {
        let sidebar = self.last_sidebar_area;
        let full = frame.area();
        let theme = self.theme;
        let Some(jump) = self.zoxide_jump.as_mut() else {
            return;
        };
        // Anchor the popup over the Explorer column (it is an Explorer
        // action), dropping from the sidebar's top-left. The sidebar is
        // narrow, so widen the box rightward over the editor for readable
        // paths, capped to the frame. When the sidebar is collapsed there
        // is nothing to anchor to, so fall back to a centered box.
        let rect = match sidebar {
            Some(side) if side.width >= 2 && side.height >= 4 => {
                let width = side
                    .width
                    .max(ZOXIDE_JUMP_MIN_WIDTH)
                    .min(full.width.saturating_sub(side.x));
                Rect {
                    x: side.x,
                    y: side.y,
                    width,
                    height: side.height,
                }
            }
            _ => fallback_popup_rect(full, 100),
        };
        crate::widgets::zoxide_jump::render_zoxide_jump(jump, rect, frame.buffer_mut(), theme);
    }

    fn render_command_history_popup(&mut self, frame: &mut ratatui::Frame) {
        let full = frame.area();
        let theme = self.theme;
        let Some(pop) = self.command_history_popup.as_mut() else {
            return;
        };
        // Centered box, the zoxide-jump fallback geometry: wide enough for
        // command lines, anchored in the upper half like Quick Open.
        let rect = fallback_popup_rect(full, 110);
        crate::widgets::history_popup::render_history_popup(pop, rect, frame.buffer_mut(), theme);
    }

    pub fn consume_branch_picker_image_clear(&mut self) -> bool {
        self.overlays.branch_picker_clear.consume()
    }

    /// Open the Checkout / Create Branch picker, seeded with the repo's
    /// branches (most-recently-committed first). A one-shot `git
    /// for-each-ref` runs here, off the render path — same discipline as
    /// the zoxide jumper. Outside a git repo there is nothing to pick, so
    /// we report that instead of opening an empty box.
    fn open_branch_picker(&mut self) {
        if self.branch_picker.is_some() {
            return;
        }
        self.commit_menu_open = false;
        match crate::git::list_branches(&self.scm_root()) {
            Ok(branches) => {
                let n = branches.len();
                self.branch_picker =
                    Some(crate::widgets::branch_picker::BranchPicker::new(branches));
                self.overlays.branch_picker_clear.request();
                self.status =
                    format!("Branches: {n} — type to filter or name a new branch, Esc to close");
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("branches: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Branch picker: {err}");
            }
        }
    }

    fn close_branch_picker(&mut self) {
        if self.branch_picker.take().is_some() {
            self.overlays.branch_picker_clear.request();
            self.overlays.activity.mark_dirty();
            self.overlays.welcome.mark_dirty();
            self.overlays.hero.mark_dirty();
            self.invalidate_editor_image_layouts();
            self.status.clear();
        }
    }

    /// Run the action the highlighted picker row resolves to: switch to an
    /// existing branch, or create-and-switch a new one. The picker closes
    /// on success; on failure it stays open with the error in the SC
    /// feedback line so the user can amend the name.
    fn apply_branch_action(&mut self, action: crate::widgets::branch_picker::BranchAction) {
        use crate::widgets::branch_picker::BranchAction;
        let (result, verb) = match &action {
            BranchAction::Checkout(name) => (
                crate::git::checkout_branch(&self.scm_root(), name),
                "Switched to",
            ),
            BranchAction::Create(name) => {
                (crate::git::create_branch(&self.scm_root(), name), "Created")
            }
        };
        match result {
            Ok(summary) => {
                self.close_branch_picker();
                self.source_control.commit_feedback = Some(summary.clone());
                self.source_control.commit_feedback_is_error = false;
                self.status = format!("{verb}: {summary}");
                self.active_git_bypass_debounce();
                self.refresh_git_status_debounced();
                self.refresh_source_control();
            }
            Err(err) => {
                self.source_control.commit_feedback = Some(format!("branch: {err}"));
                self.source_control.commit_feedback_is_error = true;
                self.status = format!("Branch: {err}");
            }
        }
    }

    fn handle_branch_picker_key(&mut self, key: KeyEvent) {
        let Some(picker) = self.branch_picker.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_branch_picker(),
            (KeyCode::Enter, _) => self.apply_branch_picker_selection(),
            (KeyCode::Up, _) => picker.select_prev(),
            (KeyCode::Down, _) => picker.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    picker.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    picker.select_next();
                }
            }
            (KeyCode::Left, _) => picker.move_cursor_left(),
            (KeyCode::Right, _) => picker.move_cursor_right(),
            (KeyCode::Home, _) => picker.move_cursor_home(),
            (KeyCode::End, _) => picker.move_cursor_end(),
            (KeyCode::Backspace, _) => picker.pop_char(),
            (KeyCode::Delete, _) => picker.delete_char(),
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                picker.push_char(c);
            }
            _ => {}
        }
    }

    fn handle_branch_picker_mouse(&mut self, m: MouseEvent) {
        let Some(picker) = self.branch_picker.as_mut() else {
            return;
        };
        let inside = rect_contains(picker.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    picker.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    picker.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_branch_picker();
            }
            // Click a row to act on it, the way VS Code's quick-pick behaves.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = picker.row_index_at(m.row) {
                    picker.selected = idx;
                    self.apply_branch_picker_selection();
                }
            }
            _ => {}
        }
    }

    fn render_branch_picker(&mut self, frame: &mut ratatui::Frame) {
        let sidebar = self.last_sidebar_area;
        let full = frame.area();
        let theme = self.theme;
        let Some(picker) = self.branch_picker.as_mut() else {
            return;
        };
        // Anchor over the sidebar column like the jumper (it is a Source
        // Control action), widening rightward for readable branch names;
        // fall back to a centered box when the sidebar is collapsed.
        let rect = match sidebar {
            Some(side) if side.width >= 2 && side.height >= 4 => {
                let width = side
                    .width
                    .max(ZOXIDE_JUMP_MIN_WIDTH)
                    .min(full.width.saturating_sub(side.x));
                Rect {
                    x: side.x,
                    y: side.y,
                    width,
                    height: side.height,
                }
            }
            _ => fallback_popup_rect(full, 100),
        };
        crate::widgets::branch_picker::render_branch_picker(
            picker,
            rect,
            frame.buffer_mut(),
            theme,
        );
    }

    pub fn consume_input_prompt_image_clear(&mut self) -> bool {
        self.overlays.input_prompt_clear.consume()
    }

    pub fn consume_list_picker_image_clear(&mut self) -> bool {
        self.overlays.list_picker_clear.consume()
    }

    fn handle_input_prompt_key(&mut self, key: KeyEvent) {
        let Some(prompt) = self.input_prompt.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_input_prompt(),
            (KeyCode::Enter, _) => self.submit_input_prompt(),
            (KeyCode::Left, _) => prompt.move_cursor_left(),
            (KeyCode::Right, _) => prompt.move_cursor_right(),
            (KeyCode::Home, _) => prompt.move_cursor_home(),
            (KeyCode::End, _) => prompt.move_cursor_end(),
            (KeyCode::Backspace, _) => prompt.pop_char(),
            (KeyCode::Delete, _) => prompt.delete_char(),
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                prompt.push_char(c);
            }
            _ => {}
        }
    }

    fn handle_input_prompt_mouse(&mut self, m: MouseEvent) {
        let Some(prompt) = self.input_prompt.as_ref() else {
            return;
        };
        let inside = rect_contains(prompt.last_rect, m.column, m.row);
        if matches!(
            m.kind,
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
        ) && !inside
        {
            self.close_input_prompt();
        }
    }

    fn render_input_prompt(&mut self, frame: &mut ratatui::Frame) {
        let full = frame.area();
        let theme = self.theme;
        let Some(prompt) = self.input_prompt.as_mut() else {
            return;
        };
        crate::widgets::input_prompt::render_input_prompt(prompt, full, frame.buffer_mut(), theme);
    }

    fn handle_list_picker_key(&mut self, key: KeyEvent) {
        let Some(picker) = self.list_picker.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_list_picker(),
            (KeyCode::Enter, _) => self.confirm_list_picker(),
            (KeyCode::Up, _) => picker.select_prev(),
            (KeyCode::Down, _) => picker.select_next(),
            (KeyCode::PageUp, _) => {
                for _ in 0..10 {
                    picker.select_prev();
                }
            }
            (KeyCode::PageDown, _) => {
                for _ in 0..10 {
                    picker.select_next();
                }
            }
            (KeyCode::Left, _) => picker.move_cursor_left(),
            (KeyCode::Right, _) => picker.move_cursor_right(),
            (KeyCode::Backspace, _) => picker.pop_char(),
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                picker.push_char(c);
            }
            _ => {}
        }
    }

    fn handle_list_picker_mouse(&mut self, m: MouseEvent) {
        let Some(picker) = self.list_picker.as_mut() else {
            return;
        };
        let inside = rect_contains(picker.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => {
                for _ in 0..3 {
                    picker.select_next();
                }
            }
            MouseEventKind::ScrollUp => {
                for _ in 0..3 {
                    picker.select_prev();
                }
            }
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_list_picker();
            }
            // Click a row to select and run it, the way VS Code menus behave.
            MouseEventKind::Down(MouseButton::Left) => {
                if let Some(idx) = picker.row_index_at(m.row) {
                    picker.selected = idx;
                    self.confirm_list_picker();
                }
            }
            _ => {}
        }
    }

    fn render_list_picker(&mut self, frame: &mut ratatui::Frame) {
        let full = frame.area();
        let theme = self.theme;
        let Some(picker) = self.list_picker.as_mut() else {
            return;
        };
        crate::widgets::list_picker::render_list_picker(picker, full, frame.buffer_mut(), theme);
    }

    /// Render the Source Control "⋯" actions menu under the header pill.
    fn render_scm_menu(&mut self, frame: &mut ratatui::Frame) {
        if !self.scm_menu.open || self.sidebar_view != SidebarView::SourceControl {
            self.scm_menu.close();
            return;
        }
        let anchor = self.source_control.header_more_btn;
        if anchor.width == 0 {
            return;
        }
        let screen = frame.area();
        crate::widgets::scm_menu::render(
            &mut self.scm_menu,
            anchor,
            screen,
            frame.buffer_mut(),
            self.theme,
        );
    }

    fn open_editor_find(&mut self) {
        // A hex tab's find is the byte-query popup, not the text bar
        // (#172): route there whether the chord or the palette got here.
        if self.editor.hex.is_some() {
            self.open_hex_find_prompt();
            return;
        }
        if self.editor_find.is_some() {
            return;
        }
        let opts = self.search.opts;
        if self.editor.diff.is_some() {
            let initial = self
                .editor
                .diff
                .as_ref()
                .and_then(|d| d.selection_text())
                .filter(|s| !s.contains('\n'))
                .unwrap_or_default();
            self.editor_find = Some(crate::widgets::editor_find::EditorFind::new(
                String::new(),
                opts,
            ));
            if !initial.is_empty() {
                self.diff_find_set_query(initial);
            }
            self.status =
                String::from("Find: type to search, Enter next, Shift+Enter prev, Esc close");
            return;
        }
        let initial = if !self.editor.selection_text().is_empty()
            && !self.editor.selection_text().contains('\n')
        {
            self.editor.selection_text()
        } else {
            self.editor.word_before_cursor()
        };
        let mut state = crate::widgets::editor_find::EditorFind::new(initial.clone(), opts);
        if !initial.is_empty() {
            state.set_match_count(
                crate::widgets::editor_find::count_matches(&self.editor.lines, &initial, opts),
                false,
            );
            self.editor
                .set_search_highlight(Some(initial.clone()), opts);
        }
        self.editor_find = Some(state);
        self.status = String::from("Find: type to search, Enter next, Shift+Enter prev, Esc close");
    }

    /// Cmd+F in the terminal: open a find bar that searches the active pane's
    /// grid + scrollback (iTerm2 / Ghostty scrollback search). Seeds from a
    /// single-line selection and lands on the most recent match.
    fn open_terminal_find(&mut self) {
        if self.terminal_find.is_some() {
            return;
        }
        let opts = self.search.opts;
        let sel = self.terminal().selection_text();
        let initial = if !sel.is_empty() && !sel.contains('\n') {
            sel
        } else {
            String::new()
        };
        let (lines, _top) = self.terminal().grid_lines();
        let mut state = crate::widgets::editor_find::EditorFind::new(initial.clone(), opts);
        state.set_match_count(
            crate::widgets::editor_find::count_matches(&lines, &initial, opts),
            false,
        );
        self.terminal_find = Some(state);
        self.terminal_find_pane = self.active_terminal;
        self.terminal_find_match = None;
        self.terminal_mut()
            .set_search((!initial.is_empty()).then(|| initial.clone()), opts);
        self.status = String::from(
            "Find in terminal: type to search, Enter next, Shift+Enter prev, Esc close",
        );
        if !initial.is_empty() {
            // Land on the bottom-most (most recent) match, like iTerm2.
            self.terminal_find_jump(false);
        }
    }

    /// Make pane `idx` the active terminal, tearing down the overlays that
    /// were bound to the pane being left.
    ///
    /// Shared by the built-in click path and the bound-gesture dispatch so
    /// the two cannot drift: every terminal helper reaches the grid through
    /// `self.terminal()`, which indexes `active_terminal`, so a caller that
    /// skips this reads a pane the user did not click. That is not
    /// hypothetical — a bound `mouse_open_link_at_click` reported "No link
    /// there" over a plainly visible URL in a split, because the dispatch
    /// returned above the assignment the built-in makes.
    fn activate_terminal_pane(&mut self, idx: usize) {
        if self.active_terminal == idx {
            return;
        }
        // Copy mode is bound to the pane it opened on; a click on a sibling
        // pane leaves it, tmux-style, rather than hijacking the new pane's
        // grid.
        if self
            .terminal_copy_mode
            .as_ref()
            .is_some_and(|st| st.pane != idx)
        {
            self.close_terminal_copy_mode();
        }
        // Quick-select labels are pane-bound the same way.
        if self
            .terminal_quick_select
            .as_ref()
            .is_some_and(|st| st.pane != idx)
        {
            self.close_terminal_quick_select();
        }
        // As is the find bar and its highlight.
        if self.terminal_find.is_some() && self.terminal_find_pane != idx {
            self.close_terminal_find();
        }
        self.active_terminal = idx;
    }

    fn close_terminal_find(&mut self) {
        if self.terminal_find.take().is_some() {
            self.terminal_find_match = None;
            let opts = self.search.opts;
            // Clear every pane, not just the active one: the close may be
            // the pane-binding invariant firing after `active_terminal`
            // already moved off the pane that owns the highlight.
            for t in &mut self.terminals {
                t.set_search(None, opts);
                t.set_current_match(None, 0);
            }
        }
    }

    /// Re-run the terminal search after the query changed: recount,
    /// re-highlight every occurrence, and re-anchor on the most recent match.
    fn terminal_find_set_query(&mut self, new_query: String) {
        let opts = self.search.opts;
        let (lines, _top) = self.terminal().grid_lines();
        let count = crate::widgets::editor_find::count_matches(&lines, &new_query, opts);
        if let Some(state) = self.terminal_find.as_mut() {
            state.query = new_query.clone();
            state.set_match_count(count, false);
            state.match_index = None;
        }
        self.terminal_find_match = None;
        self.terminal_mut()
            .set_search((!new_query.is_empty()).then(|| new_query.clone()), opts);
        self.terminal_mut().set_current_match(None, 0);
        if !new_query.is_empty() {
            self.terminal_find_jump(false);
        }
    }

    /// Move to the next (`forward`) or previous match, wrapping. Scrolls the
    /// pane so the match is visible, marks it active, and updates the "N of M"
    /// index. Navigation walks from the current match, or — on the first jump —
    /// from the bottom of the buffer so the newest occurrence wins.
    fn terminal_find_jump(&mut self, forward: bool) {
        let Some(state) = self.terminal_find.as_ref() else {
            return;
        };
        let needle = state.query.clone();
        let opts = state.opts;
        if needle.is_empty() {
            return;
        }
        let (lines, top, now) = self.terminal().grid_lines_and_clock();
        if lines.is_empty() {
            return;
        }
        let anchor = self.terminal_find_match;
        let (from_row, from_col) = match anchor {
            Some((clock, abs, col, _len)) => {
                // Re-base the stored line by the rows scrolled since it was
                // anchored, so navigation walks from the match's TEXT, not
                // from the viewport row it occupied at anchor time.
                let abs = abs - (now - clock) as i32;
                let row = (abs - top).clamp(0, lines.len() as i32 - 1) as usize;
                (row, col)
            }
            // No anchor: start past the last line's end so `prev` lands on the
            // bottom-most match and `next` wraps to the top-most.
            None => (lines.len().saturating_sub(1), usize::MAX),
        };
        let skip_current = anchor.is_some();
        let m = if forward {
            crate::widgets::editor_find::find_next_match(
                &lines,
                &needle,
                opts,
                from_row,
                from_col,
                skip_current,
            )
        } else {
            crate::widgets::editor_find::find_prev_match(
                &lines,
                &needle,
                opts,
                from_row,
                from_col,
                skip_current,
            )
        };
        let Some(m) = m else {
            return;
        };
        let abs_line = top + m.row as i32;
        self.terminal_find_match = Some((now, abs_line, m.col_chars, m.len_chars));
        self.terminal_mut()
            .set_current_match(Some((abs_line, m.col_chars, m.len_chars)), now);
        self.terminal_mut().scroll_to_line(abs_line);
        let idx =
            crate::widgets::editor_find::match_index_at(&lines, &needle, opts, m.row, m.col_chars);
        if let Some(state) = self.terminal_find.as_mut() {
            state.match_index = idx;
        }
    }

    fn handle_terminal_find_key(&mut self, key: KeyEvent) {
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_terminal_find(),
            (KeyCode::Enter, _) | (KeyCode::F(3), _) => {
                self.terminal_find_jump(!shift);
            }
            (KeyCode::Backspace, _) => {
                let mut q = self
                    .terminal_find
                    .as_ref()
                    .map(|s| s.query.clone())
                    .unwrap_or_default();
                q.pop();
                self.terminal_find_set_query(q);
            }
            (KeyCode::Char('v'), m)
                if m.contains(KeyModifiers::CONTROL) || m.contains(KeyModifiers::SUPER) =>
            {
                if let Some(text) = (self.clipboard_reader)() {
                    let mut q = self
                        .terminal_find
                        .as_ref()
                        .map(|s| s.query.clone())
                        .unwrap_or_default();
                    for c in text.chars() {
                        if !c.is_control() {
                            q.push(c);
                        }
                    }
                    self.terminal_find_set_query(q);
                }
            }
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                let mut q = self
                    .terminal_find
                    .as_ref()
                    .map(|s| s.query.clone())
                    .unwrap_or_default();
                q.push(c);
                self.terminal_find_set_query(q);
            }
            _ => {}
        }
    }

    /// Ctrl+Shift+Space: enter quick-select on the active pane. Scans the
    /// visible viewport for URLs / paths / hashes / IPs (see
    /// [`crate::quick_select`]), assigns home-row labels with the bottom-most
    /// match getting the cheapest one (WezTerm / tmux-thumbs), and overlays
    /// them for the render loop.
    fn open_terminal_quick_select(&mut self) {
        let (lines, wraps, top, clock) = self.terminal_mut().visible_lines_and_clock();
        let mut matches = crate::quick_select::find_matches_wrapped(&lines, &wraps);
        // A hex run or a number inside a masked span would be a fragment of
        // the secret one keystroke from the clipboard (#360): no hint there.
        if self.triggers.has_redactions() && !self.redactions_revealed() {
            let clear = |row: usize, start: usize, len: usize| {
                lines.get(row).is_none_or(|line| {
                    crate::triggers::redact_spans(line, &self.triggers)
                        .iter()
                        .all(|s| start + len <= s.start || start >= s.start + s.len)
                })
            };
            // A match that wraps the pane edge continues in `tail`; every
            // segment must be clear, or the fragment past the wrap leaks.
            matches.retain(|m| {
                clear(m.row, m.start, m.len) && m.tail.iter().all(|&(r, s, l)| clear(r, s, l))
            });
        }
        if matches.is_empty() {
            self.status = String::from("Quick select: nothing to match on screen");
            return;
        }
        let labels =
            crate::quick_select::assign_labels(matches.len(), crate::quick_select::ALPHABET);
        let dropped = matches.len().saturating_sub(labels.len());
        let hints: Vec<QuickHint> = crate::quick_select::label_matches(matches, &labels)
            .into_iter()
            .map(|(m, label)| QuickHint {
                line: top + m.row as i32,
                start: m.start,
                len: m.len,
                text: m.text,
                label,
                tail: m
                    .tail
                    .iter()
                    .map(|&(r, s, l)| (top + r as i32, s, l))
                    .collect(),
            })
            .collect();
        self.push_quick_select_hints(&hints, "", clock);
        self.terminal_quick_select = Some(QuickSelectState {
            pane: self.active_terminal,
            clock,
            hints,
            typed: String::new(),
            shifted: false,
        });
        self.status = if dropped > 0 {
            format!(
                "Quick select: type a label to copy, UPPERCASE pastes, Esc cancels ({dropped} top matches unlabelled)"
            )
        } else {
            String::from("Quick select: type a label to copy, UPPERCASE pastes, Esc cancels")
        };
    }

    /// Push the hint spans matching the typed label prefix down to the pane
    /// for painting. Called on open and after every typed / erased char.
    fn push_quick_select_hints(&mut self, hints: &[QuickHint], typed: &str, clock: i64) {
        let spans: Vec<crate::widgets::terminal::HintSpan> = hints
            .iter()
            .filter(|h| h.label.starts_with(typed))
            .flat_map(|h| {
                // The head span carries the label glyph; a wrapped match's
                // tail segments highlight their continuation rows with the
                // label fully "typed" so no glyph ever paints on them.
                std::iter::once(crate::widgets::terminal::HintSpan {
                    line: h.line,
                    start: h.start,
                    len: h.len,
                    label: h.label.clone(),
                    typed: typed.len(),
                })
                .chain(h.tail.iter().map(|&(line, start, len)| {
                    crate::widgets::terminal::HintSpan {
                        line,
                        start,
                        len,
                        label: h.label.clone(),
                        typed: h.label.len(),
                    }
                }))
            })
            .collect();
        self.terminal_mut().set_hints(Some(spans), clock);
    }

    fn close_terminal_quick_select(&mut self) {
        if self.terminal_quick_select.take().is_some() {
            // Clear every pane, not just the active one: a mouse click can
            // move `active_terminal` while the labels are still up.
            for t in &mut self.terminals {
                t.set_hints(None, 0);
            }
        }
    }

    /// Ctrl+Shift+Y: enter copy mode on the active pane. The cursor starts
    /// at the shell's cursor cell (WezTerm's convention) and the pane paints
    /// it as a green modal block.
    fn open_terminal_copy_mode(&mut self) {
        // Cursor, bounds, and clock from ONE snapshot (see
        // `begin_annotate_terminal` for why the pairing must be atomic).
        let ((line, col), (top, bottom, cols, _), clock) =
            self.terminal_mut().cursor_bounds_and_clock();
        let line = line.clamp(top, bottom);
        let col = col.min(cols.saturating_sub(1));
        self.terminal_mut().set_copy_cursor(Some((line, col)));
        self.terminal_copy_mode = Some(CopyModeState {
            pane: self.active_terminal,
            line,
            col,
            anchor: None,
            kind: CopySelKind::Char,
            clock,
        });
        self.status = String::from(
            "Copy mode: h/j/k/l w/b/e 0/$ g/G move, v/V/^V select, y copies, Esc exits",
        );
    }

    fn close_terminal_copy_mode(&mut self) {
        if self.terminal_copy_mode.take().is_some() {
            // Clear every pane, not just the active one: a mouse click can
            // move `active_terminal` while the mode is up.
            for t in &mut self.terminals {
                t.set_copy_cursor(None);
                t.clear_selection();
            }
        }
    }

    /// Push the copy-mode cursor + selection into the pane and keep the
    /// cursor on screen (centering only when it left the viewport).
    fn apply_terminal_copy_mode(&mut self) {
        let Some(st) = self.terminal_copy_mode.as_ref() else {
            return;
        };
        // Bound to its own pane — never paint another pane's grid (see
        // `handle_terminal_copy_mode_key`).
        if st.pane != self.active_terminal {
            self.close_terminal_copy_mode();
            return;
        }
        let (line, col) = (st.line, st.col);
        let (_, _, cols, rows) = self.terminal().grid_bounds();
        let sel = st.anchor.map(|(al, ac)| match st.kind {
            CopySelKind::Char => crate::widgets::terminal::Selection {
                anchor: (al, ac),
                head: (line, col),
                block: false,
            },
            CopySelKind::Line => crate::widgets::terminal::Selection {
                anchor: (al.min(line), 0),
                head: (al.max(line), cols.saturating_sub(1)),
                block: false,
            },
            CopySelKind::Block => crate::widgets::terminal::Selection {
                anchor: (al, ac),
                head: (line, col),
                block: true,
            },
        });
        let off = self.terminal().scroll_display_offset();
        let visible = (-off, rows as i32 - 1 - off);
        let t = self.terminal_mut();
        t.set_selection(sel);
        t.set_copy_cursor(Some((line, col)));
        if line < visible.0 || line > visible.1 {
            t.scroll_to_line(line);
        }
    }

    /// The char index in `text` whose grid column covers `col` (the last
    /// char whose start column is <= col), for word motions over the
    /// spacer-skipped row text.
    fn char_idx_at_col(colmap: &[usize], col: u16) -> usize {
        let col = col as usize;
        match colmap.binary_search(&col) {
            Ok(i) => i,
            Err(0) => 0,
            Err(i) => i - 1,
        }
    }

    fn handle_terminal_copy_mode_key(&mut self, key: KeyEvent) {
        let Some(mut st) = self.terminal_copy_mode.take() else {
            return;
        };
        // The mode is bound to the pane it opened on: if a gesture moved
        // `active_terminal` since (a click on a sibling pane), the stored
        // coordinates and clock describe the wrong pane — close instead of
        // folding another pane's clock into them.
        if st.pane != self.active_terminal {
            self.terminal_copy_mode = Some(st);
            self.close_terminal_copy_mode();
            return;
        }
        // Content streamed since the last key: fold the scroll-clock
        // movement into the stored coordinates so this keystroke moves
        // from where the pane's re-anchored highlight actually is.
        let now = self.terminal_mut().scroll_clock();
        let drift = (now - st.clock) as i32;
        if drift != 0 {
            st.line -= drift;
            if let Some(a) = st.anchor.as_mut() {
                a.0 -= drift;
            }
            st.clock = now;
        }
        let (top, bottom, cols, rows) = self.terminal().grid_bounds();
        // Content that fell off the scrollback pins to the oldest line,
        // mirroring the pane's own rebase.
        st.line = st.line.clamp(top, bottom);
        if let Some(a) = st.anchor.as_mut() {
            a.0 = a.0.clamp(top, bottom);
        }
        let last_col = cols.saturating_sub(1);
        let half = (rows as i32 / 2).max(1);
        let page = (rows as i32 - 1).max(1);
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let word = crate::widgets::terminal::is_terminal_word_char;
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                self.terminal_copy_mode = Some(st);
                self.close_terminal_copy_mode();
                self.status = String::from("Copy mode off");
                return;
            }
            KeyCode::Char('y') | KeyCode::Enter => {
                let text = self.terminal_text_for_copy(self.terminal().selection_text());
                self.terminal_copy_mode = Some(st);
                self.close_terminal_copy_mode();
                if text.is_empty() {
                    self.status =
                        String::from("Copy mode: nothing selected (v/V/^V starts a selection)");
                } else {
                    copy_to_clipboard(&text);
                    self.status = format!("Copied {} chars to clipboard", text.chars().count());
                }
                return;
            }
            // Selection arms: v again (same kind) drops the anchor, a
            // different kind reshapes the existing selection in place.
            KeyCode::Char('v') if ctrl => {
                if st.anchor.is_some() && st.kind == CopySelKind::Block {
                    st.anchor = None;
                } else {
                    st.anchor.get_or_insert((st.line, st.col));
                    st.kind = CopySelKind::Block;
                }
            }
            KeyCode::Char('v') => {
                if st.anchor.is_some() && st.kind == CopySelKind::Char {
                    st.anchor = None;
                } else {
                    st.anchor.get_or_insert((st.line, st.col));
                    st.kind = CopySelKind::Char;
                }
            }
            KeyCode::Char('V') => {
                if st.anchor.is_some() && st.kind == CopySelKind::Line {
                    st.anchor = None;
                } else {
                    st.anchor.get_or_insert((st.line, st.col));
                    st.kind = CopySelKind::Line;
                }
            }
            KeyCode::Char('h') | KeyCode::Left => st.col = st.col.saturating_sub(1),
            KeyCode::Char('l') | KeyCode::Right => st.col = (st.col + 1).min(last_col),
            KeyCode::Char('j') | KeyCode::Down => st.line = (st.line + 1).min(bottom),
            KeyCode::Char('k') | KeyCode::Up => st.line = (st.line - 1).max(top),
            KeyCode::Char('0') | KeyCode::Home => st.col = 0,
            KeyCode::Char('$') | KeyCode::End => {
                let (text, colmap) = self.terminal().row_text(st.line);
                let trimmed = text.trim_end();
                let chars = trimmed.chars().count();
                st.col = if chars == 0 {
                    0
                } else {
                    colmap.get(chars - 1).map_or(0, |&c| c as u16)
                };
            }
            KeyCode::Char('g') => st.line = top,
            KeyCode::Char('G') => st.line = bottom,
            KeyCode::Char('u') if ctrl => st.line = (st.line - half).max(top),
            KeyCode::Char('d') if ctrl => st.line = (st.line + half).min(bottom),
            KeyCode::PageUp => st.line = (st.line - page).max(top),
            KeyCode::PageDown => st.line = (st.line + page).min(bottom),
            KeyCode::Char('w') => {
                let (text, colmap) = self.terminal().row_text(st.line);
                let chars: Vec<char> = text.chars().collect();
                let mut i = Self::char_idx_at_col(&colmap, st.col);
                while i < chars.len() && word(chars[i]) {
                    i += 1;
                }
                while i < chars.len() && !word(chars[i]) {
                    i += 1;
                }
                // Trailing blanks reach the row's end: wrap to the next row
                // start like vim's w does at end of line.
                if i >= text.trim_end().chars().count() && st.line < bottom {
                    st.line += 1;
                    st.col = 0;
                } else {
                    st.col = colmap.get(i).map_or(last_col, |&c| c as u16);
                }
            }
            KeyCode::Char('b') => {
                let (text, colmap) = self.terminal().row_text(st.line);
                let chars: Vec<char> = text.chars().collect();
                let mut i = Self::char_idx_at_col(&colmap, st.col);
                if i == 0 {
                    if st.line > top {
                        st.line -= 1;
                        let (ptext, pcolmap) = self.terminal().row_text(st.line);
                        let pchars = ptext.trim_end().chars().count();
                        st.col = if pchars == 0 {
                            0
                        } else {
                            pcolmap.get(pchars - 1).map_or(0, |&c| c as u16)
                        };
                    }
                } else {
                    i -= 1;
                    while i > 0 && !word(chars[i]) {
                        i -= 1;
                    }
                    while i > 0 && word(chars[i - 1]) {
                        i -= 1;
                    }
                    st.col = colmap.get(i).map_or(0, |&c| c as u16);
                }
            }
            KeyCode::Char('e') => {
                let (text, colmap) = self.terminal().row_text(st.line);
                let chars: Vec<char> = text.chars().collect();
                let content = text.trim_end().chars().count();
                let mut i = Self::char_idx_at_col(&colmap, st.col);
                i += 1;
                while i < chars.len() && !word(chars[i]) {
                    i += 1;
                }
                // Past the last word on this row (the scan ran into the
                // trailing padding): hop to the next row's first word end,
                // like vim's `e` at end of line — `w` and `b` both wrap,
                // and without this `e` was a dead key at the row's last word.
                if i >= content && st.line < bottom {
                    // Word-less rows are skipped like vim: `e` lands on the
                    // end of the next word wherever it lives below, and only
                    // falls back to the next row's column 0 when nothing
                    // down to the bottom has a word.
                    let mut landed = None;
                    let mut line = st.line + 1;
                    while line <= bottom {
                        let (ntext, ncolmap) = self.terminal().row_text(line);
                        let nchars: Vec<char> = ntext.chars().collect();
                        let mut j = 0;
                        while j < nchars.len() && !word(nchars[j]) {
                            j += 1;
                        }
                        if j < nchars.len() && word(nchars[j]) {
                            while j + 1 < nchars.len() && word(nchars[j + 1]) {
                                j += 1;
                            }
                            landed = Some((line, ncolmap.get(j).map_or(0, |&c| c as u16)));
                            break;
                        }
                        line += 1;
                    }
                    (st.line, st.col) = landed.unwrap_or((st.line + 1, 0));
                } else {
                    while i + 1 < chars.len() && word(chars[i + 1]) {
                        i += 1;
                    }
                    if i < chars.len() {
                        st.col = colmap.get(i).map_or(last_col, |&c| c as u16);
                    }
                }
            }
            _ => {}
        }
        st.line = st.line.clamp(top, bottom);
        st.col = st.col.min(last_col);
        self.terminal_copy_mode = Some(st);
        self.apply_terminal_copy_mode();
    }

    fn handle_terminal_quick_select_key(&mut self, key: KeyEvent) {
        // Bound to its origin pane: if anything moved the active pane while
        // the labels were up, close instead of pushing (or pasting) the old
        // pane's coordinates and text into the new one.
        if self
            .terminal_quick_select
            .as_ref()
            .is_some_and(|st| st.pane != self.active_terminal)
        {
            self.close_terminal_quick_select();
            return;
        }
        match key.code {
            KeyCode::Esc => {
                self.close_terminal_quick_select();
                self.status = String::from("Quick select cancelled");
            }
            KeyCode::Backspace => {
                let Some(state) = self.terminal_quick_select.as_mut() else {
                    return;
                };
                state.typed.pop();
                // Case history is not kept; retyping decides paste-vs-copy.
                state.shifted = false;
                let (hints, typed, clock) = (state.hints.clone(), state.typed.clone(), state.clock);
                self.push_quick_select_hints(&hints, &typed, clock);
            }
            KeyCode::Char(c) if c.is_ascii_alphabetic() => {
                let Some(state) = self.terminal_quick_select.as_ref() else {
                    return;
                };
                let candidate = format!("{}{}", state.typed, c.to_ascii_lowercase());
                let shifted = state.shifted || c.is_ascii_uppercase();
                if let Some(hit) = state.hints.iter().find(|h| h.label == candidate) {
                    // A hint can land inside a masked span (a hex run, a
                    // number); the clipboard rule applies here too (#360).
                    let text = self.terminal_text_for_copy(hit.text.clone());
                    self.close_terminal_quick_select();
                    copy_to_clipboard(&text);
                    if shifted {
                        self.terminal_mut().paste_input(text.as_bytes());
                        self.status = format!(
                            "Copied {} chars to clipboard and pasted into the shell",
                            text.chars().count()
                        );
                    } else {
                        self.status = format!("Copied {} chars to clipboard", text.chars().count());
                    }
                } else if state.hints.iter().any(|h| h.label.starts_with(&candidate)) {
                    let Some(state) = self.terminal_quick_select.as_mut() else {
                        return;
                    };
                    state.typed = candidate.clone();
                    state.shifted = shifted;
                    let (hints, clock) = (state.hints.clone(), state.clock);
                    self.push_quick_select_hints(&hints, &candidate, clock);
                }
                // A char no label starts with is ignored, like WezTerm.
            }
            _ => {}
        }
    }

    /// `Cmd+Opt+F` (VS Code `editor.action.startFindReplaceAction`): open
    /// the find bar expanded with the replace row, or toggle the row on an
    /// already-open bar. Read-only tabs (diff / sheet / image previews)
    /// get the plain find bar — there is nothing to replace into.
    fn open_editor_replace(&mut self) {
        if !self.editor_is_text() {
            self.open_editor_find();
            return;
        }
        if self.editor_find.is_none() {
            self.open_editor_find();
        }
        let Some(state) = self.editor_find.as_mut() else {
            return;
        };
        state.replace_visible = !state.replace_visible;
        state.focus = if state.replace_visible && !state.query.is_empty() {
            crate::widgets::editor_find::FindField::Replace
        } else {
            crate::widgets::editor_find::FindField::Query
        };
        if state.replace_visible {
            self.status = String::from(
                "Replace: Tab switches field, Enter replaces, Cmd+Opt+Enter replaces all, Esc close",
            );
        }
    }

    fn close_editor_find(&mut self) {
        if self.editor_find.take().is_some() {
            self.editor.set_search_highlight(None, self.search.opts);
            if let Some(diff) = self.editor.diff.as_mut() {
                diff.find.needle = None;
                diff.find.active = None;
            }
            self.status.clear();
        }
    }

    /// Viewport geometry (visible rows, visible text columns) of the diff
    /// body, derived from the last rendered inner rect the same way
    /// `render_diff` lays the columns out. Used to keep a jumped-to match
    /// on screen.
    fn diff_find_viewport(&self) -> (usize, usize) {
        let inner = self.editor.last_inner;
        let viewport_rows = (inner.height as usize).saturating_sub(2);
        let half = inner.width / 2;
        let text_cols = match self.editor.diff.as_ref() {
            Some(diff) => {
                let r_gutter = (diff.right_lines.len() + 1).to_string().len() as u16 + 1;
                inner
                    .width
                    .saturating_sub(half + 1)
                    .saturating_sub(r_gutter + 2) as usize
            }
            None => 0,
        };
        (viewport_rows, text_cols)
    }

    /// Recompute the diff's matches for the current query, select the
    /// match at `target` (wrapping), scroll it into view, and sync the
    /// find bar's count / index. Drives every diff find action.
    fn diff_find_apply(&mut self, target: usize) {
        let (needle, opts) = match self.editor_find.as_ref() {
            Some(s) => (s.query.clone(), s.opts),
            None => return,
        };
        let (viewport_rows, text_cols) = self.diff_find_viewport();
        let Some(diff) = self.editor.diff.as_mut() else {
            return;
        };
        diff.find.opts = opts;
        if needle.is_empty() {
            diff.find.needle = None;
            diff.find.active = None;
            if let Some(s) = self.editor_find.as_mut() {
                s.set_match_count(0, false);
                s.match_index = None;
            }
            return;
        }
        diff.find.needle = Some(needle.clone());
        let matches = diff.find_matches(&needle, opts);
        let count = matches.len();
        if count == 0 {
            diff.find.active = None;
            if let Some(s) = self.editor_find.as_mut() {
                s.set_match_count(0, false);
                s.match_index = None;
            }
            return;
        }
        let pos = target % count;
        let m = matches[pos];
        diff.find.active = Some(m);
        diff.scroll_to_match(m, viewport_rows, text_cols);
        if let Some(s) = self.editor_find.as_mut() {
            s.set_match_count(count, false);
            s.match_index = Some(pos + 1);
        }
    }

    fn diff_find_set_query(&mut self, new_query: String) {
        if let Some(s) = self.editor_find.as_mut() {
            s.query = new_query;
        }
        self.diff_find_apply(0);
    }

    fn diff_find_current_pos(&self) -> usize {
        self.editor_find
            .as_ref()
            .and_then(|s| s.match_index)
            .map(|i| i.saturating_sub(1))
            .unwrap_or(0)
    }

    fn editor_find_set_query(&mut self, new_query: String) {
        let unchanged = self
            .editor_find
            .as_ref()
            .map(|s| s.query == new_query)
            .unwrap_or(true);
        if unchanged {
            return;
        }
        if self.editor.diff.is_some() {
            self.diff_find_set_query(new_query);
            return;
        }
        if self.editor.log.is_some() {
            self.log_find_set_query(new_query);
            return;
        }
        let Some(state) = self.editor_find.as_mut() else {
            return;
        };
        state.query = new_query;
        let opts = state.opts;
        state.set_match_count(
            crate::widgets::editor_find::count_matches(&self.editor.lines, &state.query, opts),
            false,
        );
        if state.query.is_empty() {
            state.match_index = None;
            self.editor.active_search_match = None;
            self.editor.set_search_highlight(None, opts);
            return;
        }
        self.editor
            .set_search_highlight(Some(state.query.clone()), opts);
        let from_row = self.editor.cursor_row;
        let from_col = self.editor.cursor_col;
        if let Some(m) = crate::widgets::editor_find::find_next_match(
            &self.editor.lines,
            &state.query,
            opts,
            from_row,
            from_col,
            false,
        ) {
            self.jump_editor_to_match(m);
        }
        self.refresh_editor_find_index();
    }

    fn editor_find_jump_next(&mut self) {
        let Some(state) = self.editor_find.as_ref() else {
            return;
        };
        if state.query.is_empty() {
            return;
        }
        if self.editor.diff.is_some() {
            self.diff_find_apply(self.diff_find_current_pos() + 1);
            return;
        }
        if self.editor.log.is_some() {
            self.log_find_step(true);
            return;
        }
        let opts = state.opts;
        let needle = state.query.clone();
        if let Some(m) = crate::widgets::editor_find::find_next_match(
            &self.editor.lines,
            &needle,
            opts,
            self.editor.cursor_row,
            self.editor.cursor_col,
            true,
        ) {
            self.jump_editor_to_match(m);
            self.refresh_editor_find_index();
        }
    }

    fn editor_find_jump_prev(&mut self) {
        let Some(state) = self.editor_find.as_ref() else {
            return;
        };
        if state.query.is_empty() {
            return;
        }
        if self.editor.diff.is_some() {
            let count = state.match_count;
            if count == 0 {
                return;
            }
            self.diff_find_apply(self.diff_find_current_pos() + count - 1);
            return;
        }
        if self.editor.log.is_some() {
            self.log_find_step(false);
            return;
        }
        let opts = state.opts;
        let needle = state.query.clone();
        if let Some(m) = crate::widgets::editor_find::find_prev_match(
            &self.editor.lines,
            &needle,
            opts,
            self.editor.cursor_row,
            self.editor.cursor_col,
            true,
        ) {
            self.jump_editor_to_match(m);
            self.refresh_editor_find_index();
        }
    }

    /// Find over a rendered ANSI log (#257).
    ///
    /// A log tab's `lines` is a one-line stub, because the file stays on disk
    /// and only a window of it is ever parsed. Running the ordinary find path
    /// over that stub answers "No results" for a file full of matches, so the
    /// search goes through the view's own stripped text instead, the same fork
    /// the diff view already takes.
    fn log_find_set_query(&mut self, new_query: String) {
        let Some(state) = self.editor_find.as_mut() else {
            return;
        };
        state.query = new_query;
        let opts = state.opts;
        let needle = state.query.clone();
        if needle.is_empty() {
            state.set_match_count(0, false);
            state.match_index = None;
            self.editor.active_search_match = None;
            self.editor.set_search_highlight(None, opts);
            return;
        }
        let Some(log) = self.editor.log.as_ref() else {
            return;
        };
        let (count, truncated) = log.count_matches(&needle, opts);
        // Search from the top of the viewport, so typing finds what is on
        // screen first rather than jumping to the head of the file.
        let hit = log.find_next(&needle, opts, self.editor.scroll, 0, false);
        if let Some(state) = self.editor_find.as_mut() {
            state.set_match_count(count, truncated);
            // "N of M" would have to count the matches BEFORE this one, which
            // for a budgeted scan is a number we may not have; the bar falls
            // back to "M matches" rather than guessing an index.
            state.match_index = None;
        }
        self.editor.set_search_highlight(Some(needle), opts);
        // A CHANGED query invalidates the old position outright, so the
        // active match is cleared before the new step is applied. The early
        // return for an out-of-reach STEP deliberately keeps the match the
        // user was on; doing the same here left the previous query's
        // highlight painted under a new query that could not reach a match
        // of its own.
        self.editor.active_search_match = None;
        self.scroll_log_to_match(hit);
    }

    /// Fold in the background index of an open rendered log (#394).
    ///
    /// Returns whether a repaint is due: the header's line count and the
    /// scroll range moved. When the pass finishes, an open find bar has its
    /// count re-run, since the count it shows was taken against a partial
    /// index and flagged as such; a step the user makes next reaches the
    /// tail on its own.
    pub fn poll_log_index(&mut self) -> bool {
        let Some(log) = self.editor.log.as_mut() else {
            return false;
        };
        if !log.indexing() {
            return false;
        }
        let changed = log.poll_index();
        if log.indexing() {
            return changed;
        }
        if let Some(state) = self.editor_find.as_ref()
            && !state.query.is_empty()
        {
            let (count, truncated) = log.count_matches(&state.query, state.opts);
            if let Some(state) = self.editor_find.as_mut() {
                state.set_match_count(count, truncated);
            }
        }
        true
    }

    /// Enter / Shift+Enter over a rendered log.
    fn log_find_step(&mut self, forward: bool) {
        let Some(state) = self.editor_find.as_ref() else {
            return;
        };
        let opts = state.opts;
        let needle = state.query.clone();
        let Some(log) = self.editor.log.as_ref() else {
            return;
        };
        // With no active match, walk from the viewport rather than the file
        // head, so the first step lands near what the user is looking at.
        let (row, col) = match self.editor.active_search_match {
            Some((r, c, _)) => (r, c),
            None => (self.editor.scroll, 0),
        };
        let hit = if forward {
            log.find_next(&needle, opts, row, col, true)
        } else {
            log.find_prev(&needle, opts, row, col)
        };
        self.scroll_log_to_match(hit);
    }

    /// Park the viewport on the step's match and mark it active. A log has
    /// no caret, so the match position is carried by `active_search_match`
    /// alone and the row is centred rather than merely revealed.
    ///
    /// A step that ran out of budget is NOT the same as one that found
    /// nothing: it leaves the count marked partial, so the bar keeps saying
    /// how far the search actually reached instead of claiming "No results"
    /// for a file it never finished reading.
    fn scroll_log_to_match(&mut self, step: crate::log_view::Step) {
        if step.out_of_reach() {
            // Mark the count partial and STOP. Falling through to clear the
            // active match left the bar reading "1+ matches" with nothing
            // highlighted and no way back to the match the user was on: a
            // step that could not reach further must leave them where they
            // are, not throw away the position it did have.
            if let Some(state) = self.editor_find.as_mut() {
                let count = state.match_count;
                state.set_match_count(count, true);
            }
            return;
        }
        let Some(m) = step.found() else {
            self.editor.active_search_match = None;
            return;
        };
        self.editor.active_search_match = Some((m.row, m.col_chars, m.len_chars));
        // The log body starts one row below the header.
        let rows = (self.editor.last_inner.height as usize).saturating_sub(1);
        if rows == 0 {
            self.editor.scroll = m.row;
            return;
        }
        if m.row < self.editor.scroll || m.row >= self.editor.scroll + rows {
            self.editor.scroll = m.row.saturating_sub(rows / 2);
        }
    }

    fn jump_editor_to_match(&mut self, m: crate::widgets::editor_find::MatchPos) {
        self.editor.cursor_row = m.row;
        self.editor.cursor_col = m.col_chars;
        self.editor.active_search_match = Some((m.row, m.col_chars, m.len_chars));
        let viewport = self.editor.last_inner.height as usize;
        if viewport > 0 {
            if self.editor.cursor_row < self.editor.scroll {
                self.editor.scroll = self.editor.cursor_row;
            } else if self.editor.cursor_row >= self.editor.scroll + viewport {
                self.editor.scroll = self.editor.cursor_row + 1 - viewport;
            }
        }
        self.editor.ensure_cursor_col_visible();
    }

    fn refresh_editor_find_index(&mut self) {
        let Some(state) = self.editor_find.as_mut() else {
            return;
        };
        let opts = state.opts;
        let needle = state.query.clone();
        state.match_index = crate::widgets::editor_find::match_index_at(
            &self.editor.lines,
            &needle,
            opts,
            self.editor.cursor_row,
            self.editor.cursor_col,
        );
    }

    /// True when the replace row is shown and owns the keyboard.
    fn editor_find_replace_focused(&self) -> bool {
        self.editor_find
            .as_ref()
            .map(|s| {
                s.replace_visible && s.focus == crate::widgets::editor_find::FindField::Replace
            })
            .unwrap_or(false)
    }

    /// Append / edit the focused find-bar field: the replace row edits in
    /// place, the query row re-runs the search via `editor_find_set_query`.
    fn editor_find_edit_focused(&mut self, edit: impl FnOnce(&mut String)) {
        if self.editor_find_replace_focused() {
            if let Some(s) = self.editor_find.as_mut() {
                edit(&mut s.replace);
            }
            return;
        }
        let mut new_q = self
            .editor_find
            .as_ref()
            .map(|s| s.query.clone())
            .unwrap_or_default();
        edit(&mut new_q);
        self.editor_find_set_query(new_q);
    }

    fn handle_editor_find_key(&mut self, key: KeyEvent) {
        if is_editor_replace_key(key) {
            self.open_editor_replace();
            return;
        }
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let cmd_like = key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER);
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) => self.close_editor_find(),
            // `Cmd+Opt+Enter` (Linux: `Ctrl+Alt+Enter`) = Replace All,
            // VS Code's binding, from either field.
            (KeyCode::Enter, m) if m.contains(KeyModifiers::ALT) && cmd_like => {
                self.editor_find_replace_all();
            }
            (KeyCode::Enter, _) => {
                if self.editor_find_replace_focused() {
                    self.editor_find_replace_current();
                } else if shift {
                    self.editor_find_jump_prev();
                } else {
                    self.editor_find_jump_next();
                }
            }
            (KeyCode::Tab | KeyCode::BackTab, _) => {
                if let Some(s) = self.editor_find.as_mut()
                    && s.replace_visible
                {
                    use crate::widgets::editor_find::FindField;
                    s.focus = match s.focus {
                        FindField::Query => FindField::Replace,
                        FindField::Replace => FindField::Query,
                    };
                }
            }
            (KeyCode::F(3), _) => {
                if shift {
                    self.editor_find_jump_prev();
                } else {
                    self.editor_find_jump_next();
                }
            }
            (KeyCode::Backspace, _) => {
                self.editor_find_edit_focused(|s| {
                    s.pop();
                });
            }
            (KeyCode::Char('v'), m)
                if m.contains(KeyModifiers::CONTROL) || m.contains(KeyModifiers::SUPER) =>
            {
                if let Some(text) = (self.clipboard_reader)() {
                    self.editor_find_edit_focused(|s| {
                        for c in text.chars() {
                            if !c.is_control() {
                                s.push(c);
                            }
                        }
                    });
                }
            }
            (KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
                self.editor_find_edit_focused(|s| s.push(c));
            }
            _ => {}
        }
    }

    /// Replace the active find match with the replace field's text
    /// (expanding `$1` captures in regex mode) and advance to the next
    /// match — the find bar's Replace (Enter in the replace row). With no
    /// active match, Enter just finds the next one, like VS Code.
    fn editor_find_replace_current(&mut self) {
        if !self.editor_is_text() {
            return;
        }
        let Some(state) = self.editor_find.as_ref() else {
            return;
        };
        if state.query.is_empty() {
            return;
        }
        let (needle, replacement, opts) = (state.query.clone(), state.replace.clone(), state.opts);
        let Some((row, col, len)) = self.editor.active_search_match else {
            self.editor_find_jump_next();
            return;
        };
        let Some(line) = self.editor.lines.get(row) else {
            return;
        };
        let Some(text) = crate::widgets::editor_find::expand_replacement(
            line,
            col,
            len,
            &needle,
            &replacement,
            opts,
        ) else {
            // Stale match position (buffer changed underneath): resync
            // instead of splicing blindly.
            self.editor_find_jump_next();
            return;
        };
        self.editor.replace_find_match(row, col, len, &text);
        self.editor.active_search_match = None;
        self.editor.set_search_highlight(Some(needle.clone()), opts);
        if let Some(s) = self.editor_find.as_mut() {
            s.set_match_count(
                crate::widgets::editor_find::count_matches(&self.editor.lines, &needle, opts),
                false,
            );
        }
        if let Some(m) = crate::widgets::editor_find::find_next_match(
            &self.editor.lines,
            &needle,
            opts,
            self.editor.cursor_row,
            self.editor.cursor_col,
            false,
        ) {
            self.jump_editor_to_match(m);
        }
        self.refresh_editor_find_index();
    }

    /// Replace every match in the buffer as one undo step — the find
    /// bar's Replace All (`Cmd+Opt+Enter`).
    fn editor_find_replace_all(&mut self) {
        if !self.editor_is_text() {
            return;
        }
        let Some(state) = self.editor_find.as_ref() else {
            return;
        };
        if !state.replace_visible || state.query.is_empty() {
            return;
        }
        let (needle, replacement, opts) = (state.query.clone(), state.replace.clone(), state.opts);
        let Some((new_lines, n)) = crate::widgets::editor_find::replace_all_in_lines(
            &self.editor.lines,
            &needle,
            &replacement,
            opts,
        ) else {
            return;
        };
        if n == 0 {
            self.status = String::from("Replace All: no matches");
            return;
        }
        self.editor.replace_all_lines(new_lines);
        self.editor.active_search_match = None;
        if let Some(s) = self.editor_find.as_mut() {
            // Recount against the new buffer: `a` -> `aa` doubles the
            // matches, and a hard zero would read "No results" over a body
            // still painted full of highlights.
            s.set_match_count(
                crate::widgets::editor_find::count_matches(&self.editor.lines, &needle, opts),
                false,
            );
            s.match_index = None;
        }
        self.editor.set_search_highlight(Some(needle), opts);
        self.status = if n == 1 {
            String::from("Replaced 1 occurrence")
        } else {
            format!("Replaced {n} occurrences")
        };
    }

    fn render_editor_find(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let Some(state) = self.editor_find.as_mut() else {
            return;
        };
        let area = self.editor.last_full_area;
        if area.width == 0 || area.height == 0 {
            return;
        }
        crate::widgets::editor_find::render_editor_find(state, area, frame.buffer_mut(), theme);
    }

    /// Draw the find-in-terminal bar over the active terminal pane, reusing
    /// the editor find widget (query row only). Same top-right placement.
    fn render_terminal_find(&mut self, frame: &mut ratatui::Frame) {
        if self.terminal_find.is_none() || !self.show_terminal {
            return;
        }
        let theme = self.theme;
        let area = self.terminal().last_area;
        if area.width == 0 || area.height == 0 {
            return;
        }
        let Some(state) = self.terminal_find.as_mut() else {
            return;
        };
        crate::widgets::editor_find::render_editor_find(state, area, frame.buffer_mut(), theme);
    }

    fn handle_shortcuts_modal_key(&mut self, key: KeyEvent) {
        let Some(modal) = self.shortcuts_modal.as_mut() else {
            return;
        };
        match (key.code, key.modifiers) {
            (KeyCode::Esc, _) | (KeyCode::F(1), _) => self.close_shortcuts_modal(),
            (KeyCode::Char('q'), KeyModifiers::NONE) => self.close_shortcuts_modal(),
            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => modal.scroll_down(1),
            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => modal.scroll_up(1),
            (KeyCode::PageDown, _) | (KeyCode::Char(' '), _) => modal.scroll_down(10),
            (KeyCode::PageUp, _) => modal.scroll_up(10),
            (KeyCode::Home, _) | (KeyCode::Char('g'), _) => modal.scroll_to_top(),
            (KeyCode::End, _) | (KeyCode::Char('G'), _) => modal.scroll_to_bottom(),
            _ => {}
        }
    }

    fn handle_shortcuts_modal_mouse(&mut self, m: MouseEvent) {
        let Some(modal) = self.shortcuts_modal.as_mut() else {
            return;
        };
        let inside = rect_contains(modal.last_rect, m.column, m.row);
        match m.kind {
            MouseEventKind::ScrollDown => modal.scroll_down(3),
            MouseEventKind::ScrollUp => modal.scroll_up(3),
            MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
                if !inside =>
            {
                self.close_shortcuts_modal();
            }
            _ => {}
        }
    }

    fn render_shortcuts_modal(&mut self, frame: &mut ratatui::Frame) {
        let theme = self.theme;
        let Some(modal) = self.shortcuts_modal.as_mut() else {
            return;
        };
        let area = frame.area();
        crate::widgets::shortcuts::render_shortcuts_modal(modal, area, frame.buffer_mut(), theme);
    }

    fn render_connect_dialog(&mut self, frame: &mut ratatui::Frame) {
        let visible = self.cursor_visible_phase();
        let theme = self.theme;
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return;
        };
        dialog.theme = theme;
        let area = frame.area();
        use ratatui::widgets::Widget as _;
        dialog.render(area, frame.buffer_mut());
        if visible && let Some((cx, cy)) = dialog.cursor_screen_pos() {
            frame.set_cursor_position((cx, cy));
        }
    }

    /// A tap inside the on-screen keyboard band. Layer/modifier keys mutate
    /// the keyboard; character/named keys synthesize a `KeyEvent` and feed
    /// it through `handle_key`, so it reaches whatever currently owns the
    /// keyboard focus (editor, terminal, search, or an open modal).
    /// Begin a push-to-talk session on a mic press. Gated on availability:
    /// only Termux with `termux-speech-to-text` can listen; a missing
    /// `termux-api` package kicks off a background install and asks the user to
    /// retry, and a non-Termux host just explains it is Termux-only.
    /// Tap the mic: cancel a live session, or start a new one. The success path
    /// is not this tap but going quiet - the system speech dialog finalizes on
    /// silence and the transcript is injected then. A second tap is the escape
    /// hatch (cancel) because killing the recognizer preempts its result, so it
    /// can never be the way to "finish".
    fn toggle_voice_input(&mut self) {
        if self.voice_handle.is_some() {
            self.cancel_voice_input();
        } else {
            self.start_voice_input();
        }
    }

    fn start_voice_input(&mut self) {
        if self.voice_handle.is_some() {
            return;
        }
        match crate::voice::availability() {
            crate::voice::Availability::Ready => {
                self.voice_handle = Some(crate::voice::start(self.voice_tx.clone()));
                self.voice_canceling = false;
                self.status = String::from("Listening, speak then pause to insert");
            }
            crate::voice::Availability::NeedsApi => {
                crate::voice::ensure_api_installed_in_background();
                self.status = String::from(
                    "Installing Termux:API for voice input, tap the mic again once it finishes",
                );
            }
            crate::voice::Availability::NeedsTermux => {
                self.status = String::from("Voice input is available only on Termux");
            }
        }
    }

    /// Cancel the active session (a second mic tap): kill the recognizer and
    /// discard. Recognition normally ends on its own when you stop talking;
    /// this is only for abandoning a session that is stuck or unwanted. The
    /// killed worker reports `Empty`, which `drain_voice` turns into a "canceled"
    /// message via this flag.
    fn cancel_voice_input(&mut self) {
        if let Some(handle) = self.voice_handle.as_ref() {
            self.voice_canceling = true;
            handle.stop();
        }
    }

    /// Per-tick: deliver a finished voice session's result. Returns whether the
    /// next frame should redraw (transcript injected or a status message set).
    fn drain_voice(&mut self) -> bool {
        let mut changed = false;
        while let Ok(msg) = self.voice_rx.try_recv() {
            changed = true;
            self.voice_handle = None;
            match msg {
                crate::voice::VoiceMsg::Transcript(text) => {
                    self.voice_canceling = false;
                    self.inject_voice_text(&text);
                }
                crate::voice::VoiceMsg::Empty => {
                    self.status = if std::mem::take(&mut self.voice_canceling) {
                        String::from("Voice input canceled")
                    } else {
                        String::from("No speech detected")
                    };
                }
                crate::voice::VoiceMsg::Failed(e) => {
                    self.voice_canceling = false;
                    self.status = e;
                }
            }
        }
        changed
    }

    /// Type a recognized transcript into whatever owns keyboard focus by
    /// replaying it as synthetic key events through `handle_key` - the same
    /// path an OSK key tap takes - so it reaches the editor, terminal, or an
    /// open modal without pane-specific wiring.
    fn inject_voice_text(&mut self, text: &str) {
        for ch in text.chars() {
            let code = if ch == '\n' {
                KeyCode::Enter
            } else {
                KeyCode::Char(ch)
            };
            if let Err(e) = self.handle_key(KeyEvent::new(code, KeyModifiers::NONE)) {
                self.status = format!("Voice input failed: {e}");
                return;
            }
        }
        self.status = String::new();
    }

    fn handle_osk_mouse(&mut self, m: MouseEvent) {
        if !matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
            return;
        }
        let Some(osk) = self.osk.as_mut() else {
            return;
        };
        let Some(key) = osk.key_at(m.column, m.row) else {
            return;
        };
        if key == crate::widgets::osk::OskKey::Hide {
            self.osk = None;
            return;
        }
        let ev = osk.tap(key);
        // Layer/modifier taps reshape the band; refresh the hit rects
        // immediately so a follow-up tap that lands before the next frame
        // hits the new layer, not the stale one.
        let band = osk.last_area;
        osk.layout(band);
        // The split choice outlives the session (best-effort, like themes).
        if key == crate::widgets::osk::OskKey::SplitToggle {
            let _ = crate::prefs::save_osk_split(osk.split);
        }
        // Mic is a tap, not push-to-talk: Termux turns any finger hold into its
        // own text-selection gesture (hardcoded in TerminalView, not
        // suppressible from a TUI), so a hold can never reach croft as a
        // sustained press. A quick tap is the only touch Termux forwards as a
        // click. A tap starts recognition; the transcript lands when the user
        // pauses (Android finalizes on silence), and a second tap cancels.
        // Deferred until the `osk` borrow ends so the toggle can take `&mut
        // self`. `tap` returned None for it, so nothing reaches handle_key.
        let is_voice = key == crate::widgets::osk::OskKey::Voice;
        if let Some(ev) = ev
            && let Err(e) = self.handle_key(ev)
        {
            self.status = format!("On-screen key failed: {e}");
        }
        if is_voice {
            self.toggle_voice_input();
        }
    }

    fn handle_mouse(&mut self, m: MouseEvent) {
        // On-screen keyboard taps outrank every other gate - including the
        // modal overlays - because the OSK is how Termux users type into
        // those modals. Its band is laid out disjoint from all panes, so
        // swallowing events inside it never steals a pane's click.
        if self
            .osk
            .as_ref()
            .is_some_and(|k| rect_contains(k.last_area, m.column, m.row))
        {
            self.handle_osk_mouse(m);
            return;
        }
        // A click on the port-detection toast's action buttons is consumed
        // before anything else; clicks elsewhere fall through to normal
        // handling, so the toast never blocks the rest of the UI.
        if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
            && (self.handle_port_toast_click(m.column, m.row)
                || self.handle_update_toast_click(m.column, m.row))
        {
            return;
        }
        if self.connect_dialog.is_some() {
            if matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
                self.handle_connect_dialog_click(m.column, m.row);
            }
            return;
        }
        if self.shortcuts_modal.is_some() {
            self.handle_shortcuts_modal_mouse(m);
            return;
        }
        if self.file_finder.is_some() {
            self.handle_file_finder_mouse(m);
            return;
        }
        if self.process_picker.is_some() {
            self.handle_process_picker_mouse(m);
            return;
        }
        if self.command_palette.is_some() {
            self.handle_command_palette_mouse(m);
            return;
        }
        if self.workspace_symbols.is_some() {
            self.handle_workspace_symbols_mouse(m);
            return;
        }
        if self.go_to_symbol.is_some() {
            self.handle_go_to_symbol_mouse(m);
            return;
        }
        if self.zoxide_jump.is_some() {
            self.handle_zoxide_jump_mouse(m);
            return;
        }
        if self.command_history_popup.is_some() {
            // Keyboard-first popup: a click anywhere dismisses it (Esc's
            // mouse equivalent); the wheel moves the selection.
            match m.kind {
                MouseEventKind::ScrollUp => {
                    if let Some(pop) = self.command_history_popup.as_mut() {
                        pop.select_prev();
                    }
                }
                MouseEventKind::ScrollDown => {
                    if let Some(pop) = self.command_history_popup.as_mut() {
                        pop.select_next();
                    }
                }
                MouseEventKind::Down(_) => self.command_history_popup = None,
                _ => {}
            }
            return;
        }
        if self.branch_picker.is_some() {
            self.handle_branch_picker_mouse(m);
            return;
        }
        if self.input_prompt.is_some() {
            self.handle_input_prompt_mouse(m);
            return;
        }
        if self.list_picker.is_some() {
            self.handle_list_picker_mouse(m);
            return;
        }
        if self.scm_menu.open && matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
            use crate::widgets::scm_menu::ClickOutcome;
            match self.scm_menu.click(m.column, m.row) {
                ClickOutcome::Fire(action) => self.dispatch_scm_action(action),
                ClickOutcome::Toggled => {}
                ClickOutcome::Missed => self.scm_menu.close(),
            }
            return;
        }
        if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
            && self
                .shortcuts_hit_rect
                .is_some_and(|r| rect_contains(r, m.column, m.row))
        {
            self.open_shortcuts_modal();
            return;
        }
        // Clickable status-bar segments: encoding / EOL / language open a
        // "change" picker; the diagnostics counts jump to the PROBLEMS panel.
        if matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
            if rect_contains(self.status_language_rect, m.column, m.row) {
                self.open_status_language_menu(
                    self.status_language_rect.x,
                    self.status_language_rect.y,
                );
                return;
            }
            if rect_contains(self.status_eol_rect, m.column, m.row) {
                self.open_status_eol_menu(self.status_eol_rect.x, self.status_eol_rect.y);
                return;
            }
            if rect_contains(self.status_encoding_rect, m.column, m.row) {
                self.open_status_encoding_menu(
                    self.status_encoding_rect.x,
                    self.status_encoding_rect.y,
                );
                return;
            }
            if rect_contains(self.status_indent_rect, m.column, m.row) {
                self.open_status_indent_menu(self.status_indent_rect.x, self.status_indent_rect.y);
                return;
            }
            if rect_contains(self.status_diag_rect, m.column, m.row) {
                self.set_bottom_panel_tab(BottomPanelTab::Problems);
                return;
            }
            if rect_contains(self.status_agents_rect, m.column, m.row) {
                self.focus_agent_pane();
                return;
            }
        }
        // Layout-control icons (Toggle Side Bar / Panel / Customize Layout) at
        // the top-right of the editor tab strip / welcome screen. Checked
        // before the panes so a click on an icon never falls through to the
        // editor below it. Skipped while a menu is open (that block wins).
        if self.context_menu.is_none() && matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
        {
            let icons = self.layout_icon_areas;
            if rect_contains(icons.toggle_side_bar, m.column, m.row) {
                self.toggle_side_bar();
                self.after_chrome_visibility_change();
                return;
            }
            if rect_contains(icons.toggle_panel, m.column, m.row) {
                self.toggle_terminal();
                return;
            }
            if rect_contains(icons.customize, m.column, m.row) {
                self.open_customize_layout_menu();
                return;
            }
        }

        // While a prompt is open, mouse events are ignored.
        if self.prompt.is_some() {
            return;
        }

        // While a context menu is open, route clicks to it.
        if self.context_menu.is_some() {
            match m.kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    // 1. A click inside the open submenu panel dispatches that child.
                    if let Some(child) = self.submenu_item_at(m.column, m.row) {
                        let dispatch = self.context_menu.as_ref().and_then(|menu| {
                            let parent = menu.open_submenu?;
                            let MenuEntry::Submenu { items, .. } = menu.items.get(parent)? else {
                                return None;
                            };
                            match items.get(child) {
                                Some(MenuEntry::Item { action, .. }) => {
                                    Some((action.clone(), menu.target_dir.clone()))
                                }
                                _ => None,
                            }
                        });
                        if let Some((action, dir)) = dispatch {
                            self.context_menu = None;
                            self.dispatch_menu_action(action, dir);
                        }
                        return;
                    }
                    // 2. A click on a top-level row: dispatch an item, or open a submenu.
                    if let Some(idx) = self.menu_item_at(m.column, m.row) {
                        let action =
                            self.context_menu
                                .as_ref()
                                .and_then(|menu| match menu.items.get(idx) {
                                    Some(MenuEntry::Item { action, .. }) => {
                                        Some((action.clone(), menu.target_dir.clone()))
                                    }
                                    _ => None,
                                });
                        match action {
                            Some((action, dir)) => {
                                self.context_menu = None;
                                self.dispatch_menu_action(action, dir);
                            }
                            None => {
                                // A submenu parent (or a divider): open the submenu.
                                if let Some(menu) = self.context_menu.as_mut() {
                                    menu.selected = idx;
                                    menu.open_cursor_submenu();
                                }
                            }
                        }
                        return;
                    }
                    // 3. Click outside every panel: dismiss.
                    self.context_menu = None;
                    return;
                }
                MouseEventKind::Down(MouseButton::Right) => {
                    self.context_menu = None;
                    // fall through so the right-click below can re-open if applicable
                }
                _ => return,
            }
        }

        // When the editor is split, a press anywhere in the NON-focused
        // column (except its draggable seam) moves focus there first, so
        // the rest of this handler - which all reads `self.editor` - then
        // operates on the clicked group. The swap keeps the physical
        // columns fixed.
        if matches!(m.kind, MouseEventKind::Down(_))
            && self.editor_layout.is_split()
            && self.seam_at(m.column, m.row).is_none()
            && let Some(target) = self.editor_layout.inactive_dfs_index_at(m.column, m.row)
        {
            let current = std::mem::take(&mut self.editor);
            self.editor = self.editor_layout.refocus_to_dfs(current, target);
            self.focus_pane(Pane::Editor);
        }

        // Hit-test the side panel against the ACTIVE widget's last_area
        // rather than always against `self.tree.last_area`. The tree is
        // only re-rendered when the Explorer view is active; switching
        // to Search / Source Control / Remote / Run-Debug freezes
        // `tree.last_area` at whatever rectangle the last Explorer
        // render captured, which can be smaller than the current side
        // panel and silently swallow clicks on rows below that rect.
        let active_sidebar_area = match self.sidebar_view {
            SidebarView::Explorer => self.tree.last_area,
            SidebarView::Search => self.search.last_area,
            SidebarView::SourceControl => self.source_control.last_area,
            SidebarView::Remote => self.remote.last_area,
            SidebarView::RunDebug => self.run_debug.last_area,
            SidebarView::Extensions => self.extensions.last_area,
            SidebarView::Testing => self.testing.last_area,
        };
        // The COMMITS graph docks BELOW the change list in its own strip, so
        // `source_control.last_area` alone misses it; without this union the
        // graph's wheel-scroll and click handlers (all gated on `in_tree`)
        // are unreachable (Codeberg #41).
        let in_commit_graph = self.sidebar_view == SidebarView::SourceControl
            && rect_contains(self.commit_graph.last_area, m.column, m.row);
        let in_tree = self.show_tree
            && (rect_contains(active_sidebar_area, m.column, m.row) || in_commit_graph);
        // The OUTLINE section sits below the tree in the Explorer sidebar and
        // scrolls independently, so wheel events over it must reach the panel
        // rather than the tree above.
        let in_outline = self.sidebar_view == SidebarView::Explorer
            && rect_contains(self.outline.last_area, m.column, m.row);
        let in_open_editors = self.sidebar_view == SidebarView::Explorer
            && rect_contains(self.open_editors.last_area, m.column, m.row);
        let in_timeline = self.sidebar_view == SidebarView::Explorer
            && rect_contains(self.timeline.last_area, m.column, m.row);
        let in_deps = self.sidebar_view == SidebarView::Explorer
            && rect_contains(self.dependencies.last_area, m.column, m.row);
        let in_editor_pane = rect_contains(self.editor.last_full_area, m.column, m.row);
        let in_editor = rect_contains(self.editor.last_area, m.column, m.row);
        let terminal_hit = self.terminal_at_pos(m.column, m.row);
        let in_terminal = terminal_hit.is_some();
        // User mouse bindings (#259) resolve before the built-in widget
        // behaviour, mirroring how keybindings.json wins over default chords.
        // Placed after the region predicates so a binding's `when` context is
        // known, and above every built-in so rebinding one actually takes it
        // over. A gesture croft has no binding for falls straight through.
        // Classify ONCE and reuse. `gesture_for` reads the modified-click
        // tracker to decide `Click` vs `DoubleClick`, so calling it a second
        // time after recording would let a single click arm itself and come
        // back a double — which is exactly what an earlier attempt at this did.
        // The recording therefore happens after the lookup, using the gesture
        // decided here, never a freshly re-derived one.
        let bound_mouse = if self.keymap.has_mouse_bindings()
            && let Some(ctx) = mouse_context_for(&m, in_editor, in_terminal, in_tree, self)
            && let Some(gesture) = gesture_for(&m, self, ctx, std::time::Instant::now())
        {
            Some((ctx, gesture, self.keymap.command_for_mouse(gesture, ctx)))
        } else {
            None
        };

        // A modified click is recorded whether or not it matched a binding. The
        // first click of a `ctrl+double_click` pair matches nothing by
        // construction — it classifies as `ctrl+click`, and a user who bound
        // only the double has nothing for it to hit — so recording only on a
        // match left the pair's second click seeing an empty tracker, and the
        // double could not fire at all.
        //
        // Unmodified clicks are deliberately not recorded here: their trackers
        // are shared with the built-ins, which record their own clicks on the
        // paths below. Doing it in both places would double-count.
        //
        // A click the pointer-owning child gets is not croft's to remember.
        // The built-ins record INSIDE their `child_owns_pointer` check; this
        // recording sat above it, so clicks croft deliberately declined to act
        // on still armed the tracker, and a later modified click paired with
        // one the user had aimed at the TUI in the terminal. Same predicate as
        // the dispatch below, indexed by the pane that was CLICKED.
        let child_owns_pointer = bound_mouse.is_some_and(|(ctx, gesture, _)| {
            // Only the gestures croft actually FORWARDS: a tracking child can
            // own nothing else. That is the wheel (both wheel arms below) and
            // the LEFT button -- press in the Down(Left) arm, motion in Drag,
            // release in Up -- since #474, when clicking a TUI's own controls
            // (Claude Code's diff-panel ×) started working. `Click` and
            // `DoubleClick` are both Down(Left), so both are the child's.
            // Middle and right clicks are still croft's (paste, the context
            // menu), so a binding on them fires over a tracking child too.
            matches!(
                gesture.kind,
                crate::keymap::GestureKind::WheelUp
                    | crate::keymap::GestureKind::WheelDown
                    | crate::keymap::GestureKind::Click
                    | crate::keymap::GestureKind::DoubleClick
            ) && matches!(ctx, crate::keymap::MouseContext::Terminal)
                && terminal_hit.is_some_and(|idx| {
                    // Tracking is not enough: `terminal_at_pos` hit-tests
                    // `last_area`, which includes the BORDER, while delivery
                    // goes through `cell_at` on `last_inner`, which does not.
                    // Declining a binding for a cell the child will never be
                    // told about loses the gesture for both parties. The
                    // built-in wheel path already falls through on exactly
                    // this case — see the `report_mouse` guard on both wheel
                    // arms, whose comment names the border explicitly.
                    self.terminals[idx].mouse_reporting()
                        && self.terminals[idx].cell_at(m.column, m.row).is_some()
                })
                && !m.modifiers.contains(KeyModifiers::SHIFT)
        });
        if let Some((_, gesture, _)) = bound_mouse
            && !gesture.mods.is_empty()
            && !child_owns_pointer
        {
            let now = std::time::Instant::now();
            match gesture.kind {
                // Clear on a fired double so a third click re-arms rather than
                // re-firing; record otherwise so the NEXT modified click can be
                // seen as the second of a pair.
                crate::keymap::GestureKind::DoubleClick => self.modified_click.clear(),
                crate::keymap::GestureKind::Click => {
                    self.modified_click
                        .record(now, m.column, m.row, gesture.mods)
                }
                _ => {}
            }
        }

        // The first half of a bound double-click matches no binding, so
        // without this it falls through to whatever built-in owns the same
        // modifier: binding `ctrl+double_click` in the editor made the pair's
        // first click fire go-to-definition, and in the terminal it armed the
        // plain double-click tracker so the user's NEXT ordinary click
        // selected a word they never gestured for. Both are the same bug —
        // croft acting on a click the user aimed at their own binding.
        //
        // Swallowed AFTER the modified-click recording above, which is what
        // lets the second click of the pair see the first. Only the prefix of
        // a bound double is swallowed: a Ctrl+click with no double bound
        // reaches the built-in unchanged.
        //
        // `child_owns_pointer` for the same reason the matched dispatch below
        // consults it — a TUI that asked for mouse tracking owns the pointer,
        // so croft must not suppress a built-in on its behalf. The recording
        // above already declines there, so the bound double is unreachable in
        // that state anyway: swallowing would cost the built-in and buy
        // nothing. Omitting it here disabled the built-in Ctrl+click over
        // every full-screen TUI for anyone who bound only `ctrl+double_click`.
        // Over a tracking child the click is forwarded to it (#474), so
        // `child_owns_pointer` is true for a left click there and the swallow
        // steps aside: the recording above already declined, the bound double
        // is unreachable, and swallowing would only cost the child its press.
        // Where the child does not own it, the question is narrower: would
        // declining this click COST the user a built-in that was going to act?
        // For Ctrl/Cmd the built-in opens a URL or a file reference, so defer
        // when either is under the cursor -- that link-open runs BEFORE the
        // forward in the Down(Left) arm, so it applies over a tracking child
        // as well.
        let builtin_would_act = matches!(bound_mouse, Some((ctx, _, _)) if
            matches!(ctx, crate::keymap::MouseContext::Terminal))
            && (m.modifiers.contains(KeyModifiers::CONTROL)
                || m.modifiers.contains(KeyModifiers::SUPER))
            && terminal_hit
                .is_some_and(|idx| self.terminal_would_open_something_at(idx, m.column, m.row));
        if let Some((ctx, gesture, None)) = bound_mouse
            && !gesture.mods.is_empty()
            && !builtin_would_act
            && !child_owns_pointer
            && self.keymap.is_double_click_prefix(gesture, ctx)
        {
            // Focus still moves, as a click in a pane always does — otherwise
            // the pair's second click lands in a pane the keyboard has not
            // followed. This mirrors what the matched path does below.
            match ctx {
                crate::keymap::MouseContext::Terminal => {
                    if let Some(idx) = terminal_hit {
                        self.activate_terminal_pane(idx);
                        self.focus_pane(Pane::Terminal);
                    }
                }
                crate::keymap::MouseContext::Editor | crate::keymap::MouseContext::TabStrip => {
                    self.focus_pane(Pane::Editor)
                }
                crate::keymap::MouseContext::FileTree => self.focus_pane(Pane::Tree),
            }
            // Same teardown the matched branch runs: this is an early return
            // on the same press path, and it re-focuses a pane underneath
            // whatever popups were showing.
            self.dismiss_click_overlays(m);
            return;
        }

        if let Some((ctx, gesture, Some(cmd))) = bound_mouse {
            // A terminal running a mouse-tracking TUI owns the pointer, same
            // rule the built-ins follow: croft must not steal a click the
            // child asked for. Computed once above so the recording and this
            // dispatch cannot drift apart — they must agree on whether the
            // click was croft's to act on.
            if !child_owns_pointer {
                // Every built-in pairs `is_double` with `record`/`clear` so
                // the count stays right. The early return below skips the
                // built-in branch that would have recorded, so the dispatch
                // has to keep the tracker itself: clear on a fired double
                // (or a third click re-fires it), record on a fired UNMODIFIED
                // single (or a `click` binding starves the `double_click`
                // binding beside it — `is_double` could never become true).
                //
                // Unmodified only, because the built-ins that read these
                // trackers do not consult modifiers. Recording a ctrl+click
                // would arm the editor's plain double-click, and the user's
                // next ordinary click would select a word they never asked
                // for. Bare clicks are reserved in `editor`/`terminal`, so
                // the record here only ever matters for `file_tree` and
                // `tab_strip`, which is exactly where it is needed.
                // Modified clicks are recorded above, before the command
                // lookup, so the first click of a pair is remembered even
                // though it matches nothing.
                let now = std::time::Instant::now();
                if gesture.mods.is_empty() {
                    let tracker = match ctx {
                        crate::keymap::MouseContext::Terminal => &mut self.terminal_click,
                        crate::keymap::MouseContext::FileTree => &mut self.tree_click,
                        // The strip shares the editor's tracker, as
                        // `gesture_for` does: a double-click is the same
                        // gesture whether it lands on a tab or the text below
                        // it. Spelled out rather than caught by `_` so a new
                        // variant has to choose.
                        crate::keymap::MouseContext::Editor
                        | crate::keymap::MouseContext::TabStrip => &mut self.editor_click,
                    };
                    match gesture.kind {
                        crate::keymap::GestureKind::DoubleClick => tracker.clear(),
                        // Pass the modifiers through: #317's guard then keeps
                        // a MODIFIED gesture from arming the built-in tracker,
                        // which is what the separate ModifiedClickTracker
                        // exists for. Hard-coding NONE here would re-open the
                        // exact hole - a ctrl+click binding arming the plain
                        // double-click the user never made.
                        crate::keymap::GestureKind::Click => {
                            tracker.record(now, m.column, m.row, m.modifiers)
                        }
                        _ => {}
                    }
                }
                // The early return below skips the teardown every other
                // press path runs, so do it here: a fired binding changes
                // the state underneath these popups, and leaving them up
                // paints a hover, a tab tooltip or a button hint describing
                // what was there before the command ran. The dwell timer is
                // cleared for the same reason — it is armed at coordinates
                // whose meaning the command just changed.
                self.dismiss_click_overlays(m);

                // Termux: the tap still has to raise the on-screen keyboard.
                // Skipping it leaves a device with no other keyboard unable
                // to type into the field the tap just focused. Reachable
                // despite bare clicks being reserved in editor/terminal: any
                // MODIFIED click in the editor or terminal gets here, and a
                // bound gesture there should raise the keyboard exactly as the
                // built-in press would. `ctx` carries the region, so the
                // built-in's in_editor / in_terminal / in_tree — computed
                // below this block — are not needed to make the same decision.
                if self.osk_auto
                    && self.osk.is_none()
                    && matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
                    && match ctx {
                        crate::keymap::MouseContext::Editor
                        | crate::keymap::MouseContext::Terminal => true,
                        // `mouse_context_for` only yields `FileTree` while the
                        // sidebar is showing the Explorer, so the Search view
                        // this once tested for is unreachable from here — the
                        // narrowing that fixed tree bindings firing over other
                        // sidebar views left this arm behind. The tree has no
                        // text input to raise a keyboard for, so `false` is
                        // what the reachable half always evaluated to anyway.
                        crate::keymap::MouseContext::FileTree
                        | crate::keymap::MouseContext::TabStrip => false,
                    }
                {
                    let mut osk = crate::widgets::osk::Osk::new();
                    osk.split = crate::prefs::Prefs::load_or_default().osk_split;
                    self.osk = Some(osk);
                }

                // Every terminal command reads the grid through
                // `self.terminal()`, i.e. `active_terminal`. The built-in
                // click path makes the clicked pane active before it runs
                // any of them; this early-returns above that, so it has to
                // do the same or a bound command inspects whichever pane
                // happened to be focused. Same helper, so the overlay
                // teardown cannot drift between the two paths.
                if matches!(ctx, crate::keymap::MouseContext::Terminal)
                    && let Some(idx) = terminal_hit
                {
                    self.activate_terminal_pane(idx);
                }

                // Clicking a pane focuses it — every built-in click handler
                // does this, and returning above them skips it. Distinct from
                // the pane activation above: that decides which terminal a
                // command READS, this decides where the next KEYSTROKE goes.
                // Without it a bound gesture that clicks into another pane
                // acts on the clicked pane while the keyboard silently stays
                // behind, so the user's next character lands in the pane they
                // just clicked away from.
                //
                // The tab strip focuses the editor: it has no focus of its
                // own, and that is what clicking a tab does anyway.
                match ctx {
                    crate::keymap::MouseContext::Terminal => self.focus_pane(Pane::Terminal),
                    crate::keymap::MouseContext::FileTree => self.focus_pane(Pane::Tree),
                    crate::keymap::MouseContext::Editor | crate::keymap::MouseContext::TabStrip => {
                        self.focus_pane(Pane::Editor)
                    }
                }

                // Position-carrying commands read the click through this,
                // set before dispatch and cleared after so a keyboard
                // invocation of the same command never sees a stale click.
                self.last_mouse_pos = Some((m.column, m.row));
                self.run_command(cmd);
                self.last_mouse_pos = None;
                return;
            }
        }
        let in_problems = self.bottom_panel_tab == BottomPanelTab::Problems
            && rect_contains(self.problems.last_area, m.column, m.row);
        let in_output = self.bottom_panel_tab == BottomPanelTab::Output
            && rect_contains(self.output.last_area, m.column, m.row);
        let in_tree_scrollbar = self.sidebar_view == SidebarView::Explorer
            && rect_contains(self.tree.last_scrollbar, m.column, m.row);
        let in_remote_scrollbar = self.sidebar_view == SidebarView::Remote
            && rect_contains(self.remote.last_scrollbar, m.column, m.row);
        let in_search_scrollbar = self.sidebar_view == SidebarView::Search
            && rect_contains(self.search.last_scrollbar, m.column, m.row);
        let in_editor_scrollbar = rect_contains(self.editor.last_scrollbar, m.column, m.row);
        let in_editor_hscrollbar = rect_contains(self.editor.last_hscrollbar, m.column, m.row);

        if matches!(m.kind, MouseEventKind::Moved) {
            self.pointer_cell = Some((m.column, m.row));
            self.on_mouse_moved(m.column, m.row, in_editor);
            return;
        }
        // Extend / finish a rendered-preview selection (#215) before any
        // other gesture claims the drag.
        if self.update_preview_selection(m) {
            return;
        }
        // A rendered log carries its own selection for the same reason the
        // preview does: the tab's `lines` is a stub (#257).
        if self.update_log_selection(m) {
            return;
        }
        // The release of a press is not a new gesture, so it keeps the popup:
        // that is what lets a press-and-hold (touch) read the hover after
        // lifting the finger. Every other event dismisses it.
        if !matches!(m.kind, MouseEventKind::Up(_)) {
            self.hover_popup = None;
            self.hover_diagnostic = None;
        }
        // Any click dismisses the tab tooltip (selecting/closing a tab,
        // or clicking elsewhere) so it can't linger over the new state.
        self.tab_tooltip = None;
        self.tab_hover.clear();
        self.tab_hover_idx = None;
        // Same for the chrome button hint: a click acts on the control, so the
        // hint has served its purpose and must not survive the state change.
        self.ui_tooltip = None;
        self.ui_hover.clear();
        self.ui_tooltip_label = None;

        // A left press in the editor body arms the same dwell a resting
        // pointer does: a touchscreen emits no Moved events (a finger cannot
        // hover), so the tap itself is the "pointer arrived here" signal and
        // the LSP hover fires HOVER_DELAY later. This matches VS Code on
        // desktop too, where the hover re-shows when the pointer rests on a
        // symbol after a click. Drags (selection) and scrolls cancel the
        // pending dwell; the release does not, so a quick tap still fires.
        match m.kind {
            MouseEventKind::Down(MouseButton::Left)
                if in_editor
                    && !in_editor_scrollbar
                    && !in_editor_hscrollbar
                    && self.editor.tab_at(m.column, m.row).is_none() =>
            {
                // clear() before on_move(): a repeat tap on the same cell
                // must restart the timer (on_move alone keys off cell change).
                self.hover.clear();
                self.hover
                    .on_move(std::time::Instant::now(), m.column, m.row);
            }
            MouseEventKind::Up(_) => {}
            _ => self.hover.clear(),
        }

        // Termux: a tap in any editable area raises the on-screen keyboard,
        // standing in for the native soft keyboard that active mouse
        // tracking permanently suppresses. The tap still falls through to
        // its normal focus / cursor handling below.
        if self.osk_auto
            && self.osk.is_none()
            && matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
            && (in_editor || in_terminal || (in_tree && self.sidebar_view == SidebarView::Search))
        {
            let mut osk = crate::widgets::osk::Osk::new();
            // Restore the persisted split-layout choice (foldables).
            osk.split = crate::prefs::Prefs::load_or_default().osk_split;
            self.osk = Some(osk);
            // The raise reflows the whole frame, so a dwell armed at the
            // pre-raise coordinates would resolve the wrong buffer cell.
            self.hover.clear();
        }

        match m.kind {
            MouseEventKind::Down(MouseButton::Right) => {
                // Minimap strip right-click: the VS Code-style options menu
                // (Minimap toggle + Side submenu). Checked first so the strip
                // wins over the editor pane it sits beside.
                if rect_contains(self.minimap_img_rect, m.column, m.row) {
                    self.open_minimap_menu(m.column, m.row);
                    return;
                }
                // A PROBLEMS diagnostic row: Fix with Navigator (#374).
                // Offered whether or not a navigator is seated, like the
                // CAPTURES ask: the menu model has no disabled state, and a
                // refusal that says why beats a greyed entry.
                if self.bottom_panel_tab == BottomPanelTab::Problems
                    && rect_contains(self.problems.last_area, m.column, m.row)
                    && let Some((path, item)) = self.problems.diagnostic_at(m.row)
                {
                    self.context_menu = Some(ContextMenu::flat(
                        (m.column, m.row),
                        vec![(
                            String::from("Fix with Navigator"),
                            MenuAction::FixProblemWithNavigator { path, item },
                        )],
                        self.tree.root.clone(),
                    ));
                    return;
                }
                // A CAPTURES row: the ask is offered whether or not a
                // navigator is seated, and says so if none is (#372).
                if self.bottom_panel_tab == BottomPanelTab::Captures
                    && rect_contains(self.captures.last_area, m.column, m.row)
                    && let Some(idx) = self.captures.row_at(m.column, m.row)
                {
                    self.captures.select_index(idx);
                    self.context_menu = Some(ContextMenu::flat(
                        (m.column, m.row),
                        vec![(
                            String::from("Ask Navigator About This Line"),
                            MenuAction::AskNavigatorAboutCapture,
                        )],
                        self.tree.root.clone(),
                    ));
                    return;
                }
                // Editor tab strip: right-click on a tab opens the
                // Close / Close Others / Close to the Right / Close All
                // menu. Routed here BEFORE the explorer branch so the
                // hit-test wins even when the editor pane shares its
                // column with the sidebar.
                if let Some(tab_idx) = self.editor.tab_at(m.column, m.row) {
                    self.focus_pane(Pane::Editor);
                    let tab_path = self.editor.tab_path(tab_idx);
                    let items = build_tab_context_menu_items(
                        tab_idx,
                        self.editor.tab_count(),
                        self.editor_layout.is_split(),
                        tab_path.as_deref(),
                        !self.is_remote && cfg!(target_os = "macos"),
                        self.editor.is_preview(tab_idx),
                        self.editor.is_pinned(tab_idx),
                    );
                    self.context_menu = Some(ContextMenu {
                        origin: (m.column, m.row),
                        items,
                        selected: 0,
                        open_submenu: None,
                        submenu_selected: 0,
                        target_dir: self.tree.root.clone(),
                    });
                    return;
                }
                // Terminal pane right-click: the `…`-overflow equivalent. Rename
                // and Clear (the gaps vs VS Code's toolbar); split/close already
                // have buttons and chords.
                // A folded pane clears its `last_area`, so `terminal_at_pos`
                // can never name one and the menu's "Expand Terminal" branch
                // was unreachable while KEYBINDINGS.md advertised it (#313).
                // Fall back to the strips so a folded pane has a second
                // gesture rather than left-click alone.
                let terminal_hit = terminal_hit.or_else(|| {
                    self.terminal_strip_rects
                        .iter()
                        .position(|r| rect_contains(*r, m.column, m.row))
                });
                if self.bottom_panel_tab == BottomPanelTab::Terminal
                    && let Some(idx) = terminal_hit
                {
                    self.active_terminal = idx;
                    self.focus_pane(Pane::Terminal);
                    // A folded pane cannot BE the active one: `focus_pane`
                    // runs `sync_focus_flags`, whose invariant walks focus to
                    // the nearest expanded neighbour rather than leave it on
                    // a pane with nothing painted. Entries carrying `idx` are
                    // unaffected, but the ones that read `active_terminal`
                    // would act on that neighbour while this menu names THIS
                    // pane - and the broadcast entry read its label from
                    // `idx` while toggling the neighbour, so it could say
                    // "Exclude from Broadcast" and include a different pane.
                    // Each of them is also a gesture on a grid the user
                    // cannot see while the pane is a strip.
                    let folded = self.terminals.get(idx).is_some_and(|t| t.collapsed);
                    let mut items: Vec<MenuEntry> = Vec::new();
                    // Copy and Paste lead the menu, as they do in VS Code's
                    // terminal. Both act on the ACTIVE pane, so a folded one
                    // offers neither: focus has already walked to an expanded
                    // neighbour, and pasting into a grid the user cannot see
                    // is worse than not offering the entry at all.
                    if !folded {
                        // Copy appears only while there is something to copy.
                        // The menu model has no disabled state, and an entry
                        // that silently copies nothing is worse than no entry.
                        if self.terminals[idx]
                            .selection()
                            .is_some_and(|s| s.has_area())
                        {
                            items.push(MenuEntry::Item {
                                label: String::from("Copy"),
                                action: MenuAction::TerminalCopySelection,
                            });
                        }
                        items.push(MenuEntry::Item {
                            label: String::from("Paste"),
                            action: MenuAction::TerminalPaste,
                        });
                    }
                    items.push(MenuEntry::Item {
                        label: String::from("Rename Terminal"),
                        action: MenuAction::RenameTerminal(idx),
                    });
                    items.push(MenuEntry::Item {
                        label: String::from("Clear"),
                        action: MenuAction::ClearTerminal(idx),
                    });
                    if !folded {
                        items.extend([
                            MenuEntry::Item {
                                label: String::from("Quick Select"),
                                action: MenuAction::TerminalQuickSelect,
                            },
                            MenuEntry::Item {
                                label: String::from("Copy Mode"),
                                action: MenuAction::TerminalCopyMode,
                            },
                            MenuEntry::Item {
                                label: String::from("Command History"),
                                action: MenuAction::TerminalCommandHistory,
                            },
                            MenuEntry::Item {
                                label: String::from("Open Scrollback in Editor"),
                                action: MenuAction::OpenScrollbackInEditor,
                            },
                        ]);
                    }
                    // Undo close only appears while a parked pane is alive
                    // to restore (the grace window).
                    if !self.closed_terminals.is_empty() {
                        items.push(MenuEntry::Item {
                            label: String::from("Reopen Closed Terminal"),
                            action: MenuAction::UndoCloseTerminal,
                        });
                    }
                    // Maximize and broadcast both need a second pane, so a
                    // lone terminal doesn't offer them.
                    if self.terminals.len() > 1 {
                        items.push(MenuEntry::Item {
                            label: String::from(if self.terminal_pane_maximized {
                                "Restore Terminal Split"
                            } else {
                                "Maximize Terminal"
                            }),
                            action: MenuAction::ToggleMaximizeTerminal(idx),
                        });
                        // Collapse is meaningless while maximize owns the
                        // whole panel and the flags are ignored, so the entry
                        // is not offered there.
                        if !self.terminal_pane_maximized {
                            items.push(MenuEntry::Item {
                                label: String::from(if self.terminals[idx].collapsed {
                                    "Expand Terminal"
                                } else {
                                    "Collapse Terminal"
                                }),
                                action: MenuAction::ToggleCollapseTerminal(idx),
                            });
                        }
                        items.push(MenuEntry::Item {
                            label: String::from(if self.broadcast_input {
                                "Stop Broadcast Input"
                            } else {
                                "Broadcast Input"
                            }),
                            action: MenuAction::ToggleBroadcastInput,
                        });
                        if self.broadcast_input && !folded {
                            items.push(MenuEntry::Item {
                                label: String::from(if self.terminals[idx].broadcast_excluded {
                                    "Include in Broadcast"
                                } else {
                                    "Exclude from Broadcast"
                                }),
                                action: MenuAction::ToggleBroadcastExclusion,
                            });
                        }
                    }
                    self.context_menu = Some(ContextMenu {
                        origin: (m.column, m.row),
                        items,
                        selected: 0,
                        open_submenu: None,
                        submenu_selected: 0,
                        target_dir: self.tree.root.clone(),
                    });
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::Explorer {
                    self.focus_pane(Pane::Tree);
                    // A right-click on the sticky band context-menus the
                    // PINNED directory, not the covered row (#117): the band
                    // hit wins the row resolution and the menu flow proceeds
                    // for that node.
                    let node_idx = self
                        .tree
                        .sticky_row_at(m.row)
                        .or_else(|| self.tree.node_at_y(m.row));
                    if let Some(idx) = node_idx {
                        let path_clicked = self.tree.nodes[idx].path.clone();
                        let already_marked = self.tree.marked.contains(&path_clicked);
                        if already_marked {
                            self.tree.selected = idx;
                        } else {
                            self.tree.select_replace(idx);
                        }
                    }
                    let node = node_idx.and_then(|i| self.tree.nodes.get(i));
                    let target_dir =
                        crate::widgets::file_tree::create_target_dir_for(node, &self.tree.root);
                    let selection = self.tree.action_paths();
                    let mut items = build_tree_context_menu_items_in_dir(
                        &self.config_dir,
                        node,
                        &self.tree.root,
                        &selection,
                        &target_dir,
                        self.tree_clipboard.as_ref(),
                        self.compare_anchor.as_deref(),
                    );
                    let clicked = node.map(|n| n.path.clone());
                    maybe_add_reveal_in_finder(
                        &mut items,
                        clicked.as_deref(),
                        !self.is_remote && cfg!(target_os = "macos"),
                    );
                    self.context_menu =
                        Some(ContextMenu::flat((m.column, m.row), items, target_dir));
                    return;
                }
                // Editor gutter: right-click in the glyph margin / line-number
                // column opens the breakpoint menu (Add / Remove Breakpoint,
                // Add Conditional / Edit Condition), mirroring VS Code's
                // glyph-margin context menu. Routed before the body branch so a
                // gutter click never falls through to the symbol menu. Diff /
                // sheet / image tabs have no debuggable source lines.
                if in_editor
                    && self.editor.diff.is_none()
                    && self.editor.sheet.is_none()
                    && self.editor.image.is_none()
                    && let Some(line0) = self.editor.gutter_line_at(m.column, m.row)
                {
                    self.focus_pane(Pane::Editor);
                    let line = line0 + 1; // 1-based, as breakpoints are stored
                    let (has_bp, has_cond, has_log) = self
                        .editor
                        .path
                        .as_ref()
                        .map(|p| {
                            let has_bp = self
                                .editor
                                .breakpoints
                                .get(p)
                                .is_some_and(|s| s.contains(&line));
                            let has_cond = self
                                .editor
                                .breakpoint_conditions
                                .get(p)
                                .is_some_and(|c| c.contains_key(&line));
                            let has_log = self
                                .editor
                                .breakpoint_logs
                                .get(p)
                                .is_some_and(|m| m.contains_key(&line));
                            (has_bp, has_cond, has_log)
                        })
                        .unwrap_or((false, false, false));
                    let toggle_label = if has_bp {
                        String::from("Remove Breakpoint")
                    } else {
                        String::from("Add Breakpoint")
                    };
                    let cond_label = if has_cond {
                        String::from("Edit Condition\u{2026}")
                    } else {
                        String::from("Add Conditional Breakpoint\u{2026}")
                    };
                    let log_label = if has_log {
                        String::from("Edit Logpoint")
                    } else {
                        String::from("Add Logpoint")
                    };
                    let mut items = vec![
                        (toggle_label, MenuAction::ToggleBreakpointAt { line }),
                        (cond_label, MenuAction::EditBreakpointConditionAt { line }),
                        (log_label, MenuAction::EditLogpointAt { line }),
                    ];
                    // The resident navigator's line-scoped ask, only while
                    // one is seated (`line` here is 1-based, the box 0-based).
                    if self.pair_host.is_some() {
                        items.push((
                            String::from("Ask Navigator"),
                            MenuAction::AskNavigatorAt {
                                line: line.saturating_sub(1),
                            },
                        ));
                    }
                    self.context_menu = Some(ContextMenu::flat(
                        (m.column, m.row),
                        items,
                        self.tree.root.clone(),
                    ));
                    return;
                }
                // Editor body: right-click over a text buffer opens the symbol
                // menu (Go to Definition / Rename Symbol / Change All
                // Occurrences). Read-only diff / sheet / image tabs have no
                // symbols, so they're excluded.
                if in_editor
                    && self.editor.diff.is_none()
                    && self.editor.sheet.is_none()
                    && self.editor.image.is_none()
                    && let Some((row, col)) = self.editor.buffer_pos_at(m.column, m.row)
                {
                    self.focus_pane(Pane::Editor);
                    let mut items = vec![(
                        String::from("Go to Definition"),
                        MenuAction::GoToDefinitionAt { row, col },
                    )];
                    // Only offer "Go to Declaration" when this file's language
                    // server actually implements `textDocument/declaration`.
                    // TypeScript's vtsls advertises `declarationProvider: false`,
                    // so the row is hidden there, exactly as VS Code does.
                    if self.editor_language_supports_declaration() {
                        items.push((
                            String::from("Go to Declaration"),
                            MenuAction::GoToDeclarationAt { row, col },
                        ));
                    }
                    // "Go to Type Definition" is offered only when the server
                    // implements `textDocument/typeDefinition` (vtsls,
                    // basedpyright, rust-analyzer and gopls all do), mirroring
                    // VS Code's ordering right after Go to Declaration.
                    if self.editor_language_supports_type_definition() {
                        items.push((
                            String::from("Go to Type Definition"),
                            MenuAction::GoToTypeDefinitionAt { row, col },
                        ));
                    }
                    // "Go to Implementations" is offered only when the server
                    // implements `textDocument/implementation` (rust-analyzer,
                    // gopls, vtsls do), placed right after Type Definition to
                    // mirror VS Code's Go To submenu order.
                    if self.editor_language_supports_implementation() {
                        items.push((
                            String::from("Go to Implementations"),
                            MenuAction::GoToImplementationAt { row, col },
                        ));
                    }
                    // "Go to References" is offered only when the server
                    // implements `textDocument/references` (every server croft
                    // ships does), placed last in the Go To group to mirror VS
                    // Code's submenu order.
                    if self.editor_language_supports_references() {
                        items.push((
                            String::from("Go to References"),
                            MenuAction::GoToReferencesAt { row, col },
                        ));
                    }
                    // Call hierarchy, one level per invocation: who calls
                    // this (incoming) and what does this call (outgoing).
                    if self.editor_language_supports_call_hierarchy() {
                        items.push((
                            String::from("Show Incoming Calls"),
                            MenuAction::ShowCallsAt {
                                row,
                                col,
                                incoming: true,
                            },
                        ));
                        items.push((
                            String::from("Show Outgoing Calls"),
                            MenuAction::ShowCallsAt {
                                row,
                                col,
                                incoming: false,
                            },
                        ));
                    }
                    items.push((String::from("Go Back"), MenuAction::NavigateBack));
                    items.push((String::from("Go Forward"), MenuAction::NavigateForward));
                    items.push((
                        String::from("Rename Symbol"),
                        MenuAction::RenameSymbolAt { row, col },
                    ));
                    items.push((
                        String::from("Change All Occurrences"),
                        MenuAction::ChangeAllOccurrencesAt { row, col },
                    ));
                    if self.editor_language_supports_code_action() {
                        items.push((
                            String::from("Quick Fix"),
                            MenuAction::QuickFixAt { row, col },
                        ));
                    }
                    // The navigator's selection-scoped ask (GitHub-review
                    // style), only while one is seated and lines are selected.
                    if self.pair_host.is_some()
                        && let Some((start, end)) = self.editor.selection_rows()
                    {
                        items.push((
                            String::from("Ask Navigator About Selection"),
                            MenuAction::AskNavigatorSelection { start, end },
                        ));
                    }
                    self.context_menu = Some(ContextMenu::flat(
                        (m.column, m.row),
                        items,
                        self.tree.root.clone(),
                    ));
                }
            }
            MouseEventKind::Down(MouseButton::Left) => {
                // Markdown/rendered preview selection (#215): a press inside
                // the rendered view starts a drag-selection over what the
                // user can SEE, not the source buffer beneath it.
                if self.begin_preview_selection(m.column, m.row) {
                    return;
                }
                // Before the selection: a Ctrl+click on a printed
                // `path:line` follows it rather than starting a drag (#257).
                if m.modifiers.contains(KeyModifiers::CONTROL)
                    && self.log_file_click(m.column, m.row)
                {
                    return;
                }
                if self.begin_log_selection(m.column, m.row) {
                    return;
                }
                // (H) Go to Definition rides CTRL, matching the terminal pane's
                // file/URL clicks. SGR mouse reporting carries no super bit, so
                // ALT is left to the editor's Alt+click multi-cursor below.
                if in_editor && m.modifiers.contains(KeyModifiers::CONTROL) {
                    if m.modifiers.contains(KeyModifiers::SHIFT) {
                        self.nav_back();
                    } else {
                        self.trigger_definition_at(m.column, m.row);
                    }
                    return;
                }
                // Merge-conflict accept actions on a conflict header row —
                // the [Accept …] spans the editor paints, VS Code's
                // merge-conflict CodeLens clicks. Checked before every other
                // editor click: the header row is marker text, so a caret
                // placement there serves nobody. A stale span cannot
                // mis-fire — `resolve_conflict_at` re-validates the row
                // against the live conflict set.
                if in_editor && self.editor.diff.is_none() {
                    let hit = self
                        .editor
                        .merge_action_spans
                        .iter()
                        .find(|(y, xs, _, _)| *y == m.row && xs.contains(&m.column))
                        .map(|(_, _, row, res)| (*row, *res));
                    if let Some((row, res)) = hit {
                        self.focus_pane(Pane::Editor);
                        self.editor.clear_selection();
                        self.editor.cursor_row = row;
                        self.editor.cursor_col = 0;
                        self.resolve_merge_at_cursor(res);
                        return;
                    }
                }
                // Merge editor (#253): a click on a source pane's
                // per-conflict checkbox toggles that side's inclusion
                // (both checked = Accept Combination). Any other click in
                // the source-pane area is swallowed — the panes are
                // read-only; the Result below keeps normal click behavior.
                if in_editor && self.editor.merge.is_some() {
                    let (check_hit, in_panes) = self
                        .editor
                        .merge
                        .as_ref()
                        .map(|mv| {
                            (
                                mv.check_spans
                                    .iter()
                                    .find(|(y, xs, _, _)| *y == m.row && xs.contains(&m.column))
                                    .map(|(_, _, idx, side)| (*idx, *side)),
                                mv.last_panes_area.contains(ratatui::layout::Position {
                                    x: m.column,
                                    y: m.row,
                                }),
                            )
                        })
                        .unwrap_or((None, false));
                    if let Some((idx, side)) = check_hit {
                        self.focus_pane(Pane::Editor);
                        self.merge_toggle_side(idx, side);
                        return;
                    }
                    if in_panes {
                        self.focus_pane(Pane::Editor);
                        return;
                    }
                }
                if !in_editor {
                    self.editor_click.clear();
                }
                if !in_tree {
                    self.tree_click.clear();
                }
                // Splitter hit-test runs before everything else: clicking the
                // single-column seam between sidebar and editor (or the
                // single-row seam between editor and terminal) starts a
                // resize drag instead of falling through to the underlying
                // pane's click handler.
                if let Some(x) = self.sidebar_splitter_x {
                    // Two-column hit-zone: the seam itself (`x`, the editor's
                    // left edge) and one column to the left (the tree's right
                    // border). Either grab starts a sidebar drag — a 1-cell
                    // target is too easy to miss.
                    //
                    // The OUTLINE panel draws no right border, so its scrollbar
                    // sits on the sidebar's rightmost column (`x - 1`), inside
                    // this zone. Exempt that column when it's the outline bar so
                    // the press reaches the scrollbar handler below instead of
                    // being swallowed as a resize.
                    //
                    // Likewise a lone terminal pane's left border shares this
                    // column, and its command decoration dots live there: a
                    // press on a dot cell must reach the decoration handler,
                    // not start a resize (the rest of the column still drags).
                    // The COMMITS graph draws no right border either, so its
                    // scrollbar shares the same column (Codeberg #41).
                    // Both scrollbar rects refresh only while their widget
                    // renders (outline under Explorer, the graph under
                    // Source Control), so each exemption is gated on its
                    // view — a stale rect from the last visit must not keep
                    // deadening the seam after a view switch.
                    let outline_bar = self.sidebar_view == SidebarView::Explorer
                        && rect_contains(self.outline.last_scrollbar, m.column, m.row);
                    let graph_bar = self.sidebar_view == SidebarView::SourceControl
                        && rect_contains(self.commit_graph.last_scrollbar, m.column, m.row);
                    // A collapsed terminal pane's one-column strip shares this
                    // zone too (#468): the leftmost pane starts on the seam
                    // itself, and with the side bar on the right the last
                    // pane ends one column short of it. The strip's only
                    // gesture is the click that unfolds it, so the seam must
                    // not take that click as a resize, or a folded pane on
                    // that edge can never be brought back. The rects are
                    // cleared whenever the panel is not painted, so a stale
                    // strip cannot deaden the seam later.
                    let on_strip = self
                        .terminal_strip_rects
                        .iter()
                        .any(|r| rect_contains(*r, m.column, m.row));
                    if (m.column == x || m.column == x.saturating_sub(1))
                        && !on_strip
                        && !outline_bar
                        && !graph_bar
                        && self.decoration_dot_at(m.column, m.row).is_none()
                    {
                        self.splitter_drag = Some(SplitterDrag::Sidebar);
                        return;
                    }
                }
                // Any seam between editor groups in the grid (any depth). Same
                // two-cell hit-zone as the other seams.
                if let Some(seam) = self.seam_at(m.column, m.row) {
                    self.splitter_drag = Some(SplitterDrag::EditorSeam(seam));
                    return;
                }
                // OPEN EDITORS: header toggles collapse; a row activates that
                // editor's tab; the scrollbar lane starts a thumb drag. Any
                // other click is swallowed so it can't fall through to a panel
                // visually beneath this one.
                if rect_contains(self.open_editors.last_area, m.column, m.row) {
                    if rect_contains(self.open_editors.last_scrollbar, m.column, m.row) {
                        self.open_editors.scroll_to_bar_y(m.row);
                        self.open_editors_scrollbar_drag = true;
                    } else if self.open_editors.hit_header(m.column, m.row) {
                        self.open_editors.toggle_collapse();
                    } else if let Some(idx) = self.open_editors.row_at(m.row)
                        && let Some(path) = self.open_editors.path_at(idx)
                    {
                        self.activate_open_editor(path);
                    }
                    return;
                }
                // TIMELINE: header toggles collapse; a row opens that commit's
                // diff for the file in a read-only editor tab.
                if rect_contains(self.timeline.last_area, m.column, m.row) {
                    if rect_contains(self.timeline.last_scrollbar, m.column, m.row) {
                        self.timeline.scroll_to_bar_y(m.row);
                        self.timeline_scrollbar_drag = true;
                    } else if self.timeline.hit_header(m.column, m.row) {
                        self.timeline.toggle_collapse();
                    } else if let Some(idx) = self.timeline.row_at(m.row)
                        && let Some((path, hash)) = self.timeline.diff_target(idx)
                    {
                        self.open_timeline_diff(path, hash);
                    }
                    return;
                }
                // DEPENDENCIES: display-only, so only the header (collapse)
                // and the scrollbar lane are interactive.
                if rect_contains(self.dependencies.last_area, m.column, m.row) {
                    if rect_contains(self.dependencies.last_scrollbar, m.column, m.row) {
                        self.dependencies.scroll_to_bar_y(m.row);
                        self.deps_scrollbar_drag = true;
                    } else if self.dependencies.hit_header(m.column, m.row) {
                        self.dependencies.toggle_collapse();
                    }
                    return;
                }
                // The OUTLINE section stacks just above the SYSTEM panel. A
                // click on its header toggles collapse; a click on a symbol row
                // jumps the editor to that symbol (recording nav history, like
                // go-to-definition); any other click inside its rect is
                // swallowed so it doesn't fall through to the tree above.
                if rect_contains(self.outline.last_area, m.column, m.row) {
                    if rect_contains(self.outline.last_scrollbar, m.column, m.row) {
                        self.outline.scroll_to_bar_y(m.row);
                        self.outline_scrollbar_drag = true;
                    } else if self.outline.hit_header(m.column, m.row) {
                        self.outline.toggle_collapse();
                    } else if let Some(idx) = self.outline.row_at(m.row)
                        && let Some((path, line, col)) = self.outline.jump_target(idx)
                    {
                        self.go_to_definition(path, line, col);
                    }
                    return;
                }
                // The panel group's tabs sit on the splitter row, so they must
                // win the hit-test before the splitter-drag handler claims the
                // click (same precedence as the "[+]" / "[-]" buttons below).
                if rect_contains(self.problems_tab_rect, m.column, m.row) {
                    self.set_bottom_panel_tab(BottomPanelTab::Problems);
                    return;
                }
                if rect_contains(self.output_tab_rect, m.column, m.row) {
                    self.set_bottom_panel_tab(BottomPanelTab::Output);
                    return;
                }
                if rect_contains(self.terminal_tab_rect, m.column, m.row) {
                    self.set_bottom_panel_tab(BottomPanelTab::Terminal);
                    return;
                }
                if rect_contains(self.ports_tab_rect, m.column, m.row) {
                    self.set_bottom_panel_tab(BottomPanelTab::Ports);
                    return;
                }
                if rect_contains(self.captures_tab_rect, m.column, m.row) {
                    self.set_bottom_panel_tab(BottomPanelTab::Captures);
                    return;
                }
                // A click in the OUTPUT view hits its toolbar (dropdown / clear /
                // rpc / level) or dropdown list; if it lands in the log body the
                // widget doesn't consume it, so we just focus the panel pane.
                if self.bottom_panel_tab == BottomPanelTab::Output
                    && rect_contains(self.output.last_area, m.column, m.row)
                {
                    if !self.output.click(m.column, m.row) {
                        self.focus_pane(Pane::Terminal);
                    }
                    return;
                }
                // A click in the PROBLEMS list jumps the editor to that
                // diagnostic, or toggles a file group. Checked before the
                // terminal/splitter logic because the terminals are not
                // painted while this tab is active.
                if self.bottom_panel_tab == BottomPanelTab::Problems
                    && rect_contains(self.problems.last_area, m.column, m.row)
                {
                    use crate::widgets::problems::ProblemHit;
                    // Toolbar buttons (severity filter / group toggle) consume
                    // the click before it resolves to a row.
                    if self.problems.click(m.column, m.row) {
                        return;
                    }
                    match self.problems.hit_at(m.row) {
                        Some(ProblemHit::Header(path)) => self.problems.toggle_collapse(&path),
                        Some(ProblemHit::Diagnostic {
                            path,
                            line,
                            col,
                            col_utf16,
                        }) => {
                            // An LSP diagnostic's column is UTF-16; a build
                            // tool's is already a character column.
                            let opened = if col_utf16 {
                                self.open_at_utf16(&path, line, col)
                            } else {
                                self.open_at(&path, line as usize, col as usize)
                            };
                            if let Err(e) = opened {
                                self.status = format!("Open failed: {e}");
                            }
                        }
                        None => self.focus_pane(Pane::Terminal),
                    }
                    return;
                }
                // A click in the PORTS list selects that row (so the keyboard
                // actions act on it) or focuses the pane.
                if self.bottom_panel_tab == BottomPanelTab::Ports
                    && rect_contains(self.ports.last_area, m.column, m.row)
                {
                    match self.ports.row_at(m.column, m.row) {
                        Some(idx) => {
                            self.ports.select_index(idx);
                            // A second click on the same row opens that port,
                            // the same as pressing Enter on it.
                            let now = std::time::Instant::now();
                            if self
                                .ports_click
                                .is_double(now, m.column, m.row, m.modifiers)
                            {
                                self.ports_open_selected();
                                self.ports_click.clear();
                            } else {
                                self.ports_click.record(now, m.column, m.row, m.modifiers);
                            }
                        }
                        None => self.focus_pane(Pane::Terminal),
                    }
                    return;
                }
                // A click on a CAPTURES row jumps straight to the captured
                // line (iTerm2's captured-output click).
                if self.bottom_panel_tab == BottomPanelTab::Captures
                    && rect_contains(self.captures.last_area, m.column, m.row)
                {
                    match self.captures.row_at(m.column, m.row) {
                        Some(idx) => {
                            self.captures.select_index(idx);
                            self.captures_open_selected();
                        }
                        None => self.focus_pane(Pane::Terminal),
                    }
                    return;
                }
                // The "[+]" / "[-]" buttons sit on the same row as the
                // editor/terminal splitter, so they have to win the
                // hit-test before the splitter-drag handler claims this
                // click. Each terminal pane has its own pair so the user
                // can kill any pane, not only the active one.
                if let Some(idx) = self
                    .terminal_close_buttons
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    if self.close_terminal_at(idx) {
                        self.status =
                            format!("Closed terminal: {} remaining", self.terminals.len());
                    }
                    return;
                }
                if let Some(idx) = self
                    .terminal_profile_buttons
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    self.open_terminal_profile_picker(idx);
                    return;
                }
                if let Some(idx) = self
                    .terminal_collapse_buttons
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    self.toggle_terminal_collapse(idx);
                    return;
                }
                // A strip is one column wide, so it is tested before the
                // splitter and the pane body below: anything that claims the
                // click first makes a folded pane impossible to unfold.
                if let Some(idx) = self
                    .terminal_strip_rects
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    self.toggle_terminal_collapse(idx);
                    return;
                }
                if let Some(idx) = self
                    .terminal_max_buttons
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    // Entering maximize mode hands the clicked pane the
                    // panel; the button on the maximized pane restores.
                    if !self.terminal_pane_maximized {
                        self.active_terminal = idx;
                        self.focus_pane(Pane::Terminal);
                    }
                    self.toggle_terminal_pane_maximize();
                    return;
                }
                if let Some(idx) = self
                    .terminal_rail_rects
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    self.active_terminal = idx;
                    self.focus_pane(Pane::Terminal);
                    // Holding the press arms a drag-reorder: crossing other
                    // rail rows live-moves this terminal between them.
                    self.terminal_drag_from = Some(idx);
                    return;
                }
                if let Some(idx) = self
                    .terminal_label_rects
                    .iter()
                    .position(|r| rect_contains(*r, m.column, m.row))
                {
                    // The pane name pill is the drag handle for reordering
                    // side-by-side panes (VS Code drags its terminal tabs the
                    // same way). The press itself focuses the pane, exactly
                    // like a click into its body would.
                    self.active_terminal = idx;
                    self.focus_pane(Pane::Terminal);
                    self.terminal_drag_from = Some(idx);
                    return;
                }
                if self
                    .terminal_add_buttons
                    .iter()
                    .any(|r| rect_contains(*r, m.column, m.row))
                {
                    match self.split_terminal() {
                        Ok(()) => {
                            self.status =
                                format!("Split terminal: {} active", self.terminals.len());
                        }
                        Err(e) => {
                            self.status = format!("Split terminal failed: {e}");
                        }
                    }
                    return;
                }
                if let Some(y) = self.terminal_splitter_y {
                    // Two-row hit-zone: the terminal's top border (`y`) and
                    // the editor / welcome's bottom border (`y - 1`).
                    // Symmetric with the sidebar drag — either edge of the
                    // visible seam grabs the splitter.
                    //
                    // Gate by column too: the editor / terminal splitter
                    // only spans the RIGHT column (everything at or past
                    // `sidebar_splitter_x`). Without this gate, a click
                    // on a tree row in the LEFT column whose y lines up
                    // with the splitter is silently hijacked into a
                    // splitter-drag and never reaches `node_at_y` -
                    // exactly the dead-zone the user hit on the last
                    // two files in the Explorer.
                    let in_splitter_x_range = self.sidebar_splitter_x.is_none_or(|x| m.column >= x);
                    if in_splitter_x_range && (m.row == y || m.row == y.saturating_sub(1)) {
                        self.splitter_drag = Some(SplitterDrag::Terminal);
                        return;
                    }
                }
                // Activity-bar hit-test takes precedence over the side panel.
                if rect_contains(self.sidebar_areas.explorer_icon, m.column, m.row) {
                    self.set_sidebar_view(SidebarView::Explorer);
                    return;
                }
                if rect_contains(self.sidebar_areas.search_icon, m.column, m.row) {
                    self.set_sidebar_view(SidebarView::Search);
                    return;
                }
                if rect_contains(self.sidebar_areas.source_control_icon, m.column, m.row) {
                    self.set_sidebar_view(SidebarView::SourceControl);
                    return;
                }
                if rect_contains(self.sidebar_areas.remote_icon, m.column, m.row) {
                    self.set_sidebar_view(SidebarView::Remote);
                    return;
                }
                if rect_contains(self.sidebar_areas.run_debug_icon, m.column, m.row) {
                    self.set_sidebar_view(SidebarView::RunDebug);
                    return;
                }
                if rect_contains(self.sidebar_areas.extensions_icon, m.column, m.row) {
                    self.set_sidebar_view(SidebarView::Extensions);
                    return;
                }
                if rect_contains(self.sidebar_areas.testing_icon, m.column, m.row) {
                    self.open_testing_view();
                    return;
                }
                if rect_contains(self.sidebar_areas.settings_icon, m.column, m.row) {
                    self.open_settings_menu();
                    return;
                }
                if in_tree_scrollbar {
                    self.focus_pane(Pane::Tree);
                    self.tree.scroll_to_bar_y(m.row);
                    self.scrollbar_drag = Some(Pane::Tree);
                    self.tree_click.clear();
                    return;
                }
                if in_remote_scrollbar {
                    self.focus_pane(Pane::Tree);
                    self.remote.scroll_to_bar_y(m.row);
                    self.scrollbar_drag = Some(Pane::Tree);
                    self.tree_click.clear();
                    return;
                }
                if in_search_scrollbar {
                    self.focus_pane(Pane::Tree);
                    self.search.scroll_to_bar_y(m.row);
                    self.scrollbar_drag = Some(Pane::Tree);
                    self.tree_click.clear();
                    return;
                }
                if rect_contains(self.minimap_img_rect, m.column, m.row) {
                    self.focus_pane(Pane::Editor);
                    self.minimap_scroll_to_row(m.row);
                    self.minimap_drag = true;
                    self.editor_click.clear();
                    return;
                }
                if in_editor_scrollbar {
                    self.focus_pane(Pane::Editor);
                    self.editor.scroll_to_bar_y(m.row);
                    self.scrollbar_drag = Some(Pane::Editor);
                    self.editor_click.clear();
                    self.poke_cursor();
                    return;
                }
                if in_editor_hscrollbar {
                    self.focus_pane(Pane::Editor);
                    self.editor.scroll_to_bar_x(m.column);
                    self.editor_hscrollbar_drag = true;
                    self.editor_click.clear();
                    self.poke_cursor();
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::Search {
                    self.focus_pane(Pane::Tree);
                    if self.search.paste_button_at(m.column, m.row) {
                        let text = (self.clipboard_reader)();
                        self.paste_clipboard_into_search(text.as_deref());
                        return;
                    }
                    // Header "Refresh" re-runs the current query.
                    if self.search.refresh_at(m.column, m.row) {
                        self.submit_search_query();
                        return;
                    }
                    // Header "Clear Search Results" wipes the query + results.
                    if self.search.clear_at(m.column, m.row) {
                        self.search.clear_all();
                        return;
                    }
                    // Left chevron expands/collapses the Replace row.
                    if self.search.chevron_at(m.column, m.row) {
                        self.search.toggle_replace();
                        return;
                    }
                    // "" ellipsis expands/collapses files-to-include/exclude.
                    if self.search.ellipsis_at(m.column, m.row) {
                        self.search.toggle_details();
                        return;
                    }
                    // Replace-all action icon runs Replace All across results.
                    if self.search.replace_all_at(m.column, m.row) {
                        self.run_search_replace_all();
                        return;
                    }
                    // Click inside one of the input boxes focuses that field.
                    if let Some(field) = self.search.field_at(m.column, m.row) {
                        self.search.focus_field(field);
                        return;
                    }
                    if let Some(t) = self.search.toggle_at(m.column, m.row) {
                        match t {
                            crate::widgets::search::SearchToggle::CaseSensitive => {
                                self.search.opts.case_sensitive = !self.search.opts.case_sensitive;
                            }
                            crate::widgets::search::SearchToggle::WholeWord => {
                                self.search.opts.whole_word = !self.search.opts.whole_word;
                            }
                            crate::widgets::search::SearchToggle::UseRegex => {
                                self.search.opts.use_regex = !self.search.opts.use_regex;
                            }
                        }
                        self.submit_search_query();
                        return;
                    }
                    // Click on a result row: open it. Mirrors the Explorer's
                    // preview/pin gesture — a single click opens the hit in
                    // the replaceable preview slot, a double-click pins the
                    // tab so moving on to the next result opens beside it
                    // instead of replacing the file under review.
                    if let Some(idx) = self.search.hit_at_y(m.row) {
                        self.search.selected = idx;
                        let now = std::time::Instant::now();
                        let is_double =
                            self.tree_click.is_double(now, m.column, m.row, m.modifiers);
                        if let Some(hit) = self.search.selected_hit().cloned() {
                            self.open_search_hit(&hit);
                            if is_double {
                                self.editor.pin_active();
                            }
                        }
                        if is_double {
                            self.tree_click.clear();
                        } else {
                            self.tree_click.record(now, m.column, m.row, m.modifiers);
                        }
                    } else {
                        // Click on the input/header area: just focus search.
                    }
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::SourceControl {
                    self.focus_pane(Pane::Tree);
                    // COMMITS graph: header toggles collapse; a row opens that
                    // commit's full patch in a read-only tab. Checked first —
                    // its rect is carved out of the Source Control strip.
                    if rect_contains(self.commit_graph.last_area, m.column, m.row) {
                        if rect_contains(self.commit_graph.last_scrollbar, m.column, m.row) {
                            self.commit_graph.scroll_to_bar_y(m.row);
                            self.graph_scrollbar_drag = true;
                        } else if self.commit_graph.hit_header(m.column, m.row) {
                            self.commit_graph.toggle_collapse();
                        } else if let Some((hash, short)) = self
                            .commit_graph
                            .commit_at(m.row)
                            .map(|c| (c.hash.clone(), c.short_hash.clone()))
                        {
                            self.open_commit_patch(&hash, &short);
                        }
                        return;
                    }
                    if let Some(root) = self.source_control.click_repository(m.column, m.row) {
                        // Pin the panel to the clicked repository (#161);
                        // the next cross-folder focus releases it.
                        self.scm_pin = Some(root.clone());
                        self.seed_active_scm(root);
                        return;
                    }
                    if self.source_control.click_more(m.column, m.row) {
                        self.commit_menu_open = false;
                        self.scm_menu.open = !self.scm_menu.open;
                        if !self.scm_menu.open {
                            self.scm_menu.close();
                        }
                        return;
                    }
                    if self.source_control.click_header_refresh(m.column, m.row) {
                        self.refresh_source_control();
                        self.status = String::from("Refreshed Source Control");
                        return;
                    }
                    if self.commit_menu_open
                        && let Some(item) =
                            self.source_control.click_commit_menu_item(m.column, m.row)
                    {
                        self.commit_menu_open = false;
                        self.dispatch_commit_menu_item(item);
                        return;
                    }
                    if self.source_control.click_commit_caret(m.column, m.row) {
                        self.commit_menu_open = !self.commit_menu_open;
                        return;
                    }
                    if self.commit_menu_open {
                        // Any click outside the caret/menu closes the
                        // dropdown without firing its action; fall through
                        // so the underlying gesture still applies (the
                        // user can dismiss-by-clicking-elsewhere instead
                        // of needing Esc + click).
                        self.commit_menu_open = false;
                    }
                    if self.source_control.click_init_repo_button(m.column, m.row) {
                        self.initialize_repository();
                        return;
                    }
                    if self.source_control.click_button(m.column, m.row) {
                        self.commit_source_control();
                        return;
                    }
                    if self.source_control.click_input(m.column, m.row) {
                        return;
                    }
                    if self.source_control.click_branch(m.column, m.row) {
                        self.open_branch_picker();
                        return;
                    }
                    if let Some(idx) = self.source_control.click_discard_action(m.column, m.row) {
                        self.request_discard_source_control_entry(idx);
                        return;
                    }
                    if let Some(idx) = self.source_control.click_stage_action(m.column, m.row) {
                        self.stage_source_control_entry(idx);
                        return;
                    }
                    if let Some(idx) = self.source_control.click_unstage_action(m.column, m.row) {
                        self.unstage_source_control_entry(idx);
                        return;
                    }
                    if let Some(idx) = self.source_control.entry_at_y(m.row) {
                        self.open_source_control_entry(idx);
                    }
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::RunDebug {
                    self.focus_pane(Pane::Tree);
                    if self.run_debug.debug_active {
                        if let Some(widx) = self.run_debug.watch_remove_at(m.column, m.row) {
                            self.remove_watch_expression(widx);
                            self.refresh_debug_panel();
                        } else if let Some(idx) = self.run_debug.debug_row_at(m.row) {
                            self.debug_panel_click(idx);
                        }
                    } else if self.run_debug.click_button(m.column, m.row) {
                        self.run_debug_button_action();
                    } else if self.run_debug.click_config(m.column, m.row) {
                        self.open_debug_config_picker();
                    }
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::Extensions {
                    self.focus_pane(Pane::Tree);
                    // The filter's clear (✕) button empties the search.
                    if self.extensions.click_clear(m.column, m.row) {
                        self.extensions.clear_filter();
                        return;
                    }
                    // The refresh (⟳) button re-pulls the signed remote index.
                    if self.extensions.click_refresh(m.column, m.row) {
                        self.refresh_extension_index();
                        return;
                    }
                    // Clicking a row selects it; clicking its trash button
                    // uninstalls it; clicking its toggle switch (the right-edge
                    // pill) flips the extension. The trash zone sits left of the
                    // switch, so the two never overlap.
                    if let Some(idx) = self.extensions.row_at(m.row) {
                        let on_trash = self.extensions.click_uninstall(m.column, m.row);
                        let on_switch = self.extensions.click_action(m.column, m.row);
                        self.extensions.select(idx);
                        if on_trash {
                            self.uninstall_selected_extension();
                        } else if on_switch {
                            self.toggle_selected_extension();
                        }
                    }
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::Testing {
                    self.focus_pane(Pane::Tree);
                    // The scrollbar lane starts a thumb drag; elsewhere the play
                    // glyph runs a case or suite while a case's name reveals its
                    // source (VS Code's split: the label shows, the icon runs).
                    // Empty space does nothing.
                    if rect_contains(self.testing.last_scrollbar, m.column, m.row) {
                        self.testing.scroll_to_bar_y(m.row);
                        self.testing_scrollbar_drag = true;
                    } else {
                        match self.testing.hit_at(m.column, m.row) {
                            Some(crate::widgets::testing::RowHit::RunCase(name)) => {
                                self.run_test(name)
                            }
                            Some(crate::widgets::testing::RowHit::ShowCase(name)) => {
                                self.jump_to_test_source(name)
                            }
                            Some(crate::widgets::testing::RowHit::RunSuite(suite)) => {
                                self.run_suite(suite)
                            }
                            None => {}
                        }
                    }
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::Remote {
                    self.focus_pane(Pane::Tree);
                    if rect_contains(self.remote.header_chevron_btn, m.column, m.row) {
                        self.remote.toggle_collapsed();
                        self.status = if self.remote.collapsed {
                            String::from("Collapsed SSH section")
                        } else {
                            String::from("Expanded SSH section")
                        };
                        return;
                    }
                    if rect_contains(self.remote.header_add_btn, m.column, m.row)
                        || rect_contains(self.remote.empty_primary_btn, m.column, m.row)
                        || rect_contains(self.remote.empty_secondary_btn, m.column, m.row)
                    {
                        self.open_ssh_config_in_editor();
                        return;
                    }
                    if rect_contains(self.remote.header_refresh_btn, m.column, m.row) {
                        self.remote.refresh();
                        self.status = String::from("Reloaded SSH hosts from ~/.ssh/config");
                        return;
                    }
                    if rect_contains(self.remote.empty_learn_link, m.column, m.row) {
                        self.open_ssh_learn_more();
                        return;
                    }
                    if let Some(idx) = self.remote.target_at_y(m.row) {
                        self.remote.select(idx);
                        let now = std::time::Instant::now();
                        let is_double =
                            self.tree_click.is_double(now, m.column, m.row, m.modifiers);
                        if is_double {
                            if let Some(target) = self.remote.selected_target().cloned() {
                                self.request_remote_launch(target.alias, None);
                            }
                            self.tree_click.clear();
                        } else {
                            self.tree_click.record(now, m.column, m.row, m.modifiers);
                        }
                    }
                    return;
                }
                if in_tree && self.sidebar_view == SidebarView::Explorer {
                    self.focus_pane(Pane::Tree);
                    // Header toolbar (root folder row): New File / New Folder /
                    // Refresh / Collapse Folders. Checked before row hit-testing
                    // so a click on an icon never falls through to the node.
                    if rect_contains(self.tree.header_new_file_btn, m.column, m.row) {
                        let target = self.explorer_create_target_dir();
                        self.open_create_prompt(CreateKind::File, target);
                        return;
                    }
                    if rect_contains(self.tree.header_new_folder_btn, m.column, m.row) {
                        let target = self.explorer_create_target_dir();
                        self.open_create_prompt(CreateKind::Folder, target);
                        return;
                    }
                    if rect_contains(self.tree.header_refresh_btn, m.column, m.row) {
                        self.tree.refresh_children(0);
                        self.status = String::from("Refreshed Explorer");
                        return;
                    }
                    if rect_contains(self.tree.header_collapse_btn, m.column, m.row) {
                        self.tree.collapse_all();
                        self.status = String::from("Collapsed all folders");
                        return;
                    }
                    // The ⋯ "Views and More Actions" button on the EXPLORER
                    // title line opens the menu that toggles which sub-views
                    // (Open Editors / Folders / Outline / Timeline /
                    // Dependencies) are stacked in the panel.
                    if rect_contains(self.tree.header_views_btn, m.column, m.row) {
                        self.open_explorer_views_menu();
                        return;
                    }
                    // A left-click on the sticky band jumps: select the
                    // pinned ancestor and scroll it to the top of the tree
                    // (#117). Checked before the row map, which would answer
                    // for the covered row.
                    if let Some(idx) = self.tree.sticky_row_at(m.row) {
                        self.tree.select_replace(idx);
                        self.tree.scroll = idx;
                        self.tree_click.clear();
                        return;
                    }
                    if let Some(idx) = self.tree.node_at_y(m.row) {
                        let now = std::time::Instant::now();
                        let is_double =
                            self.tree_click.is_double(now, m.column, m.row, m.modifiers);
                        let has_shift = m.modifiers.contains(KeyModifiers::SHIFT);
                        // macOS terminals (iTerm2, Terminal.app) never put the
                        // Cmd bit on mouse events — the SGR mouse encoding only
                        // carries Shift/Alt/Ctrl. Treat Alt (Option on macOS)
                        // and Ctrl as the cherry-pick modifier so the gesture
                        // actually reaches the app.
                        let has_toggle_mod = m.modifiers.contains(KeyModifiers::ALT)
                            || m.modifiers.contains(KeyModifiers::CONTROL);
                        // Shift-click extends the range from the anchor. No
                        // activation, no drag.
                        if has_shift {
                            self.tree.extend_to(idx);
                            self.tree_click.clear();
                            self.tree_drag = None;
                            return;
                        }
                        // Alt/Ctrl-click: defer the toggle until mouse-up so a
                        // movement in between can promote the gesture into an
                        // Alt-drag (copy) instead. Don't activate (no file
                        // open, no folder toggle) and don't include the row
                        // in the multi-selection yet.
                        if has_toggle_mod {
                            self.tree_click.clear();
                            let mut drag_paths = self.tree.action_paths();
                            let path_clicked = self.tree.nodes[idx].path.clone();
                            if !drag_paths.iter().any(|p| p == &path_clicked) {
                                drag_paths.push(path_clicked);
                            }
                            self.tree_drag = Some(ExplorerDrag {
                                paths: drag_paths,
                                target_idx: None,
                                armed: false,
                                started_at: (now, m.column, m.row),
                                start_idx: idx,
                                toggle_on_release: true,
                            });
                            return;
                        }
                        // Plain click: if the row is already in the marked set,
                        // keep the marks intact so a subsequent drag carries
                        // every selected entry; otherwise collapse selection
                        // to this single row.
                        let already_marked = self.tree.marked.contains(&self.tree.nodes[idx].path);
                        if !already_marked {
                            self.tree.select_replace(idx);
                        } else {
                            self.tree.selected = idx;
                            self.tree.anchor = idx;
                        }
                        let clicked_is_dir =
                            self.tree.nodes.get(idx).is_some_and(|node| node.is_dir);
                        if clicked_is_dir && is_double {
                            self.tree_click.clear();
                            self.tree_drag = None;
                            return;
                        }
                        // Arm a potential drag-source. Movement off this cell
                        // promotes it into a real drag in the Drag handler;
                        // a stationary release keeps the click semantics.
                        let drag_paths = self.tree.action_paths();
                        if !drag_paths.is_empty() {
                            self.tree_drag = Some(ExplorerDrag {
                                paths: drag_paths,
                                target_idx: None,
                                armed: false,
                                started_at: (now, m.column, m.row),
                                start_idx: idx,
                                toggle_on_release: false,
                            });
                        }
                        if let Some(path) = self.tree.activate() {
                            let result = if is_double {
                                self.editor.open_pinned(&path)
                            } else {
                                self.editor.open_preview(&path)
                            };
                            match result {
                                Ok(()) => {
                                    self.sync_open_file_poll_mtime();
                                    self.status = self.editor.status.clone();
                                    // Opening a FILE hands the keyboard to the
                                    // editor (VS Code parity), single click or
                                    // double: otherwise the new tab's own
                                    // navigation keys are dead and a PDF sits
                                    // frozen on page 1 while the arrows walk
                                    // the file list. `activate()` returns None
                                    // for a folder, so a folder click never
                                    // reaches here and browsing keeps focus.
                                    self.focus_pane(Pane::Editor);
                                    self.poke_cursor();
                                }
                                Err(e) => self.status = format!("Error: {e}"),
                            }
                        }
                        if is_double {
                            self.tree_click.clear();
                        } else {
                            self.tree_click.record(now, m.column, m.row, m.modifiers);
                        }
                    }
                } else if in_editor_pane && !in_editor {
                    if let Some((line, col)) = self.editor.breadcrumb_target_at(m.column, m.row) {
                        // A click on a symbol crumb jumps to that symbol (same
                        // file); path crumbs return None and fall through.
                        self.focus_pane(Pane::Editor);
                        if let Some(path) = self.editor.path.clone() {
                            self.go_to_definition(path, line, col);
                        }
                        self.poke_cursor();
                    } else if let Some(idx) = self.editor.close_at(m.column, m.row) {
                        // The close cell of a pinned tab is an unpin button (it
                        // shows a thumb-tack, not the close cross), matching VS
                        // Code: a pinned tab is never closed by that click.
                        if self.editor.is_pinned(idx) {
                            self.editor.toggle_pin(idx);
                            self.status = String::from("Unpinned tab");
                            self.poke_cursor();
                        } else {
                            self.record_closed_tab_at(idx);
                            if self.editor.close_tab(idx) {
                                self.sync_open_file_poll_mtime();
                                self.status = String::from("Closed tab");
                                self.poke_cursor();
                                self.collapse_split_if_empty();
                            }
                        }
                    } else if let Some(idx) = self.editor.tab_at(m.column, m.row) {
                        self.focus_pane(Pane::Editor);
                        if self.editor.active_index() != idx {
                            self.editor.select(idx);
                            self.sync_open_file_poll_mtime();
                        }
                        self.poke_cursor();
                    }
                } else if in_editor {
                    self.focus_pane(Pane::Editor);
                    // A click on a pinned sticky-scroll header jumps to that
                    // scope instead of moving the caret into the covered line.
                    if let Some(line) = self.editor.sticky_line_at(m.column, m.row) {
                        if let Some(path) = self.editor.path.clone() {
                            self.go_to_definition(path, line, 0);
                        }
                        self.poke_cursor();
                        return;
                    }
                    // Mirror of the terminal branch: a selection lives in one
                    // pane only, so anchoring one in the editor drops any
                    // leftover terminal selection (issue #23).
                    self.terminal_mut().clear_selection();
                    // Sheet tab (#177): a click selects the cell under the
                    // pointer; the second click on the SAME selected cell
                    // opens the in-grid editor (editable kinds only).
                    if let Some(view) = self.editor.sheet.as_mut() {
                        if let Some((r, c)) = sheet_cell_at(view, m.column, m.row) {
                            let editable = matches!(
                                view.kind,
                                crate::sheet::SheetKind::Csv
                                    | crate::sheet::SheetKind::Tsv
                                    | crate::sheet::SheetKind::Xlsx
                            );
                            let current = view.current_sheet;
                            // An in-progress edit COMMITS when the
                            // click lands elsewhere (the spreadsheet
                            // convention; #193 review - discarding it
                            // silently lost the typed value).
                            let (pr, pc) = {
                                let d = &view.sheets[current];
                                (d.cur_row, d.cur_col)
                            };
                            let was_here = pr == r && pc == c;
                            if !was_here && let Some(edit) = view.editing.take() {
                                view.sheets[current].set_cell(pr, pc, edit.value);
                                view.dirty = true;
                                self.editor.dirty = true;
                            }
                            let view = self.editor.sheet.as_mut().expect("checked");
                            let data = &mut view.sheets[current];
                            data.cur_row = r;
                            data.cur_col = c;
                            if was_here && editable && view.editing.is_none() {
                                let value = view.sheets[current].cell(r, c).to_string();
                                let cursor = value.len();
                                view.editing = Some(crate::sheet::CellEdit { value, cursor });
                            }
                        }
                        self.poke_cursor();
                        return;
                    }
                    // Archive browser (#179): click selects; a second
                    // click on the selected row opens the member.
                    if let Some(view) = self.editor.archive.as_mut() {
                        if view.rows_visible > 0
                            && m.row >= view.rows_top
                            && m.row < view.rows_top + view.rows_visible
                        {
                            let idx = view.scroll + (m.row - view.rows_top) as usize;
                            if idx < view.entries.len() {
                                if view.selected == idx {
                                    self.open_selected_archive_member();
                                } else {
                                    view.selected = idx;
                                }
                            }
                        }
                        self.poke_cursor();
                        return;
                    }
                    // Hex tab (#172): a click on a byte cell — hex grid or
                    // ASCII gutter — parks the cursor there; Shift extends
                    // the selection; a drag from here extends it live.
                    if let Some(view) = self.editor.hex.as_mut() {
                        let rows = (view.layout.data_rows as usize).max(1);
                        if let Some(off) = view.hit_test(m.column, m.row) {
                            let select = m.modifiers.contains(KeyModifiers::SHIFT);
                            view.set_cursor(off, select, rows);
                        }
                        self.poke_cursor();
                        return;
                    }
                    // PDF preview: a plain click activates the link under the
                    // pointer — an external URL opens in the browser, an
                    // internal target flips to its page — matching every
                    // desktop PDF viewer. Only links anchored to text are
                    // found (pdftohtml reports link annotations through the
                    // text runs they cover), which is what hyperref/beamer
                    // emit. A non-link click just focuses the pane, above.
                    if self.editor.image.as_ref().is_some_and(|i| i.pdf.is_some()) {
                        match self.pdf_link_target_at(m.column, m.row) {
                            Some(crate::pdf::LinkTarget::Url(url)) => {
                                self.status = match open_url(&url) {
                                    Ok(()) => format!("Opened {url}"),
                                    Err(e) => format!("Could not open {url}: {e}"),
                                };
                            }
                            Some(crate::pdf::LinkTarget::Page(page)) => self.jump_pdf_page(page),
                            None => {}
                        }
                        return;
                    }
                    // Diff header arrows: take precedence over selection so a
                    // click on the ‹ / › glyph jumps to prev/next change
                    // instead of anchoring a selection at the header row.
                    if self.editor.diff.is_some() {
                        if rect_contains(self.editor.diff_prev_arrow, m.column, m.row) {
                            self.jump_diff_change(false);
                            return;
                        }
                        if rect_contains(self.editor.diff_next_arrow, m.column, m.row) {
                            self.jump_diff_change(true);
                            return;
                        }
                        let now = std::time::Instant::now();
                        let is_double =
                            self.editor_click
                                .is_double(now, m.column, m.row, m.modifiers);
                        let last_inner = self.editor.last_inner;
                        if let Some(diff) = self.editor.diff.as_mut() {
                            if let Some((side, row_idx, char_col)) =
                                crate::widgets::editor::diff_hit_test(
                                    diff, last_inner, m.column, m.row,
                                )
                            {
                                if is_double {
                                    diff.select_word_at(side, row_idx, char_col);
                                } else {
                                    diff.start_selection(side, row_idx, char_col);
                                }
                            } else {
                                diff.clear_selection();
                            }
                        }
                        if is_double {
                            self.editor_click.clear();
                        } else {
                            self.editor_click.record(now, m.column, m.row, m.modifiers);
                        }
                        self.poke_cursor();
                        return;
                    }
                    // AI-stream stop button in the sign margin: cancel the
                    // pilot's stream (it reverts the streamed text). Checked
                    // before the play glyph, whose cell it borrows while a
                    // stream is live.
                    if self.editor.stream_stop_at(m.column, m.row) {
                        self.collab_cancel_stream();
                        return;
                    }
                    // Comment-box surfaces: ✕ Ignore dismisses the box; the
                    // footer's reply field (or the body) focuses it, placing
                    // the caret where the click landed in the field.
                    if let Some((id, hit)) = self.editor.comment_box_hit(m.column, m.row) {
                        use crate::widgets::editor::CommentHit;
                        match hit {
                            CommentHit::Ignore => self.ignore_comment_box(id),
                            CommentHit::Reply | CommentHit::Body => {
                                let keep = self.editor.comment_focus.take().filter(|f| f.id == id);
                                let mut focus =
                                    keep.unwrap_or(crate::widgets::editor::CommentFocus {
                                        id,
                                        reply: String::new(),
                                        cursor: 0,
                                    });
                                if hit == CommentHit::Reply {
                                    let text_x = self.editor.last_inner.x
                                        + self.editor.last_gutter_width
                                        + 1;
                                    // `╰ ❯ ` occupies 4 cells before the field.
                                    let rel = (m.column.saturating_sub(text_x) as usize)
                                        .saturating_sub(4);
                                    focus.cursor = rel.min(focus.reply.chars().count());
                                } else {
                                    focus.cursor = focus.reply.chars().count();
                                }
                                self.editor.comment_focus = Some(focus);
                            }
                        }
                        return;
                    }
                    // Any other editor press releases a focused reply field.
                    if self.editor.comment_focus.is_some() {
                        self.editor.comment_focus = None;
                    }
                    // Gutter play glyph: run the test fn defined on the
                    // clicked line (VS Code's run bead); Alt+click debugs it
                    // instead. Sits in the sign margin one cell left of the
                    // fold chevron, checked before the editor-body Alt+click
                    // caret so the modifier never adds a caret here.
                    if let Some(name) = self.editor.test_glyph_at(m.column, m.row) {
                        if m.modifiers.contains(KeyModifiers::ALT) {
                            self.debug_named_test(name);
                        } else {
                            self.run_named_test(name);
                        }
                        return;
                    }
                    // Fold chevron in the gutter: toggle the fold, don't anchor
                    // a selection or move the cursor into the (possibly hidden)
                    // body.
                    if self.editor.fold_chevron_at(m.column, m.row) {
                        self.poke_cursor();
                        return;
                    }
                    // VS Code Shift+Alt+drag: start a column (box) selection.
                    // Checked before the plain Alt+click caret so the two
                    // modifiers don't both fire.
                    if m.modifiers.contains(KeyModifiers::ALT)
                        && m.modifiers.contains(KeyModifiers::SHIFT)
                        && self.editor.begin_box_select(m.column, m.row)
                    {
                        self.poke_cursor();
                        return;
                    }
                    // VS Code Alt+click: add (or toggle off) a secondary caret
                    // at the click instead of moving the single cursor.
                    if m.modifiers.contains(KeyModifiers::ALT)
                        && !m.modifiers.contains(KeyModifiers::SHIFT)
                        && self.editor.add_caret_at_screen(m.column, m.row)
                    {
                        self.poke_cursor();
                        return;
                    }
                    let now = std::time::Instant::now();
                    let is_double = self
                        .editor_click
                        .is_double(now, m.column, m.row, m.modifiers);
                    if is_double {
                        self.editor.select_word_at(m.column, m.row);
                        self.editor_click.clear();
                    } else {
                        // Anchor a fresh selection at the click; a drag widens it,
                        // a clean click ends up cleared on mouse-up.
                        self.editor.mouse_down(m.column, m.row);
                        self.editor_click.record(now, m.column, m.row, m.modifiers);
                    }
                    self.poke_cursor();
                } else if let Some(idx) = terminal_hit {
                    self.activate_terminal_pane(idx);
                    self.focus_pane(Pane::Terminal);
                    // Click on a gutter decoration dot (the pane's left
                    // border): open the command's action menu (VS Code's
                    // decoration menu), headed by its outcome.
                    if let Some(d) = self.terminal().decoration_at_screen(m.column, m.row) {
                        self.open_command_decoration_menu((m.column, m.row), d);
                        return;
                    }
                    // Cmd/Ctrl+click on a printed URL opens it (forwarding a
                    // remote dev-server port first), mirroring the editor's
                    // go-to-definition modifier. Consumes the click so it
                    // doesn't also start a text selection.
                    if (m.modifiers.contains(KeyModifiers::SUPER)
                        || m.modifiers.contains(KeyModifiers::CONTROL))
                        && (self.terminal_url_click(m.column, m.row)
                            || self.terminal_file_click(m.column, m.row))
                    {
                        return;
                    }
                    // A child tracking the mouse (Claude Code's diff panel,
                    // htop, lazygit, vim with `mouse=a`) gets the click
                    // itself (#474): an SGR/X10 press now, motion under
                    // 1002/1003 as the drag goes, and the release on
                    // mouse-up, all aimed at THIS pane via
                    // `terminal_pointer_forwarded`. Shift is the bypass,
                    // the same one the wheel has: croft's own selection when
                    // held. `report_mouse` is the whole gate -- it declines
                    // when the child is not tracking or the cell is on the
                    // border, and either way the click falls through to the
                    // selection below. The Cmd/Ctrl link-open above still
                    // wins, as in VS Code and iTerm2: the modifier is
                    // croft's, and Cmd has no mouse-report encoding anyway.
                    // A stale croft highlight goes, as it does for a plain
                    // click anywhere else -- the user is aiming at the TUI,
                    // not at the text under it -- and the double-click
                    // tracker is not armed: the pair, if any, is the child's.
                    if !m.modifiers.contains(KeyModifiers::SHIFT)
                        && self.terminal_mut().report_mouse(
                            MouseButtonKind::Left,
                            MouseAction::Press,
                            m.column,
                            m.row,
                            mouse_mods(&m),
                        )
                    {
                        self.terminal_mut().clear_selection();
                        self.editor.clear_selection();
                        self.terminal_pointer_forwarded = Some(ForwardedPointer {
                            pane: self.terminals[idx].uid(),
                            press: (m.column, m.row),
                            selecting: false,
                        });
                        self.terminal_click.clear();
                        return;
                    }
                    // Shift+click extends the existing selection to the
                    // clicked cell (VS Code / iTerm2) instead of starting a
                    // fresh one.
                    if m.modifiers.contains(KeyModifiers::SHIFT)
                        && self.terminal().selection().is_some()
                    {
                        self.terminal_mut().extend_selection_to(m.column, m.row);
                        self.terminal_click.clear();
                        return;
                    }
                    // A selection belongs to exactly one pane: starting one in
                    // the terminal drops any leftover editor selection so the
                    // two panes never paint a highlight at once (issue #23).
                    self.editor.clear_selection();
                    let now = std::time::Instant::now();
                    let is_double =
                        self.terminal_click
                            .is_double(now, m.column, m.row, m.modifiers);
                    if is_double {
                        self.terminal_mut().select_word_at(m.column, m.row);
                        self.terminal_click.clear();
                    } else {
                        // Begin a fresh selection at the click cell. Without a
                        // drag this is a single cell (no area), so the selection
                        // ends up cleared on mouse-up. With a drag, this is the
                        // selection anchor.
                        self.terminal_mut().start_selection_at(m.column, m.row);
                        self.terminal_click
                            .record(now, m.column, m.row, m.modifiers);
                    }
                }
            }
            MouseEventKind::Drag(MouseButton::Left) => {
                if let Some(from) = self.terminal_drag_from {
                    // Live reorder: the moment the pointer crosses another
                    // pane (side-by-side) or rail row (maximize mode), the
                    // dragged terminal moves there and the drag follows it.
                    // No ghost or indicator needed - the panes themselves
                    // rearrange under the pointer, and `move_terminal` keeps
                    // the dragged pane active.
                    let target = if self.terminal_pane_maximized && self.terminals.len() > 1 {
                        self.terminal_rail_rects
                            .iter()
                            .position(|r| rect_contains(*r, m.column, m.row))
                    } else {
                        self.terminal_at_pos(m.column, m.row)
                    };
                    if let Some(to) = target
                        && to != from
                    {
                        self.move_terminal(from, to);
                        self.terminal_drag_from = Some(to);
                    }
                    return;
                }
                if let Some(kind) = self.splitter_drag.clone() {
                    self.handle_splitter_drag(kind, m.column, m.row);
                    return;
                }
                if self.minimap_drag {
                    self.minimap_scroll_to_row(m.row);
                    return;
                }
                if self.editor_hscrollbar_drag {
                    self.editor.scroll_to_bar_x(m.column);
                    self.poke_cursor();
                    return;
                }
                if self.outline_scrollbar_drag {
                    self.outline.scroll_to_bar_y(m.row);
                    return;
                }
                if self.open_editors_scrollbar_drag {
                    self.open_editors.scroll_to_bar_y(m.row);
                    return;
                }
                if self.timeline_scrollbar_drag {
                    self.timeline.scroll_to_bar_y(m.row);
                    return;
                }
                if self.deps_scrollbar_drag {
                    self.dependencies.scroll_to_bar_y(m.row);
                    return;
                }
                if self.testing_scrollbar_drag {
                    self.testing.scroll_to_bar_y(m.row);
                    return;
                }
                if self.graph_scrollbar_drag {
                    self.commit_graph.scroll_to_bar_y(m.row);
                    return;
                }
                if let Some(pane) = self.scrollbar_drag {
                    match pane {
                        Pane::Tree => match self.sidebar_view {
                            SidebarView::Explorer => {
                                self.tree.scroll_to_bar_y(m.row);
                            }
                            SidebarView::Remote => {
                                self.remote.scroll_to_bar_y(m.row);
                            }
                            SidebarView::SourceControl => {
                                self.source_control.scroll_to_bar_y(m.row);
                            }
                            SidebarView::Search => {
                                self.search.scroll_to_bar_y(m.row);
                            }
                            SidebarView::RunDebug => {}
                            SidebarView::Extensions => {}
                            SidebarView::Testing => {}
                        },
                        Pane::Editor => {
                            self.editor.scroll_to_bar_y(m.row);
                            self.poke_cursor();
                        }
                        Pane::Terminal => {}
                    }
                    return;
                }
                // Some terminals emit a Drag at the same cell as the Down even
                // when the user hasn't actually dragged. Only forget the prior
                // click when the pointer has truly moved off that cell.
                self.editor_click.clear_if_moved(m.column, m.row);
                self.tree_click.clear_if_moved(m.column, m.row);
                self.terminal_click.clear_if_moved(m.column, m.row);
                // The modified tracker gets the same cancellation. It was left
                // out when it was added, so a bound `ctrl+double_click` fired
                // across a drag where the built-in double correctly did not —
                // the one tracker not on this list behaved differently from
                // every other one for no reason a user could discover.
                self.modified_click.clear_if_moved(m.column, m.row);
                // A drag after a press that went to a mouse-tracking child
                // (#474) belongs to whoever can use it. A child that asked
                // for motion (1002/1003) gets it, at the pane that got the
                // press, clamped to that pane's grid so a pointer that
                // wanders out reports the edge cell instead of vanishing. A
                // child that asked only for clicks (1000: Claude Code) has
                // no use for a drag, so the drag is croft's text selection,
                // anchored at the PRESS cell on its first motion so nothing
                // is lost by the press having been forwarded, then extended
                // here -- on the ORIGIN pane, found by uid, not through
                // `terminal_mut()`: Cmd+] can move the active pane while the
                // button is held, and the generic drag path below would then
                // extend the wrong pane's selection and leave this one at its
                // one-cell anchor. Edge auto-scroll is armed only while the
                // origin is still the active pane, because the tick that
                // services it scrolls the active one. The child still gets
                // the release either way. A gesture whose pane is gone ends
                // here with nothing to deliver.
                if let Some(fp) = self.terminal_pointer_forwarded {
                    let Some(idx) = self.forwarded_pane_index(fp) else {
                        self.terminal_pointer_forwarded = None;
                        self.terminal_select_autoscroll = None;
                        return;
                    };
                    if self.terminals[idx].mouse_motion_reporting() {
                        let (col, row) = self.terminals[idx].clamp_to_grid(m.column, m.row);
                        // Motion reporting was just checked, so the verdict
                        // is known; `let _` says "already decided", not
                        // "ignored". The encoder re-checks the same modes
                        // as its own guard; the two are intentional.
                        let _ = self.terminals[idx].report_mouse(
                            MouseButtonKind::Left,
                            MouseAction::Motion,
                            col,
                            row,
                            mouse_mods(&m),
                        );
                        return;
                    }
                    if !fp.selecting {
                        self.terminals[idx].start_selection_at(fp.press.0, fp.press.1);
                        self.terminal_pointer_forwarded = Some(ForwardedPointer {
                            selecting: true,
                            ..fp
                        });
                    }
                    let dir = self.terminals[idx].drag_select_to(m.column, m.row);
                    self.terminal_select_autoscroll = (dir != 0 && idx == self.active_terminal)
                        .then_some(TerminalSelectAutoScroll {
                            dir,
                            col: m.column,
                            last: std::time::Instant::now(),
                        });
                    return;
                }
                // Terminal drag-selection is handled before the per-pane
                // branches so it keeps extending even when the pointer
                // leaves the pane: dragging past the bottom edge is how the
                // user grows a selection down through scrollback. The
                // returned direction arms edge auto-scroll (serviced each
                // main-loop tick); a pointer back inside the pane disarms it.
                if self.focus == Pane::Terminal && self.terminal().selection().is_some() {
                    let dir = self.terminal_mut().drag_select_to(m.column, m.row);
                    self.terminal_select_autoscroll =
                        (dir != 0).then_some(TerminalSelectAutoScroll {
                            dir,
                            col: m.column,
                            last: std::time::Instant::now(),
                        });
                    return;
                }
                if in_editor {
                    if self.editor.diff.is_some() {
                        let last_inner = self.editor.last_inner;
                        if let Some(diff) = self.editor.diff.as_mut()
                            && let Some((_, row_idx, char_col)) =
                                crate::widgets::editor::diff_hit_test(
                                    diff, last_inner, m.column, m.row,
                                )
                        {
                            diff.extend_selection_to(row_idx, char_col);
                        }
                        self.poke_cursor();
                        return;
                    }
                    if let Some(view) = self.editor.hex.as_mut() {
                        let rows = (view.layout.data_rows as usize).max(1);
                        if let Some(off) = view.hit_test(m.column, m.row) {
                            view.set_cursor(off, true, rows);
                        }
                        self.poke_cursor();
                        return;
                    }
                    if self.editor.box_selecting() {
                        self.editor.box_drag_to_screen(m.column, m.row);
                        self.poke_cursor();
                        return;
                    }
                    self.editor.mouse_drag(m.column, m.row);
                    self.poke_cursor();
                } else if in_tree {
                    match self.sidebar_view {
                        SidebarView::Explorer => {
                            // Promote to a real drag-and-drop the moment the
                            // pointer leaves the initiating cell.
                            if let Some(drag) = self.tree_drag.as_mut() {
                                let (_, sx, sy) = drag.started_at;
                                if m.column != sx || m.row != sy {
                                    drag.armed = true;
                                }
                                if drag.armed {
                                    drag.target_idx =
                                        drag_target_index(&self.tree, m.row, &drag.paths);
                                    self.tree.drag_target = drag.target_idx;
                                }
                            }
                            // While not dragging, treat continued movement as a
                            // range-extend from the initial anchor — just like
                            // VS Code's drag-to-select.
                            if self.tree_drag.as_ref().is_none_or(|d| !d.armed)
                                && self.tree.sticky_row_at(m.row).is_none()
                                && let Some(idx) = self.tree.node_at_y(m.row)
                            {
                                // Never extend the selection onto rows the
                                // sticky band covers — they are invisible
                                // under it (#126).
                                self.tree.select(idx);
                            }
                        }
                        SidebarView::Remote => {
                            if let Some(idx) = self.remote.target_at_y(m.row) {
                                self.remote.select(idx);
                            }
                        }
                        SidebarView::Search
                        | SidebarView::SourceControl
                        | SidebarView::RunDebug
                        | SidebarView::Extensions
                        | SidebarView::Testing => {}
                    }
                } else if in_terminal {
                    self.terminal_mut().extend_selection_to(m.column, m.row);
                } else if self.tree_drag.is_some() {
                    // Pointer dragged outside the tree pane: still keep the drag
                    // alive so dropping back inside lands; just clear the drop
                    // highlight so the user knows nothing will happen here.
                    if let Some(drag) = self.tree_drag.as_mut() {
                        drag.target_idx = None;
                    }
                    self.tree.drag_target = None;
                }
            }
            MouseEventKind::Up(MouseButton::Left) => {
                // The release of a press that was forwarded to a tracking
                // child goes to the same pane (#474), clamped to its grid
                // like the drag. `report_mouse` may decline if the child
                // dropped tracking mid-press, which is the child's own
                // choice; there is nothing croft should do with the release
                // instead. The pane is found by uid, so one closed under
                // the held button is simply gone rather than mistaken for
                // its neighbour. The whole gesture ends here, aimed at the
                // ORIGIN pane and never the active one: a click, or a drag
                // the child asked for, gets no copy-on-select, click-to-move,
                // annotation or secret popup; a drag the Drag arm turned into
                // croft's selection is finalised on that pane (`end_drag`,
                // then copy-on-select), the same tail the ordinary mouse-up
                // below runs for the active pane.
                if let Some(fp) = self.terminal_pointer_forwarded.take() {
                    if let Some(idx) = self.forwarded_pane_index(fp) {
                        let (col, row) = self.terminals[idx].clamp_to_grid(m.column, m.row);
                        self.terminals[idx].report_mouse(
                            MouseButtonKind::Left,
                            MouseAction::Release,
                            col,
                            row,
                            mouse_mods(&m),
                        );
                        if fp.selecting {
                            self.terminals[idx].end_drag();
                            if self.copy_on_select
                                && self.terminals[idx]
                                    .selection()
                                    .is_some_and(|s| s.has_area())
                            {
                                let text = self
                                    .terminal_text_for_copy(self.terminals[idx].selection_text());
                                if !text.is_empty() {
                                    copy_to_clipboard(&text);
                                }
                            }
                        }
                    }
                    self.terminal_select_autoscroll = None;
                    return;
                }
                // Releasing the button ends any terminal edge auto-scroll
                // and finalizes a drag-selection (the alt-screen content
                // anchor is captured at release).
                self.terminal_select_autoscroll = None;
                if self.focus == Pane::Terminal {
                    self.terminal_mut().end_drag();
                }
                // Copy-on-select (VS Code's terminal.integrated.copyOnSelection,
                // iTerm2's default): a finished terminal drag-selection lands
                // on the clipboard without the explicit Cmd+C. Silent — this
                // fires on every selection, so no status churn.
                if self.copy_on_select
                    && self.focus == Pane::Terminal
                    && self.terminal().selection().is_some_and(|s| s.has_area())
                {
                    let text = self.terminal_text_for_copy(self.terminal().selection_text());
                    if !text.is_empty() {
                        copy_to_clipboard(&text);
                    }
                }
                // A plain click on a redacted span shows the real value in
                // a popup (#360): the mask is paint-only, so this is the
                // one way to read it without a reveal window. Checked
                // before click-to-move, like the annotation popup: on the
                // prompt row a masked token yields its value rather than a
                // caret move, which is the useful answer for a secret.
                if self.focus == Pane::Terminal
                    && !self.terminal().selection().is_some_and(|s| s.has_area())
                    && let Some(secret) = self.terminal().redacted_at(m.column, m.row)
                {
                    self.terminal_drag_from = None;
                    if self.terminal().selection().is_some() {
                        self.terminal_mut().clear_selection();
                    }
                    self.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
                        secret,
                        (m.column, m.row),
                    ));
                    return;
                }
                // A plain click on an annotated span pops its note (checked
                // before click-to-move so a note near the prompt is still
                // readable).
                if self.focus == Pane::Terminal
                    && !self.terminal().selection().is_some_and(|s| s.has_area())
                    && let Some((_, note)) = self.terminal().annotation_at(m.column, m.row)
                {
                    // This early return skips the shared mouse-up tail, so
                    // run its cleanup here too: drop the pane-drag latch and
                    // the zero-area selection the mouse-down planted, or the
                    // clicked cell stays painted as a one-cell highlight.
                    self.terminal_drag_from = None;
                    if self.terminal().selection().is_some() {
                        self.terminal_mut().clear_selection();
                    }
                    self.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
                        note,
                        (m.column, m.row),
                    ));
                    return;
                }
                // Ghostty's click-to-move-cursor: a plain click (no drag
                // selection, no reordering, program not tracking the mouse)
                // on the shell's prompt row walks its cursor to the clicked
                // cell with synthesized arrow keys. Pane-local input: a
                // click is not typing, so broadcast never mirrors it.
                if self.focus == Pane::Terminal
                    && self.terminal_drag_from.is_none()
                    && self.terminal_copy_mode.is_none()
                    && !self.terminal().selection().is_some_and(|s| s.has_area())
                    && !self.terminal().mouse_reporting()
                    && let Some(bytes) = self.terminal().prompt_click_arrows(m.column, m.row)
                {
                    self.terminal_mut().write_input(&bytes);
                }
                // Releasing ends a pane drag-reorder; the order is already
                // final because the reorder is live during the drag.
                self.terminal_drag_from = None;
                // Finish a column (box) selection, keeping the carets it built.
                if self.editor.box_selecting() {
                    self.editor.end_box_select();
                    return;
                }
                if self.splitter_drag.take().is_some() {
                    return;
                }
                if std::mem::take(&mut self.minimap_drag) {
                    return;
                }
                if self.scrollbar_drag.take().is_some() {
                    return;
                }
                if std::mem::take(&mut self.editor_hscrollbar_drag) {
                    return;
                }
                if std::mem::take(&mut self.outline_scrollbar_drag) {
                    return;
                }
                if std::mem::take(&mut self.open_editors_scrollbar_drag) {
                    return;
                }
                if std::mem::take(&mut self.timeline_scrollbar_drag) {
                    return;
                }
                if std::mem::take(&mut self.deps_scrollbar_drag) {
                    return;
                }
                if std::mem::take(&mut self.testing_scrollbar_drag) {
                    return;
                }
                if std::mem::take(&mut self.graph_scrollbar_drag) {
                    return;
                }
                if let Some(drag) = self.tree_drag.take() {
                    self.tree.drag_target = None;
                    if drag.armed {
                        // Drag while Alt/Ctrl is held copies; default is move.
                        let copy = drag.toggle_on_release
                            || m.modifiers.contains(KeyModifiers::ALT)
                            || m.modifiers.contains(KeyModifiers::CONTROL);
                        let mode = if copy {
                            ExplorerClipMode::Copy
                        } else {
                            ExplorerClipMode::Cut
                        };
                        if let Some(target_idx) = drag.target_idx {
                            let target_dir = drop_target_dir(&self.tree, target_idx);
                            self.apply_paste_or_drop(&target_dir, &drag.paths, mode);
                        } else {
                            self.status = String::from("Drop cancelled");
                        }
                        return;
                    }
                    if drag.toggle_on_release {
                        // Stationary Alt/Ctrl-click: now perform the toggle.
                        self.tree.toggle_mark(drag.start_idx);
                        return;
                    }
                }
                // Mouse-up never auto-copies. The selection stays highlighted
                // so the user can hit Cmd/Ctrl+C themselves; a click without
                // drag (zero-area selection) is silently dropped.
                if in_terminal {
                    if let Some(sel) = self.terminal().selection()
                        && !sel.has_area()
                    {
                        self.terminal_mut().clear_selection();
                    }
                } else if in_editor
                    && let Some(sel) = self.editor.selection
                    && !sel.has_area()
                {
                    self.editor.clear_selection();
                }
            }
            MouseEventKind::ScrollDown => {
                if in_outline {
                    self.outline.scroll_down(3);
                } else if in_open_editors {
                    self.open_editors.scroll_down(3);
                } else if in_timeline {
                    self.timeline.scroll_down(3);
                } else if in_deps {
                    self.dependencies.scroll_down(3);
                } else if in_problems {
                    self.problems.scroll_down(3);
                } else if in_output {
                    self.output.scroll_down(3);
                } else if in_tree {
                    match self.sidebar_view {
                        SidebarView::Explorer => self.tree.scroll_down(3),
                        SidebarView::Remote => self.remote.scroll_down(3),
                        SidebarView::SourceControl => {
                            if rect_contains(self.commit_graph.last_area, m.column, m.row) {
                                self.commit_graph.scroll_down(3);
                            } else {
                                self.source_control.scroll_down(3);
                            }
                        }
                        SidebarView::Search => self.search.scroll_down(3),
                        SidebarView::RunDebug => {}
                        SidebarView::Extensions => self.extensions.scroll_down(3),
                        SidebarView::Testing => self.testing.scroll_down(3),
                    }
                } else if in_editor {
                    if let Some(diff) = self.editor.diff.as_mut() {
                        diff.scroll_down_by(3);
                    } else if self.editor.pdf_page().is_some() {
                        self.wheel_pdf_page(1);
                    } else if let Some(view) = self.editor.hex.as_mut() {
                        let rows = (view.layout.data_rows as usize).max(1);
                        view.scroll_by(3, rows);
                    } else {
                        self.editor.scroll_down(3);
                    }
                } else if rect_contains(self.terminal_rail_area, m.column, m.row) {
                    // The rail is its own scrollable list, like VS Code's
                    // terminal tabs. Paint clamps the offset.
                    self.terminal_rail_scroll = self.terminal_rail_scroll.saturating_add(1);
                } else if let Some(idx) = terminal_hit {
                    let shift = m.modifiers.contains(KeyModifiers::SHIFT);
                    let t = &mut self.terminals[idx];
                    // A child tracking the mouse (Claude Code, htop, vim) gets
                    // a real wheel report so it scrolls its own content. Shift
                    // bypasses that for croft's scrollback. A report that
                    // could not be delivered (the wheel sat on the pane
                    // BORDER, outside the inner grid) falls through like any
                    // non-tracking pane instead of swallowing the notch.
                    if t.mouse_reporting()
                        && !shift
                        && t.report_mouse(
                            MouseButtonKind::WheelDown,
                            MouseAction::Press,
                            m.column,
                            m.row,
                            mouse_mods(&m),
                        )
                    {
                    } else if !t.scroll_down(3) {
                        if t.app_cursor_keys() {
                            t.write_input(b"\x1bOB\x1bOB\x1bOB");
                        } else {
                            t.write_input(b"\x1b[B\x1b[B\x1b[B");
                        }
                    }
                }
            }
            MouseEventKind::ScrollUp => {
                if in_outline {
                    self.outline.scroll_up(3);
                } else if in_open_editors {
                    self.open_editors.scroll_up(3);
                } else if in_timeline {
                    self.timeline.scroll_up(3);
                } else if in_deps {
                    self.dependencies.scroll_up(3);
                } else if in_problems {
                    self.problems.scroll_up(3);
                } else if in_output {
                    self.output.scroll_up(3);
                } else if in_tree {
                    match self.sidebar_view {
                        SidebarView::Explorer => self.tree.scroll_up(3),
                        SidebarView::Remote => self.remote.scroll_up(3),
                        SidebarView::SourceControl => {
                            if rect_contains(self.commit_graph.last_area, m.column, m.row) {
                                self.commit_graph.scroll_up(3);
                            } else {
                                self.source_control.scroll_up(3);
                            }
                        }
                        SidebarView::Search => self.search.scroll_up(3),
                        SidebarView::RunDebug => {}
                        SidebarView::Extensions => self.extensions.scroll_up(3),
                        SidebarView::Testing => self.testing.scroll_up(3),
                    }
                } else if in_editor {
                    if let Some(diff) = self.editor.diff.as_mut() {
                        diff.scroll_up_by(3);
                    } else if self.editor.pdf_page().is_some() {
                        self.wheel_pdf_page(-1);
                    } else if let Some(view) = self.editor.hex.as_mut() {
                        let rows = (view.layout.data_rows as usize).max(1);
                        view.scroll_by(-3, rows);
                    } else {
                        self.editor.scroll_up(3);
                    }
                } else if rect_contains(self.terminal_rail_area, m.column, m.row) {
                    self.terminal_rail_scroll = self.terminal_rail_scroll.saturating_sub(1);
                } else if let Some(idx) = terminal_hit {
                    let shift = m.modifiers.contains(KeyModifiers::SHIFT);
                    let t = &mut self.terminals[idx];
                    // Same border fall-through as the WheelDown arm below.
                    if t.mouse_reporting()
                        && !shift
                        && t.report_mouse(
                            MouseButtonKind::WheelUp,
                            MouseAction::Press,
                            m.column,
                            m.row,
                            mouse_mods(&m),
                        )
                    {
                    } else if !t.scroll_up(3) {
                        if t.app_cursor_keys() {
                            t.write_input(b"\x1bOA\x1bOA\x1bOA");
                        } else {
                            t.write_input(b"\x1b[A\x1b[A\x1b[A");
                        }
                    }
                }
            }
            MouseEventKind::ScrollLeft if in_editor => {
                if let Some(diff) = self.editor.diff.as_mut() {
                    diff.scroll_left_by(4);
                } else {
                    self.editor.scroll_left_by(4);
                }
            }
            MouseEventKind::ScrollRight if in_editor => {
                if let Some(diff) = self.editor.diff.as_mut() {
                    diff.scroll_right_by(4);
                } else {
                    self.editor.scroll_right_by(4);
                }
            }
            _ => {}
        }
    }

    /// Whether formatting the current buffer is supported by an active server.
    /// Gates format-on-save so a file whose server advertises no formatter is
    /// saved directly rather than waiting on a reply that never mutates it.
    fn editor_language_supports_formatting(&self) -> bool {
        let Some(lang) = self
            .editor
            .path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .and_then(crate::lsp::Language::from_extension)
        else {
            return false;
        };
        self.lsp
            .as_ref()
            .and_then(|lsp| lsp.language_supports_formatting(lang))
            .unwrap_or(false)
    }

    /// Whether `Cmd+S` should format before writing: the pref is on, a
    /// formatter is available, and the active tab is a real editable code file
    /// (not a diff/sheet/image preview). `supports_formatting` is passed in so
    /// the decision is pure and unit-testable.
    fn format_on_save_eligible(&self, supports_formatting: bool) -> bool {
        self.format_on_save
            && supports_formatting
            && self.editor.path.is_some()
            && self.editor.diff.is_none()
            && self.editor.sheet.is_none()
            && self.editor.image.is_none()
    }

    /// Arm the deferred write for the active tab, ahead of the format request
    /// whose reply will complete it.
    ///
    /// The latch holds one path because the manager tracks one
    /// `format_request_id`: arming a second file abandons the first reply, so
    /// simply overwriting the latch dropped the first file's save entirely,
    /// leaving it dirty and unwritten with nothing reported. Flush it here
    /// instead. It goes to disk unformatted, which is the honest outcome once
    /// its formatter reply can no longer arrive.
    fn arm_deferred_save(&mut self) {
        if let Some(pending) = std::mem::take(&mut self.save_after_format)
            && self.editor.path.as_deref() != Some(pending.as_path())
        {
            self.write_tab_to_disk(&pending);
        }
        self.save_after_format = self.editor.path.clone();
    }

    /// Write the deferred buffer to disk once its format reply has landed.
    /// A no-op unless [`Self::save`] armed `save_after_format`.
    fn complete_pending_save(&mut self) {
        let Some(path) = std::mem::take(&mut self.save_after_format) else {
            return;
        };
        // Write the tab the save was ASKED for. The reply can land long after
        // the user moved on, and `write_current_to_disk` targets whatever is
        // active — which wrote an unrequested file and left this one dirty.
        if self.editor.path.as_deref() == Some(path.as_path()) {
            self.write_current_to_disk();
            return;
        }
        self.write_tab_to_disk(&path);
    }

    /// Flip `editor.formatOnSave`, persist it, and report the new state.
    /// Persistence is skipped under test so the suite never writes the
    /// developer's `~/.config/croft/config.json` (mirrors the layout prefs).
    /// The auto-save delay after the last edit, VS Code's
    /// `files.autoSaveDelay` default.
    const AUTO_SAVE_DELAY: std::time::Duration = std::time::Duration::from_millis(1000);

    /// Write every dirty, conflict-free buffer whose last edit is older
    /// than the delay — the whole `files.autoSave: afterDelay` feature.
    /// Runs every frame; returns true when anything was saved so the
    /// caller redraws (dirty markers, badges, status).
    pub fn tick_auto_save(&mut self) -> bool {
        // `onFocusChange` fires on the transition, so the signature is
        // sampled every tick regardless of which modes are enabled.
        let focus_changed = self.note_focus_signature();
        let mut changed = false;
        if self.auto_save_on_focus_change && focus_changed {
            changed = self.sweep_auto_save(false);
        }
        if self.auto_save {
            changed |= self.sweep_auto_save(true);
        }
        changed
    }

    /// Sample the current focus (pane, active tab, active path) and report
    /// whether it moved since the last sample. The first sample never
    /// counts as a change, so launching croft writes nothing on its own.
    fn note_focus_signature(&mut self) -> bool {
        let pane = match self.focus {
            Pane::Tree => 0usize,
            Pane::Editor => 1,
            Pane::Terminal => 2,
        };
        let sig = (pane, self.editor.active_index(), self.editor.path.clone());
        match self.last_focus_signature.replace(sig.clone()) {
            None => false,
            Some(prev) => prev != sig,
        }
    }

    /// The shared auto-save sweep. `require_delay` selects the mode:
    /// `afterDelay` waits out [`Self::AUTO_SAVE_DELAY`] since the last
    /// edit and writes every dirty buffer; `onFocusChange` writes
    /// immediately but skips the editor that currently HAS focus (it has
    /// not lost it yet). Returns true when anything changed on screen.
    fn sweep_auto_save(&mut self, require_delay: bool) -> bool {
        // Each saved tab's own map rides along (#349): the recorder must not
        // look it up by path afterwards, since a split can hold the same file
        // in a second buffer with a different map.
        let mut saved_paths: Vec<(PathBuf, crate::provenance::Provenance, Option<Vec<u8>>)> =
            Vec::new();
        // The tab that still holds focus is not saved by the focus-change
        // mode: only buffers that LOST focus are written.
        let keep_focused =
            (!require_delay && self.focus == Pane::Editor).then(|| self.editor.active_index());
        // Collab guests never write shared (workspace) files; the session
        // owner is the single writer (docs/MULTIPLAYER.md, Phase D).
        let guest = self.is_collab_guest();
        let root = self.tree.root.clone();
        let due = |e: &crate::widgets::editor::Editor| {
            e.dirty
                && e.path.is_some()
                // Preview-kind edits (hex bytes, sheet cells) are
                // EXPLICIT-save only: an automatic write mid-edit could
                // land a half-updated byte sequence, and the serialising
                // kinds normalise quoting the user did not ask to touch.
                // (They also never set last_edit_at, so this guard makes
                // an implicit exclusion structural - #191 review.)
                && !e.has_non_text_view()
                && !e.disk_conflict
                // A latched encoding refusal: only an explicit Cmd+S can
                // consent to the lossy write, so retrying here would just
                // re-refuse every tick.
                && !e.encoding_loss
                && !(guest
                    && e.path
                        .as_ref()
                        .is_some_and(|p| collab_file_key(&root, p).is_some()))
                && (!require_delay
                    || e.last_edit_at
                        .is_some_and(|t| t.elapsed() >= Self::AUTO_SAVE_DELAY))
        };
        let mut conflicted: Vec<PathBuf> = Vec::new();
        // "name (encoding)" per refused tab: the refusal message names each
        // tab's OWN encoding, which need not be the active tab's.
        let mut lossy: Vec<String> = Vec::new();
        let mut sweep = |editors: &mut [crate::widgets::editor::Editor], skip: Option<usize>| {
            for (i, e) in editors
                .iter_mut()
                .enumerate()
                .filter(|(i, e)| Some(*i) != skip && due(e))
            {
                let _ = i;
                // `save_to_disk` re-checks the disk and flags (never
                // overwrites) an external change; auto save must not
                // arm the force-overwrite path an explicit Cmd+S offers.
                match e.save_to_disk() {
                    Ok(crate::widgets::editor::SaveOutcome::Saved) => {
                        if let Some(p) = e.path.clone() {
                            // The bytes this editor just wrote, so the
                            // recorder can tell whether they are still the
                            // ones on disk when its worker reads (#349).
                            saved_paths.push((p, e.provenance_to_record(), e.bytes_for_disk()));
                        }
                    }
                    // The latch also removes the tab from `due`, so this is
                    // the ONLY chance to tell the user: the FS sweep's
                    // prompt fires on the transition into disk_conflict,
                    // which this save just consumed.
                    Ok(crate::widgets::editor::SaveOutcome::DiskConflict) => {
                        conflicted.extend(e.path.clone());
                    }
                    // Same transition-only reporting as the conflict arm:
                    // the latch just set removes the tab from `due`, so
                    // this tick is the one chance to say why it stopped
                    // saving. Never arms the lossy write — consent is the
                    // explicit path's alone.
                    Ok(crate::widgets::editor::SaveOutcome::EncodingLoss) => {
                        if let Some(name) = e.path.as_ref().and_then(|p| p.file_name()) {
                            lossy.push(format!(
                                "{} ({})",
                                name.to_string_lossy(),
                                e.encoding.name()
                            ));
                        }
                    }
                    Err(_) => {}
                }
            }
        };
        sweep(&mut self.editor.editors, keep_focused);
        for group in self.editor_layout.inactive_groups_mut() {
            sweep(&mut group.editors, None);
        }
        let had_conflicts = !conflicted.is_empty();
        if had_conflicts {
            self.prompt_disk_conflict(conflicted);
        }
        let had_lossy = !lossy.is_empty();
        if had_lossy {
            // The status line, not the modal prompt: nothing was lost and
            // nothing is racing, so an auto-save refusal must not steal the
            // keyboard mid-typing burst.
            self.status = format!(
                "Auto save paused for {}: the buffer has characters the encoding cannot represent - open the tab and press Cmd+S to resolve",
                lossy.join(", ")
            );
        }
        if saved_paths.is_empty() {
            // A conflict-only (or refusal-only) tick still changed the UI:
            // returning false would defer it to the next incidental redraw.
            return had_conflicts || had_lossy;
        }
        // Mirror the explicit-save path: a config file written by auto save
        // must take effect exactly like one written by Cmd+S — including one
        // saved in a background tab or an inactive split.
        for (path, ..) in &saved_paths {
            self.reload_config_for_path(path);
        }
        if let Some(lsp) = self.lsp.as_ref() {
            for (path, ..) in &saved_paths {
                lsp.save_doc(path.clone());
            }
        }
        for (path, seats, described) in saved_paths {
            self.record_history_snapshot_of(&path, seats, described);
        }
        true
    }

    fn toggle_auto_save(&mut self) {
        self.auto_save = !self.auto_save;
        self.status = if self.auto_save {
            String::from("Auto Save: on")
        } else {
            String::from("Auto Save: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_auto_save(self.auto_save);
        }
    }

    /// Flip `files.autoSave: onFocusChange` and persist it, like
    /// [`Self::toggle_auto_save`] does for the delay mode.
    fn toggle_auto_save_on_focus_change(&mut self) {
        self.auto_save_on_focus_change = !self.auto_save_on_focus_change;
        self.status = if self.auto_save_on_focus_change {
            String::from("Auto Save on Focus Change: on")
        } else {
            String::from("Auto Save on Focus Change: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_auto_save_on_focus_change(self.auto_save_on_focus_change);
        }
    }

    /// `Editor: Toggle Provenance` (#349): flip the lens for the session and
    /// push it onto the active editor now (the per-tick sync covers the
    /// next tab focused).
    fn toggle_provenance(&mut self) {
        self.provenance_overlay = !self.provenance_overlay;
        self.editor.provenance_overlay = self.provenance_overlay;
        self.status = if self.provenance_overlay {
            String::from("Provenance: on")
        } else {
            String::from("Provenance: off")
        };
    }

    fn toggle_inline_blame(&mut self) {
        self.inline_blame_enabled = !self.inline_blame_enabled;
        self.editor.blame_enabled = self.inline_blame_enabled;
        // Re-enabling refetches (the sync marker was left set); disabling
        // keeps the data so a later re-enable can be instant if unchanged.
        if self.inline_blame_enabled {
            self.blame_fetched = None;
        }
        self.status = if self.inline_blame_enabled {
            String::from("Inline Blame: on")
        } else {
            String::from("Inline Blame: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_inline_blame(self.inline_blame_enabled);
        }
    }

    fn toggle_render_whitespace(&mut self) {
        self.whitespace_mode = self.whitespace_mode.next();
        self.editor.whitespace_mode = self.whitespace_mode;
        if !cfg!(test) {
            let _ = crate::prefs::save_render_whitespace(self.whitespace_mode.pref_id());
        }
        self.status = format!("Render Whitespace: {}", self.whitespace_mode.label());
    }

    /// Rebuild the inline-value trailers (#135) from the current stop's
    /// already-fetched VARIABLES data, on every editor showing the stopped
    /// file (inactive split groups render too).
    fn refresh_inline_values(&mut self) {
        use crate::dap::session::SessionPhase;
        if !self.inline_values_enabled {
            return;
        }
        let Some(session) = self.dap_session.as_ref() else {
            return;
        };
        if session.phase != SessionPhase::Stopped {
            return;
        }
        let Some((path, line)) = session.current_location.clone() else {
            return;
        };
        let locals = crate::dap::session::inline_locals(&session.scopes, &session.variables);
        for ed in self.editor.editors.iter_mut() {
            if ed.path.as_deref() == Some(path.as_path()) {
                ed.set_inline_values_from_locals(line, &locals);
            }
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in group.editors.iter_mut() {
                if ed.path.as_deref() == Some(path.as_path()) {
                    ed.set_inline_values_from_locals(line, &locals);
                }
            }
        }
    }

    /// Drop every inline-value trailer, in every editor of every group —
    /// called wherever the stop arrow clears (resume, step, terminate).
    fn clear_inline_values(&mut self) {
        for ed in self.editor.editors.iter_mut() {
            ed.inline_values.clear();
        }
        for group in self.editor_layout.inactive_groups_mut() {
            for ed in group.editors.iter_mut() {
                ed.inline_values.clear();
            }
        }
    }

    fn toggle_inline_values(&mut self) {
        self.inline_values_enabled = !self.inline_values_enabled;
        if self.inline_values_enabled {
            self.refresh_inline_values();
        } else {
            self.clear_inline_values();
        }
        if !cfg!(test) {
            let _ = crate::prefs::save_inline_values(self.inline_values_enabled);
        }
        self.status = format!(
            "Debug Inline Values: {}",
            if self.inline_values_enabled {
                "on"
            } else {
                "off"
            }
        );
    }

    fn toggle_bracket_colors(&mut self) {
        self.bracket_colors_enabled = !self.bracket_colors_enabled;
        self.editor.show_bracket_colors = self.bracket_colors_enabled;
        if !cfg!(test) {
            let _ = crate::prefs::save_bracket_colors(self.bracket_colors_enabled);
        }
        self.status = format!(
            "Bracket Pair Colorization: {}",
            if self.bracket_colors_enabled {
                "on"
            } else {
                "off"
            }
        );
    }

    fn toggle_indent_guides(&mut self) {
        self.indent_guides_enabled = !self.indent_guides_enabled;
        self.editor.show_indent_guides = self.indent_guides_enabled;
        if !cfg!(test) {
            let _ = crate::prefs::save_indent_guides(self.indent_guides_enabled);
        }
        self.status = format!(
            "Indent Guides: {}",
            if self.indent_guides_enabled {
                "on"
            } else {
                "off"
            }
        );
    }

    fn toggle_auto_close_pairs(&mut self) {
        self.auto_close_pairs = !self.auto_close_pairs;
        self.editor.auto_close_pairs = self.auto_close_pairs;
        if !cfg!(test) {
            let _ = crate::prefs::save_auto_close_pairs(self.auto_close_pairs);
        }
        self.status = format!(
            "Auto Closing Pairs: {}",
            if self.auto_close_pairs { "on" } else { "off" }
        );
    }

    /// VS Code's `editor.formatOnType` toggle (#254), persisted like the
    /// other editor preferences.
    fn toggle_format_on_type(&mut self) {
        self.format_on_type = !self.format_on_type;
        self.status = if self.format_on_type {
            String::from("Format on Type: on")
        } else {
            String::from("Format on Type: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_format_on_type(self.format_on_type);
        }
    }

    fn toggle_format_on_save(&mut self) {
        self.format_on_save = !self.format_on_save;
        self.status = if self.format_on_save {
            String::from("Format on Save: on")
        } else {
            String::from("Format on Save: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_format_on_save(self.format_on_save);
        }
    }

    /// Palette "Log: Toggle Highlighting (tailspin)" and the Settings row
    /// (#466): flip tailspin colouring for every open rendered log, steer
    /// the default for logs opened later, and persist the preference.
    pub fn toggle_log_highlight(&mut self) {
        self.set_log_highlight(!self.log_highlight);
        self.status = if self.log_highlight {
            String::from("Log highlighting (tailspin): on")
        } else {
            String::from("Log highlighting (tailspin): off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_disable_log_highlight(!self.log_highlight);
        }
    }

    /// Apply a log-highlight setting everywhere it lives (#466): the app's
    /// field, the log view's opening default for logs opened later, and
    /// every log view already open in any split group. Shared by the
    /// palette / Settings toggle and by a settings remerge (a workspace
    /// layer setting `disable_log_highlight`), so the two cannot drift.
    fn set_log_highlight(&mut self, on: bool) {
        self.log_highlight = on;
        seed_log_highlight_default(on);
        for group in
            std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut())
        {
            for ed in &mut group.editors {
                if let Some(log) = ed.log.as_mut() {
                    log.set_highlight(on);
                }
            }
        }
    }

    fn toggle_copy_on_select(&mut self) {
        self.copy_on_select = !self.copy_on_select;
        self.status = if self.copy_on_select {
            String::from("Copy on Selection: on")
        } else {
            String::from("Copy on Selection: off")
        };
        if !cfg!(test) {
            let _ = crate::prefs::save_copy_on_select(self.copy_on_select);
        }
    }

    fn save(&mut self) {
        // A hex tab with pending overwrites saves through its own byte
        // path (#173) — never `write_buffer_to_disk`, whose #185 guard
        // refuses every preview kind. Same disk-conflict double-press
        // contract as text saves.
        if self.editor.hex.as_ref().is_some_and(|v| v.has_edits()) {
            use crate::widgets::editor::SaveOutcome;
            let force = std::mem::take(&mut self.force_save_armed);
            match self.editor.hex_save(force) {
                Ok(SaveOutcome::Saved) => {
                    self.status = self.editor.status.clone();
                    // Local history captures the new bytes like every
                    // other successful save path (#191 review).
                    if let Some(path) = self.editor.path.clone() {
                        let seats = self.editor.provenance_to_record();
                        let described = self.editor.bytes_for_disk();
                        self.record_history_snapshot_of(&path, seats, described);
                    }
                }
                Ok(SaveOutcome::DiskConflict) => {
                    self.force_save_armed = true;
                    let name = self
                        .editor
                        .path
                        .as_ref()
                        .map(|p| p.display().to_string())
                        .unwrap_or_default();
                    self.status = format!(
                        "{name} changed on disk since you opened it - press Cmd+S again to overwrite the changed bytes"
                    );
                }
                Ok(_) => unreachable!("hex_save reports Saved or DiskConflict"),
                Err(e) => self.status = format!("Save failed: {e}"),
            }
            return;
        }
        // A CSV/TSV sheet with grid edits saves through its own
        // serialisation path (#177), same shape as the hex branch above.
        if self.editor.sheet.as_ref().is_some_and(|v| v.dirty) {
            use crate::widgets::editor::SaveOutcome;
            let force = std::mem::take(&mut self.force_save_armed);
            // Distinct consents (#194 review): overwriting an external
            // disk change and replacing a FORMULA are different
            // decisions, each armed by its own refusal message.
            let overwrite_formulas = std::mem::take(&mut self.formula_overwrite_armed);
            match self.editor.sheet_save(force, overwrite_formulas) {
                Ok(SaveOutcome::Saved) => {
                    self.status = self.editor.status.clone();
                    if let Some(path) = self.editor.path.clone() {
                        let seats = self.editor.provenance_to_record();
                        let described = self.editor.bytes_for_disk();
                        self.record_history_snapshot_of(&path, seats, described);
                    }
                    // Formula cells held back (#178): the NEXT Cmd+S is
                    // the explicit consent, same double-press contract
                    // as disk conflicts.
                    if self.editor.sheet.as_ref().is_some_and(|v| v.dirty) {
                        self.formula_overwrite_armed = true;
                    }
                }
                Ok(SaveOutcome::DiskConflict) => {
                    self.force_save_armed = true;
                    let name = self
                        .editor
                        .path
                        .as_ref()
                        .map(|p| p.display().to_string())
                        .unwrap_or_default();
                    self.status = format!(
                        "{name} changed on disk since you opened it - press Cmd+S again to overwrite"
                    );
                }
                Ok(_) => unreachable!("sheet_save reports Saved or DiskConflict"),
                Err(e) => self.status = format!("Save failed: {e}"),
            }
            return;
        }
        // A preview tab has nothing to save (and #185: letting the write
        // proceed truncated the previewed file). Friendly no-op here; the
        // choke-point guard in `write_buffer_to_disk` backstops every
        // other path.
        if self.editor.has_non_text_view() {
            self.status = String::from("Nothing to save: this tab is a read-only preview");
            return;
        }
        // Guests in a collab session never write shared files: the owner is
        // the single writer, so the FS watcher and history snapshots see one
        // author. The guest's edits already flowed to the owner as ops.
        // Except a file whose bootstrap gave up (no owner answered): the
        // guest is its only author, and refusing meant the work could never
        // persist anywhere. Same when there is NO session at all (relay
        // link down, reconnect pending): with nobody to defer to, blocking
        // strands the offline work in RAM for the whole outage.
        if self.is_collab_guest()
            && self
                .editor
                .path
                .as_ref()
                .and_then(|p| collab_file_key(&self.tree.root, p))
                .is_some_and(|file| {
                    self.collab
                        .as_ref()
                        .is_some_and(|s| !s.is_local_only(&file))
                })
        {
            self.status =
                String::from("Shared file: the session owner saves (your edits are already live)");
            return;
        }
        // A previously-refused save arms a one-shot override: the very next
        // Cmd+S overwrites the external change. Consume it here so it never
        // lingers past the press it was meant for.
        if std::mem::take(&mut self.force_save_armed) {
            use crate::widgets::editor::SaveOutcome;
            match self.editor.save_to_disk_force() {
                Ok(SaveOutcome::Saved) => {
                    self.status = self.editor.status.clone();
                    if let Some(path) = self.editor.path.clone() {
                        let seats = self.editor.provenance_to_record();
                        let described = self.editor.bytes_for_disk();
                        self.record_history_snapshot_of(&path, seats, described);
                    }
                    self.lsp_notify_saved();
                    self.reload_config_if_needed();
                }
                // Overwriting the external change was consented to; mangling
                // the buffer's characters was not. Route the refusal through
                // the same prompt-and-rearm as a plain save, keeping the
                // overwrite consent so the NEXT Cmd+S resolves both at once.
                Ok(SaveOutcome::EncodingLoss) => {
                    self.force_save_armed = true;
                    self.prompt_encoding_loss();
                }
                Ok(SaveOutcome::DiskConflict) => {
                    unreachable!("force save never reports a conflict")
                }
                Err(e) => self.status = format!("Save failed: {e}"),
            }
            return;
        }
        // Format-on-save: defer the write until the format reply arrives, then
        // `drain_lsp_format` calls `complete_pending_save`.
        if self.format_on_save_eligible(self.editor_language_supports_formatting()) {
            self.arm_deferred_save();
            self.start_format_document();
            return;
        }
        self.write_current_to_disk();
    }

    /// After a save, if the file was one of croft's JSON configs, re-read it so
    /// the change applies without a relaunch (VS Code applies keybindings and
    /// snippets on save). settings.json fields are read at startup, so that one
    /// leaves its own "next launch" note rather than reloading here.
    fn reload_config_if_needed(&mut self) {
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        self.reload_config_for_path(&path);
    }

    /// Reload whichever of croft's own config files `path` is, if any.
    /// Shared by the explicit-save path (active tab) and the auto-save
    /// sweep (every written tab, background and inactive splits included).
    fn reload_config_for_path(&mut self, path: &std::path::Path) {
        if path == crate::keymap::keybindings_path() {
            // The non-reporting loader: this path needs the warnings itself
            // for the status summary below, and `load` would print each one to
            // OUTPUT a second time.
            let (map, warns) = crate::keymap::Keymap::load_with_warnings(path);
            self.keymap = map;
            // Refused rows used to vanish, which makes a mistyped binding
            // feel like croft is broken. Same treatment the settings loader
            // gives its warnings: OUTPUT for the detail, a status summary so
            // the user knows to look (#259).
            for w in &warns {
                crate::output::push("Keybindings", crate::output::OutputLevel::Warn, w);
            }
            self.status = keybindings_reload_status(&warns);
        } else if path == crate::snippets::snippets_path() {
            self.snippets = crate::snippets::SnippetSet::load(path);
            self.status = String::from("Snippets reloaded");
        } else if path == crate::agents::agents_path() {
            self.agents = crate::agents::AgentTable::load(path);
            let dropped = self.agents.dropped_patterns();
            self.status = format!(
                "Agent lanes reloaded ({} agents known{})",
                self.agents.names().len(),
                if dropped > 0 {
                    format!(
                        ", {dropped} prompt pattern{} did not compile",
                        if dropped == 1 { "" } else { "s" }
                    )
                } else {
                    String::new()
                }
            );
        } else if path == crate::triggers::triggers_path() {
            self.triggers = load_trigger_set(self.secret_redaction);
            self.status = format!(
                "Triggers reloaded ({} active)",
                self.triggers.triggers.len()
            );
        } else if path == crate::problem_matchers::matchers_path()
            || path == crate::problem_matchers::workspace_matchers_path(self.workspace_root())
        {
            self.reload_matchers();
        } else if path == crate::prefs::config_path()
            || self.settings_chain.iter().any(|p| p == path)
        {
            self.remerge_settings();
        }
    }

    /// Re-run the layered settings merge (#251) and apply everything that can
    /// apply live: theme, editor toggles, save behavior, host accents. Called
    /// when any file of the chain is saved in the editor; layout and other
    /// startup-read settings still say "next launch".
    fn remerge_settings(&mut self) {
        let merged = crate::config_layers::load_merged(Some(self.roots.primary()));
        for w in &merged.warnings {
            crate::output::push("Settings", crate::output::OutputLevel::Warn, w);
        }
        self.settings_chain = merged.chain;
        self.settings_provenance = merged.provenance;
        self.apply_merged_settings(&merged.prefs);
        self.status = if merged.warnings.is_empty() {
            String::from("Settings reloaded")
        } else {
            format!(
                "Settings reloaded with {} warning{} — see OUTPUT · Settings",
                merged.warnings.len(),
                if merged.warnings.len() == 1 { "" } else { "s" }
            )
        };
    }

    /// Apply a merged settings view to the live session. Mirrors what the
    /// individual toggles do, minus their persistence (the values already
    /// live in config files) and minus their status chatter.
    fn apply_merged_settings(&mut self, p: &crate::prefs::Prefs) {
        self.notifier = crate::notifications::Notifier::new(&p.notifications);
        let theme = p.theme();
        if theme != self.theme {
            // Visuals only: a workspace-set theme must not be written back
            // into the user's config.
            self.apply_theme_visuals(theme);
        }
        self.format_on_save = p.format_on_save;
        self.format_on_type = p.format_on_type;
        self.auto_save = p.auto_save;
        self.auto_save_on_focus_change = p.auto_save_on_focus_change;
        self.copy_on_select = p.copy_on_select;
        // The ssh-pane offer's switches apply live like every other pref
        // here (#364); turning it off also takes down an offer on screen.
        self.remote_offer_disabled = p.disable_remote_offer;
        self.lane_agent = p.lane_agent.clone();
        // Live like every other pref here (#363): editing a group in
        // config.json takes effect on the next fleet run without a restart.
        self.fleet_groups = p.fleet_groups.clone();
        let was_excluded = std::mem::replace(
            &mut self.remote_offer_excluded,
            p.remote_offer_excluded_hosts.clone(),
        );
        // Sampling stops while the offer is off, so the per-pane memory stops
        // tracking reality; kept, it would make the first session seen after
        // a re-enable look like a continuation of the last one seen before
        // it, and that pane would never be offered that host again (#364).
        if self.remote_offer_disabled {
            self.ssh_offer_seen.clear();
        }
        // A host taken OFF the exclusion list: a pane already on it was seen
        // while excluded and would otherwise never be offered for the
        // session it is in. Forgetting what those panes were seen on makes
        // the next sample read as a session start, which is the moment the
        // user asked to be offered at.
        let freed: Vec<&String> = was_excluded
            .iter()
            .filter(|h| {
                !self
                    .remote_offer_excluded
                    .iter()
                    .any(|n| n.eq_ignore_ascii_case(h))
            })
            .collect();
        if !freed.is_empty() {
            self.ssh_offer_seen.retain(|_, seen| {
                !seen
                    .as_deref()
                    .is_some_and(|h| freed.iter().any(|f| f.eq_ignore_ascii_case(h)))
            });
        }
        if let Some(o) = self.ssh_offer.as_ref()
            && !crate::remote::offer_allowed(
                &o.host,
                self.remote_offer_disabled,
                &self.remote_offer_excluded,
                &self.remote_offer_refused,
                std::time::SystemTime::now(),
            )
        {
            self.dismiss_ssh_offer();
        }
        // Only on a real change: the startup remerge runs before any log is
        // open and the field already holds the preference, and writing the
        // process-wide default from here under test would race the tests
        // that read it (see `seed_log_highlight_default`).
        let want_highlight = !p.disable_log_highlight;
        if want_highlight != self.log_highlight {
            self.set_log_highlight(want_highlight);
        }
        self.auto_close_pairs = !p.disable_auto_close_pairs;
        self.editor.auto_close_pairs = self.auto_close_pairs;
        if !p.disable_inline_blame && !self.inline_blame_enabled {
            // Re-enabling refetches, like toggle_inline_blame.
            self.blame_fetched = None;
        }
        self.inline_blame_enabled = !p.disable_inline_blame;
        self.editor.blame_enabled = self.inline_blame_enabled;
        self.indent_guides_enabled = !p.disable_indent_guides;
        self.editor.show_indent_guides = self.indent_guides_enabled;
        self.bracket_colors_enabled = !p.disable_bracket_colors;
        self.editor.show_bracket_colors = self.bracket_colors_enabled;
        self.whitespace_mode =
            crate::widgets::editor::WhitespaceMode::from_pref(&p.render_whitespace);
        self.editor.whitespace_mode = self.whitespace_mode;
        if !p.disable_inlay_hints && !self.inlay_hints_enabled {
            self.inlay_hints_enabled = true;
            self.request_inlay_hints_for_open_editors();
        } else if p.disable_inlay_hints && self.inlay_hints_enabled {
            self.inlay_hints_enabled = false;
            self.editor.clear_inlay_hints();
            for group in self.editor_layout.inactive_groups_mut() {
                group.clear_inlay_hints();
            }
        }
        if p.disable_inline_values && self.inline_values_enabled {
            self.inline_values_enabled = false;
            self.clear_inline_values();
        } else if !p.disable_inline_values && !self.inline_values_enabled {
            self.inline_values_enabled = true;
            self.refresh_inline_values();
        }
        self.explorer_views = ExplorerViewVisibility::from_prefs(p.explorer_views);
        self.set_host_accents(&p.host_accents);
    }

    /// Tell the language servers the focused file hit the disk. rust-analyzer
    /// re-runs its check-on-save (`cargo check`, which produces the Rust
    /// PROBLEMS entries) only on `textDocument/didSave`; without this the
    /// panel never refreshes after a save (issue #37).
    fn lsp_notify_saved(&mut self) {
        if let (Some(lsp), Some(path)) = (self.lsp.as_ref(), self.editor.path.clone()) {
            lsp.save_doc(path);
        }
    }

    /// Restore persisted provenance maps onto the open buffers (#349), each
    /// once per buffer generation: when a tab is a clean text buffer that
    /// knows nothing yet, and the newest history snapshot holds exactly the
    /// bytes on disk, the seats recorded beside that snapshot describe this
    /// very text and come back. Any difference (an edit since, a save croft
    /// never saw, a file with no history) leaves every line unknown: a map is
    /// never applied to text it did not describe. Every tab of every group,
    /// not only the focused one: the lens paints in every pane
    /// (`sync_focus_flags` carries the flag there), so a map restored onto
    /// the focused tab alone would leave a split showing blanks beside it.
    fn sync_provenance(&mut self) {
        let root = self.history_root.clone();
        let groups =
            std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
        for ed in groups.flat_map(|g| g.editors.iter_mut()) {
            Self::sync_provenance_for(&root, ed);
        }
    }

    /// The per-buffer body of [`Self::sync_provenance`].
    fn sync_provenance_for(root: &Path, ed: &mut crate::widgets::editor::Editor) {
        let Some(path) = ed.path.clone() else {
            return;
        };
        let seq = ed.edit_seq;
        if ed.provenance_synced_seq == Some(seq) {
            return;
        }
        // Not eligible yet is not the same as considered: a dirty buffer, one
        // that already knows its seats, or a viewer tab (the file shown
        // through its own path, `lines` a placeholder no map should credit;
        // a markdown preview is NOT one, its `lines` are the file's own text)
        // leaves the marker unset, so a later tick, after a save or a swap
        // back to text, reconsiders instead of staying burnt for the session.
        if ed.dirty || ed.provenance.attributed() > 0 || ed.has_non_text_view() {
            return;
        }
        let Some(newest) = crate::history::entries_in(root, &path).into_iter().next() else {
            return;
        };
        // The sidecar first: most files have a snapshot and no record, and
        // the reads below are only worth paying on the UI thread when there
        // is a map to apply. Nothing above this point burns the marker: a
        // save records its snapshot and then its sidecar from a worker
        // thread, so a tick landing in that window must be free to look
        // again rather than deciding this buffer has no map.
        let Some(mut seats) = crate::history::seats_for(root, &path, newest.millis) else {
            return;
        };
        ed.provenance_synced_seq = Some(seq);
        // Then sizes: this runs on the render thread, and two whole-file
        // reads of a large file on the frame a tab is switched to would be a
        // visible stall for what is usually a mismatch.
        let (Ok(disk_meta), Ok(snap_meta)) =
            (std::fs::metadata(&path), std::fs::metadata(&newest.file))
        else {
            return;
        };
        if disk_meta.len() != snap_meta.len() {
            return;
        }
        let (Ok(on_disk), Ok(snapshot)) = (std::fs::read(&path), std::fs::read(&newest.file))
        else {
            return;
        };
        if on_disk != snapshot {
            return;
        }
        // And this buffer holds that very text. A clean buffer can still be
        // stale: when one tab of a split saves, the other keeps the pre-save
        // lines, and the snapshot then matches DISK while describing text
        // that tab never held. The disk stamp cannot tell the two apart when
        // both writes land inside one filesystem timestamp tick, so the
        // comparison is against the buffer's own bytes.
        if !ed.holds_exactly(&snapshot) {
            return;
        }
        seats.truncate(ed.lines.len());
        ed.provenance = seats;
    }

    /// Record a local-history snapshot of a file that just hit the disk, and
    /// refresh the TIMELINE when it's the active file so the new version shows.
    /// Reads back what was written so the snapshot matches the on-disk bytes
    /// exactly (encoding / EOL included). The IO runs off-thread — with auto
    /// save this fires every second, and a large file's read+write on the
    /// render thread is a visible stall.
    ///
    /// `seats` is who typed each line of the buffer that was saved, recorded
    /// beside the snapshot (#349). The caller reads it off that tab
    /// (`Editor::provenance_to_record`) at the save, on the UI thread: never
    /// looked up by path here, since a split can hold the same file in a
    /// second buffer with a different map, and a snapshot restore records
    /// the restored snapshot's own seats, which no tab holds at that moment.
    fn record_history_snapshot(&mut self, path: &Path, seats: crate::provenance::Provenance) {
        self.record_history_snapshot_of(path, seats, None);
    }

    /// [`Self::record_history_snapshot`] with the bytes the map describes.
    /// The worker re-reads the file, which is what makes the snapshot
    /// byte-exact, and between the save and that read another tab's save of
    /// the same path can land - so the map is recorded only while the bytes
    /// on disk are still the ones it describes.
    ///
    /// `described` comes from the caller because only the caller knows WHICH
    /// buffer the map came from: a search by path finds the focused tab,
    /// which need not be the tab that saved. `None` records the map
    /// unconditionally, for a caller whose map has no live buffer - a
    /// snapshot restore, whose seats come from the restored snapshot and
    /// describe the bytes it has just written itself.
    fn record_history_snapshot_of(
        &mut self,
        path: &Path,
        seats: crate::provenance::Provenance,
        described: Option<Vec<u8>>,
    ) {
        let root = self.history_root.clone();
        let path = path.to_path_buf();
        let tx = self.history_done_tx.clone();
        let millis = now_millis();
        std::thread::spawn(move || {
            if let Ok(bytes) = std::fs::read(&path) {
                // Someone else's bytes are on disk now: record the snapshot
                // alone, every line unknown, which is the safe direction.
                let seats = match described {
                    Some(want) if want != bytes => crate::provenance::Provenance::new(),
                    _ => seats,
                };
                let _ = crate::history::record_with_seats_in(&root, &path, &bytes, millis, &seats);
            }
            let _ = tx.send(path);
        });
    }

    /// Save the open tab for `path` wherever it lives — background tab of the
    /// focused group, or any inactive split — without disturbing the focus.
    /// Used by the deferred format-on-save write when the user has moved on.
    fn write_tab_to_disk(&mut self, path: &std::path::Path) {
        use crate::widgets::editor::SaveOutcome;
        let found = self
            .editor
            .editors
            .iter_mut()
            .chain(
                self.editor_layout
                    .inactive_groups_mut()
                    .into_iter()
                    .flat_map(|g| g.editors.iter_mut()),
            )
            .find(|e| e.path.as_deref() == Some(path));
        let Some(editor) = found else {
            // The tab was closed while the formatter was thinking; there is no
            // buffer left to write and the disk file is untouched.
            self.status = String::from("Save skipped: the tab was closed");
            return;
        };
        match editor.save_to_disk() {
            Ok(SaveOutcome::Saved) => {
                let seats = editor.provenance_to_record();
                let described = editor.bytes_for_disk();
                self.status = editor.status.clone();
                self.record_history_snapshot_of(path, seats, described);
                if let Some(lsp) = self.lsp.as_ref() {
                    lsp.save_doc(path.to_path_buf());
                }
                self.reload_config_for_path(path);
            }
            Ok(SaveOutcome::DiskConflict) => {
                self.status = format!(
                    "{} changed on disk since you opened it - open the tab and press Cmd+S twice to overwrite, or close it to keep the disk version",
                    path.display()
                );
            }
            Ok(SaveOutcome::EncodingLoss) => {
                // Both callers route a still-focused tab to
                // `write_current_to_disk`, which arms the press-again consent
                // itself; this function only ever runs for a tab the user
                // moved away from, and such a tab never gets lossy consent —
                // resolving needs it back in front of them.
                self.status = format!(
                    "{} not saved: it has characters {} cannot represent - open the tab and press Cmd+S to resolve",
                    path.display(),
                    editor.encoding.name()
                );
            }
            Err(e) => self.status = format!("Save failed: {e}"),
        }
    }

    fn write_current_to_disk(&mut self) {
        use crate::widgets::editor::SaveOutcome;
        match self.editor.save_to_disk() {
            Ok(SaveOutcome::Saved) => {
                self.status = self.editor.status.clone();
                if let Some(path) = self.editor.path.clone() {
                    let seats = self.editor.provenance_to_record();
                    let described = self.editor.bytes_for_disk();
                    self.record_history_snapshot_of(&path, seats, described);
                }
                self.lsp_notify_saved();
                self.reload_config_if_needed();
            }
            Ok(SaveOutcome::DiskConflict) => {
                self.force_save_armed = true;
                let name = self
                    .editor
                    .path
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_default();
                self.status = format!(
                    "{name} changed on disk since you opened it - press Cmd+S again to overwrite, or close the tab to keep the disk version"
                );
            }
            Ok(SaveOutcome::EncodingLoss) => self.prompt_encoding_loss(),
            Err(e) => self.status = format!("Save failed: {e}"),
        }
    }

    /// An explicit save was refused because the encoding cannot represent the
    /// buffer (`SaveOutcome::EncodingLoss`). Arm the one-shot lossy consent
    /// and spell out exactly what the next Cmd+S will destroy, mirroring the
    /// press-again flow of a disk conflict. The alternative exits are the
    /// same two the refusal preserved: reopen the status-bar encoding picker
    /// (a clean buffer switches encodings losslessly) or edit the characters
    /// out.
    fn prompt_encoding_loss(&mut self) {
        self.editor.lossy_save_armed = true;
        let chars = self.editor.unmappable_chars();
        let shown: String = chars.iter().map(|c| format!("{c} ")).collect();
        self.status = format!(
            "Not saved: {} cannot represent {}- press Cmd+S again to replace them with &#…; references (irreversible), or switch encoding via the status bar",
            self.editor.encoding.name(),
            shown
        );
    }

    /// Whether an open context menu (or its submenu panel) overlaps `rect`
    /// on a protocol with no image z-layer (iTerm2 OSC-1337, Sixel), where
    /// the image blit would overpaint the menu. Kitty layers images below
    /// text, so it never needs this.
    fn context_menu_covers_rect(&self, rect: Rect) -> bool {
        match self.inline_protocol {
            crate::iterm2_inline::InlineImageProtocol::ITerm2
            | crate::iterm2_inline::InlineImageProtocol::Sixel => {}
            _ => return false,
        }
        self.menu_rect()
            .into_iter()
            .chain(self.submenu_rect())
            .any(|m| rects_intersect(m, rect))
    }

    /// Compute the menu's bounding rect from current state.
    fn menu_rect(&self) -> Option<Rect> {
        let menu = self.context_menu.as_ref()?;
        // Use char count (not byte len) so multi-byte glyphs in menu
        // labels (e.g. the "" in "Rename", the arrow in "Compare with
        // Selected") don't inflate the menu width past what's needed.
        // Width must also fit the shortcut hint on the right side, with
        // at least 2 cells of gap between label and shortcut.
        let widest = menu.items.iter().map(menu_entry_width).max().unwrap_or(0);
        let width = (widest + 4).max(18) as u16;
        let height = (menu.items.len() + 2) as u16;
        let area = self.last_frame_area;
        // Clamp identically to `render_context_menu` so hit-testing maps
        // clicks to the same row the user actually sees. Without this, a
        // menu that has to shift up to fit (right-click low on screen)
        // dispatches the row above the one the user clicked.
        let x = if area.width > 0 {
            menu.origin.0.min(area.width.saturating_sub(width))
        } else {
            menu.origin.0
        };
        let y = if area.height > 0 {
            menu.origin.1.min(area.height.saturating_sub(height))
        } else {
            menu.origin.1
        };
        Some(Rect {
            x,
            y,
            width,
            height,
        })
    }

    /// Rect of the open submenu's panel: floated to the RIGHT of its parent
    /// row, flipped to the left when it would overflow the screen, with its
    /// first row aligned to the parent row. `None` when no submenu is open.
    fn submenu_rect(&self) -> Option<Rect> {
        let menu = self.context_menu.as_ref()?;
        let parent = menu.open_submenu?;
        let MenuEntry::Submenu { items, .. } = menu.items.get(parent)? else {
            return None;
        };
        let main = self.menu_rect()?;
        let widest = items.iter().map(menu_entry_width).max().unwrap_or(0);
        let width = (widest + 4).max(18) as u16;
        let height = (items.len() + 2) as u16;
        let area = self.last_frame_area;
        // Float right of the main panel; flip left if it would overflow.
        let mut x = main.x + main.width;
        if area.width > 0 && x + width > area.width {
            x = main.x.saturating_sub(width);
        }
        // Align the submenu's top border so its first row sits on the parent row.
        let y = (main.y + 1 + parent as u16).saturating_sub(1);
        let y = if area.height > 0 {
            y.min(area.height.saturating_sub(height))
        } else {
            y
        };
        Some(Rect {
            x,
            y,
            width,
            height,
        })
    }

    /// If (x, y) hits a top-level menu row, return its index.
    fn menu_item_at(&self, x: u16, y: u16) -> Option<usize> {
        let r = self.menu_rect()?;
        if !rect_contains(r, x, y) {
            return None;
        }
        // Items live inside the 1-cell border.
        let inner_y = y.checked_sub(r.y + 1)?;
        let menu = self.context_menu.as_ref()?;
        let idx = inner_y as usize;
        (idx < menu.items.len()).then_some(idx)
    }

    /// If (x, y) hits a row of the open submenu panel, return that child index.
    fn submenu_item_at(&self, x: u16, y: u16) -> Option<usize> {
        let r = self.submenu_rect()?;
        if !rect_contains(r, x, y) {
            return None;
        }
        let inner_y = y.checked_sub(r.y + 1)?;
        let menu = self.context_menu.as_ref()?;
        let parent = menu.open_submenu?;
        let MenuEntry::Submenu { items, .. } = menu.items.get(parent)? else {
            return None;
        };
        let idx = inner_y as usize;
        (idx < items.len()).then_some(idx)
    }

    fn handle_menu_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                // Esc backs out of an open submenu first; at the top level it
                // dismisses the whole menu.
                let closed = self
                    .context_menu
                    .as_mut()
                    .is_some_and(|menu| menu.close_submenu());
                if !closed {
                    self.context_menu = None;
                }
            }
            KeyCode::Up => {
                if let Some(menu) = self.context_menu.as_mut() {
                    menu.move_cursor(false);
                }
            }
            KeyCode::Down => {
                if let Some(menu) = self.context_menu.as_mut() {
                    menu.move_cursor(true);
                }
            }
            KeyCode::Left => {
                if let Some(menu) = self.context_menu.as_mut() {
                    menu.close_submenu();
                }
            }
            KeyCode::Right => {
                if let Some(menu) = self.context_menu.as_mut() {
                    menu.open_cursor_submenu();
                }
            }
            KeyCode::Enter => {
                // On a submenu parent, Enter opens it; on an item it dispatches.
                let opened = self
                    .context_menu
                    .as_mut()
                    .is_some_and(|menu| menu.open_cursor_submenu());
                if opened {
                    return;
                }
                if let Some(menu) = self.context_menu.as_ref()
                    && let Some(action) = menu.cursor_action()
                {
                    let dir = menu.target_dir.clone();
                    self.context_menu = None;
                    self.dispatch_menu_action(action, dir);
                }
            }
            _ => {}
        }
    }

    /// Add `path` as another workspace root (multi-root, #147): the model
    /// grows, the Explorer gains the section, every root gets a watcher
    /// share, the Cmd+P index and workspace search span the new set, and
    /// the LSP layer widens its project-root bound (servers for the new
    /// root spawn per (language, project root) exactly like a fresh
    /// workspace's — croft's per-project server model needs no
    /// didChangeWorkspaceFolders, since no running server's folder set
    /// changes). Session/collab identity deliberately stays keyed on the
    /// PRIMARY root: adding a folder never changes what the window IS.
    pub fn add_workspace_folder(&mut self, path: PathBuf) {
        let path = path.canonicalize().unwrap_or(path);
        if !path.is_dir() {
            self.status = format!("Not a folder: {}", path.display());
            return;
        }
        if !self.roots.add(path.clone()) {
            self.status = String::from("Folder is already in the workspace");
            return;
        }
        self.tree.add_root(path.clone());
        self.git_extra
            .push((path.clone(), GitWorker::spawn(path.clone())));
        self.rebind_workspace_watchers();
        self.sync_workspace_fanout();
        self.refresh_workspace_title();
        self.save_workspace_folders();
        self.status = format!("Added folder: {}", path.display());
    }

    /// Remove a SECONDARY workspace root (#147). The primary is refused —
    /// it is the launch identity; changing it is Make Root's job. Open
    /// tabs under the removed root stay open (they become plain
    /// out-of-workspace files, VS Code behavior).
    pub fn remove_workspace_folder(&mut self, path: PathBuf) {
        if !self.roots.remove(&path) {
            self.status = String::from(
                "The primary workspace folder cannot be removed (use Make Root to change it)",
            );
            return;
        }
        self.tree.remove_root(&path);
        // The removed folder's review queue goes with it (#345). Its rows
        // leave the tree, so no stale DOT renders — but the status chip
        // counts the same set, and a count that outlives the folder it
        // describes sends the user looking for rows that are not there.
        for gone in self
            .agent_ledger
            .unreviewed_paths()
            .into_iter()
            .filter(|p| p.starts_with(&path))
        {
            self.agent_ledger.forget_path(&gone);
        }
        self.sync_agent_lane_decorations();
        self.git_extra.retain(|(r, _)| r != &path);
        self.git_head_oids.remove(&path);
        if self.active_scm_root == path {
            // The panel was following the removed folder's repo: seed the
            // primary's immediately — assigning the field alone left the
            // removed repository on screen (#150 review).
            let primary = self.roots.primary().to_path_buf();
            self.seed_active_scm(primary);
        }
        self.rebind_workspace_watchers();
        self.sync_workspace_fanout();
        self.refresh_workspace_title();
        self.save_workspace_folders();
        self.status = format!("Removed folder: {}", path.display());
    }

    /// (Re)spawn one watcher per workspace root, splitting the per-OS
    /// watch caps across them (#147): the caps bound kernel resources per
    /// PROCESS, so N roots share one budget rather than multiplying it.
    fn rebind_workspace_watchers(&mut self) {
        let shares = self.roots.iter().count();
        let primary = self.workspace_root().to_path_buf();
        self.fs_watch.rebind_sharing(&primary, &self.tree, shares);
        self.fs_watch_extra = self
            .roots
            .iter()
            .skip(1)
            .map(|r| FsWatch::spawn_event_only(r, shares))
            .collect();
    }

    /// Push the current root set into the per-root fan-outs that are not
    /// watcher-shaped: the Cmd+P index, the search worker + panel, and
    /// the LSP project-root bound.
    fn sync_workspace_fanout(&mut self) {
        self.file_finder_index = None;
        self.file_finder = None;
        self.kick_file_finder_index_rebuild();
        let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
        let _ = self
            .search_query_tx
            .send(SearchRequest::SetRoots(roots.clone()));
        self.search.roots = roots.clone();
        if let Some(lsp) = &self.lsp {
            lsp.set_extra_roots(roots.into_iter().skip(1).collect());
        }
    }

    /// Re-emit the OSC window title for the current folder set: the
    /// primary root's name, with VS Code's " (Workspace)" marker while
    /// more than one folder is open (#147).
    fn refresh_workspace_title(&mut self) {
        use std::io::Write;
        let mut title = build_title(self.workspace_root());
        if self.roots.is_multi() {
            title.push_str(" (Workspace)");
        }
        let mut out = std::io::stdout();
        let _ = out.write_all(&set_title_seq(&title));
        let _ = out.flush();
    }

    /// Persist the current secondary-folder list under the primary
    /// root's key (#153) — the terminal-session model: an empty list
    /// prunes the key.
    fn save_workspace_folders(&mut self) {
        let primary = self.roots.primary().display().to_string();
        let folders: Vec<PathBuf> = self.roots.iter().skip(1).map(Path::to_path_buf).collect();
        if let Err(e) =
            crate::workspace::save_folders_for_root(&self.workspace_folders_path, &primary, folders)
        {
            // A corrupt store is refused, never replaced (#156 review):
            // the arrangement still works this session, it just won't
            // persist until the store is repaired or removed.
            self.status = format!("Workspace folders not saved: {e}");
        }
    }

    /// Restore the saved folder set for the current primary root (#153):
    /// each surviving folder re-joins through the normal add fan-out; a
    /// folder that no longer exists on disk is dropped from the record
    /// rather than restored.
    pub fn restore_workspace_folders(&mut self) -> usize {
        let map = crate::workspace::load_folders(&self.workspace_folders_path);
        let primary = self.roots.primary().display().to_string();
        let Some(saved) = map.get(&primary).cloned() else {
            return 0;
        };
        let before = self.roots.iter().count();
        for folder in saved {
            if folder.is_dir() {
                self.add_workspace_folder(folder);
            }
        }
        // Rewrites the record from what actually restored, dropping
        // vanished folders (and pruning the key if none survived).
        self.save_workspace_folders();
        // The caller composes the user-facing message: setting status
        // here was immediately overwritten on the re-root path (#156
        // review).
        self.roots.iter().count() - before
    }

    /// Apply a `.code-workspace` file (#163): re-root to its first folder
    /// and install its folder set exactly (the pending set suppresses the
    /// automatic store restore for this re-root).
    fn open_workspace_file(&mut self, path: &Path) {
        match crate::workspace::parse_workspace_file(path) {
            Ok(folders) => {
                let mut it = folders.into_iter();
                let primary = it.next().expect("parse guarantees a folder");
                if !primary.is_dir() {
                    // Refuse before touching the workspace: re-rooting
                    // into a vanished folder would strand the window
                    // (#164 review).
                    self.status = format!("Workspace file: missing folder {}", primary.display());
                    return;
                }
                self.pending_workspace_folders = Some(it.collect());
                self.change_workspace_root(primary);
            }
            Err(e) => self.status = format!("Workspace file: {e}"),
        }
    }

    /// Open the fuzzy directory picker in add-folder mode (#147): the
    /// same zoxide-backed popup as Cmd+Z, with Enter adding the chosen
    /// directory as a workspace root instead of re-rooting.
    fn open_add_folder_picker(&mut self) {
        self.zoxide_add_folder = true;
        self.open_zoxide_jump();
        if self.zoxide_jump.is_some() {
            self.status =
                String::from("Add Folder to Workspace: pick a directory — Enter adds, Esc cancels");
        }
    }

    /// Re-root the workspace at `new_root`. Resets the file tree, updates
    /// `workspace_root`, refreshes git status and the source-control
    /// panel, and respawns the FS watcher off-thread (a recursive stat
    /// walk on a multi-GB monorepo is the dominant cost - blocking the
    /// UI thread for it is what froze the app on "Make root"). The
    /// polling fallback in `drain_fs_events` keeps the tree fresh until
    /// the watcher comes online via `try_install_pending_init`. Open
    /// editor tabs are NOT closed - a path that escapes the new root
    /// still resolves on disk and the user may want to keep it open.
    /// Compare anchor / clipboard / marks are reset because they point
    /// into the old workspace.
    pub fn change_workspace_root(&mut self, new_root: PathBuf) {
        let display = new_root.display().to_string();
        // The remembered task belongs to the old workspace; Rerun Last Task
        // must rediscover, not rerun the old project's command here.
        self.last_task = None;
        // Read the panel's untouched-ness BEFORE the cd seed below: the seed
        // is an input write, which clears it. Then persist the outgoing
        // workspace's pane layout under ITS key while `workspace_root` still
        // names it — every save after the swap keys on the new root, which
        // both discarded this layout on re-root and filed the old panes
        // under the new workspace's entry (#137).
        let panel_pristine = self.terminals.len() == 1 && self.terminals[0].is_pristine();
        self.save_terminal_session();
        let mut shell_synced = true;
        if let Some(active) = self.terminals.get_mut(self.active_terminal) {
            // cwd_seed_is_safe, not foreground_is_shell: a pane whose shell
            // is still starting up (rc files own the tty, no input ever
            // written, no prompt yet) must still get the seed — it queues as
            // type-ahead for the first prompt (#94).
            if active.cwd_seed_is_safe() {
                active.change_cwd(&new_root);
            } else {
                shell_synced = false;
            }
        }
        self.roots.replace_primary(new_root.clone());
        // A panel the user never touched — the startup default, one unnamed
        // shell with no input ever typed and no launched program — is swapped
        // for the incoming workspace's saved layout, the same restore startup
        // runs. A panel with any user state instead survives the re-root
        // as-is: navigation must never destroy live shells.
        if panel_pristine {
            self.restore_terminal_session();
        }
        // Rebind the LSP servers to the new root. The manager captured its
        // workspace folder once, at App::new, from croft's launch directory -
        // and the Croft.app launcher hardcodes that to ~/Documents. Re-rooting
        // into a child repo left rust-analyzer running `cargo metadata` against
        // the parent, which has no Cargo.toml, so every opened .rs came back as
        // an `unlinked-file` with no hover / completion / semantic tokens.
        // Spawn a fresh manager rooted at new_root; assigning over the Option
        // drops the old manager, whose Drop shuts its servers down. Clearing
        // lsp_last_seen makes the next sync_lsp() re-open every live editor tab
        // against the new servers; the stale diagnostics / progress from the
        // old root are dropped with it.
        self.lsp = match crate::lsp::LspManager::new(new_root.clone()) {
            Ok(m) => Some(m),
            Err(e) => {
                eprintln!("lsp manager rebind failed: {e}");
                None
            }
        };
        self.lsp_last_seen.clear();
        self.lsp_diagnostics.clear();
        self.lsp_progress.clear();
        // Build diagnostics describe the OLD workspace's files; a re-root
        // that kept them showed the previous project's errors forever.
        self.build_diagnostics.clear();
        self.build_diag_files_by_pane.clear();
        // Refresh the window/icon title: it was emitted once at startup from
        // the launch dir and never updated, so after a re-root it kept showing
        // the parent (e.g. "Documents") instead of the repo. OSC 0 is
        // grid-independent, so writing it straight to stdout between draws is
        // safe - the same pattern startup uses.
        {
            use std::io::Write;
            let mut out = std::io::stdout();
            let _ = out.write_all(&set_title_seq(&build_title(&new_root)));
            let _ = out.flush();
        }
        self.tree.set_root(new_root.clone());
        self.tree_clipboard = None;
        self.compare_anchor = None;
        // The agent review queue belongs to the workspace that was left
        // (#345). `set_root` has just cleared the Explorer's copy; this
        // clears the ledger it is drawn from, so the two cannot come back
        // apart the moment an agent writes under the new root.
        self.agent_ledger = crate::agent_lane::AgentLedger::new();
        self.fs_watch.rebind(&new_root, &self.tree);
        // A re-root collapses the workspace to one folder: the secondary
        // watchers go with their roots (#147).
        self.fs_watch_extra.clear();
        // A re-root collapses the git side too (#149): the secondary
        // workers drop with their roots, the active repo IS the new
        // primary, and the per-repo HEAD markers restart.
        self.git_extra.clear();
        self.active_scm_root = new_root.clone();
        self.git_head_oids.clear();
        self.git.bypass_debounce();
        // Rebind the worker's root before any query, otherwise the next
        // Status / Changes request runs against the stale root captured
        // at App::new and the Source Control panel keeps reporting the
        // OLD repo's state (or "no repo") even after a Make Root that
        // landed inside a real git tree.
        self.git.set_root(new_root.clone());
        self.refresh_git_status_debounced();
        // Drop the old repo's graph before the refresh (inside
        // refresh_source_control) refetches for the new root; a reply still
        // in flight for the old root is dropped by the drain's root tag.
        self.commit_graph.clear();
        self.refresh_source_control();
        // Rebind the test runner too, else `cargo test -- --list` keeps running
        // in the launch dir captured at spawn (e.g. ~/Documents, no Cargo.toml)
        // and the Testing view stays empty after a Make Root into a child repo.
        // Then drop the old project's tree: its cases are unrelated, they keep
        // the beaker badge counting dead failures, and a non-empty panel blocks
        // open_testing_view's discover-on-empty, so the new project would never
        // be discovered. Results still streaming from the old root are dropped
        // by the drain's epoch tag (same idea as the commit graph's root tag).
        // With the Testing view in front, re-discover right away; otherwise the
        // now-empty panel discovers on its next open.
        self.active_test_root = new_root.clone();
        self.test_worker.set_root(new_root.clone());
        self.testing.reset();
        // Drop any in-flight `cargo test --no-run`: the drain would refuse
        // its root-mismatched binary anyway, but the occupied slot kept
        // refusing NEW debug builds until the stale compile finished.
        self.disarm_failure_breakpoint();
        self.pending_test_debug = None;
        if self.sidebar_view == SidebarView::Testing {
            self.discover_tests();
        }
        // Rebind the search worker and the panel's display root to the new
        // Explorer root so the next search targets this directory and its
        // subdirectories, not the root captured when the worker was spawned.
        // Drop the old root's hits so nothing stale lingers in the panel.
        let _ = self
            .search_query_tx
            .send(SearchRequest::SetRoot(new_root.clone()));
        self.search.root = new_root.clone();
        self.search.roots = vec![new_root.clone()];
        self.search.hits.clear();
        self.search.selected = 0;
        self.search.scroll = 0;
        // Drop any in-flight walker for the OLD root so its result is
        // discarded when it tries to send. Then kick a fresh walk
        // against the new root. file_finder_index keeps the old entries
        // for now so a Cmd+P press during the rebuild window shows
        // stale-but-immediate results instead of a UI freeze.
        self.file_finder_index_rx = None;
        self.file_finder_index_dirty = false;
        self.kick_file_finder_index_rebuild();
        // Rebind the resident navigator: the activation record, relay
        // socket, and single-host lock are all keyed by workspace root
        // (captured at App::new), so without this a `croft pair` run in the
        // NEW root writes a record this window never reads and the
        // navigator can never seat again after a re-root. Any seat from the
        // old root is torn down with its comment boxes; if this window had
        // self-appointed the old root's collab owner, that session goes too
        // (a fresh activation self-appoints against the new root).
        if let Some(host) = self.pair_host.take() {
            let sites = host.caret_sites();
            self.collab_carets.retain(|s, _| !sites.contains(s));
            self.status = String::from("Navigator unseated (workspace changed)");
        }
        self.navigator_notes.clear();
        self.pair_commentary_buf.clear();
        self.pair_turn_origin = None;
        self.clear_problem_fix();
        self.editor.comment_focus = None;
        if self.pair_host_lock.take().is_some() {
            self.collab = None;
            self.collab_config = None;
        }
        // Old-root merge bases are keyed by root-relative file, like the
        // carets below: never let them merge into a same-named file here.
        self.collab_offline_base.clear();
        self.pair_record_path = crate::session::pair_record_path(&new_root);
        self.pair_socket = crate::session::collab_socket_path(&new_root);
        self.pair_host_lock_path = crate::session::pair_host_lock_path(&new_root);
        self.navigator_down = false; // the death latch belonged to the old root
        self.last_pair_check = None; // read the new record this tick, not in 1s
        // Old-workspace carets are keyed by root-relative file, so a
        // same-named file under the new root would wear a departed peer's
        // caret. The live session repopulates its own on the next poll.
        self.collab_carets.clear();
        // The new primary's saved folder set comes back with it (#153),
        // the same way its terminal layout does: re-rooting into a
        // workspace restores that workspace's arrangement.
        let restored = match self.pending_workspace_folders.take() {
            Some(folders) => {
                let before = self.roots.iter().count();
                for folder in folders {
                    self.add_workspace_folder(folder);
                }
                self.roots.iter().count() - before
            }
            None => self.restore_workspace_folders(),
        };
        let folders_note = if restored > 0 {
            format!(
                " (+{restored} workspace folder{})",
                if restored == 1 { "" } else { "s" }
            )
        } else {
            String::new()
        };
        // The workspace settings layers follow the primary root (#251): the
        // old repo's .croft/config.json must stop applying and the new one
        // start, without a relaunch. Runs after the root swap above so the
        // merge reads the new primary. The status write below is deliberate:
        // remerge_settings sets its own status, and the re-root message is
        // the one that should win here.
        self.remerge_settings();
        self.status = if shell_synced {
            format!("Workspace root: {display}{folders_note}")
        } else {
            format!("Workspace root: {display}{folders_note} (terminal busy; shell not moved)")
        };
    }

    fn is_explorer_focused(&self) -> bool {
        self.focus == Pane::Tree && self.sidebar_view == SidebarView::Explorer
    }

    /// Dispatch the Explorer-pane keyboard shortcuts (Cmd+F / Cmd+Shift+F /
    /// Cmd+R / F2 / Cmd+/). Returns true if the key was handled. The
    /// target node is whichever row the user has highlighted; folder-only
    /// actions (Make root) are no-ops on file selections.
    fn handle_explorer_shortcut(&mut self, key: KeyEvent) -> bool {
        if is_tree_zoxide_jump_key(key) {
            self.open_zoxide_jump();
            return true;
        }
        if is_tree_new_file_key(key) {
            let target = self.explorer_create_target_dir();
            self.open_create_prompt(CreateKind::File, target);
            return true;
        }
        if is_tree_new_folder_key(key) {
            let target = self.explorer_create_target_dir();
            self.open_create_prompt(CreateKind::Folder, target);
            return true;
        }
        if is_tree_rename_key(key) {
            if let Some(path) = self.explorer_selected_path() {
                self.open_rename_prompt(path);
            }
            return true;
        }
        // Reveal in Finder is a local-macOS-only host bridge: on a remote SSH
        // session croft runs on a headless host with no Finder, so the chord
        // falls through there exactly as the menu entry is withheld.
        if !self.is_remote && cfg!(target_os = "macos") && is_reveal_in_finder_key(key) {
            if let Some(path) = self.explorer_selected_path() {
                self.reveal_in_finder(path);
            }
            return true;
        }
        if is_tree_make_root_key(key) {
            if let Some(path) = self.explorer_selected_folder() {
                self.change_workspace_root(path);
            }
            return true;
        }
        if is_tree_make_parent_root_key(key) {
            if let Some(path) = self.explorer_parent_for_make_root() {
                self.change_workspace_root(path);
            }
            return true;
        }
        false
    }

    /// Resolve the parent folder of the highlighted node for the
    /// `Cmd+Shift+/` "Make root at parent" gesture. Works on files
    /// (parent = containing directory), folders (parent = its parent),
    /// and the tree root itself (parent = one filesystem level up).
    /// Returns `None` when the selected path has no parent (filesystem
    /// root) or no node is currently selected.
    fn explorer_parent_for_make_root(&self) -> Option<PathBuf> {
        let n = self.tree.nodes.get(self.tree.selected)?;
        n.path.parent().map(|p| p.to_path_buf())
    }

    fn explorer_selected_path(&self) -> Option<PathBuf> {
        self.tree
            .nodes
            .get(self.tree.selected)
            .map(|n| n.path.clone())
    }

    fn explorer_selected_folder(&self) -> Option<PathBuf> {
        let n = self.tree.nodes.get(self.tree.selected)?;
        if n.is_dir && n.path != self.tree.root {
            Some(n.path.clone())
        } else {
            None
        }
    }

    fn explorer_create_target_dir(&self) -> PathBuf {
        let node = self.tree.nodes.get(self.tree.selected);
        crate::widgets::file_tree::create_target_dir_for(node, &self.tree.root)
    }

    /// VS Code-style type-to-jump for the Explorer. Each printable
    /// keystroke arriving while the file tree is focused appends to a
    /// short-lived prefix buffer and snaps selection to the first
    /// visible node whose name starts with that prefix. Keystrokes
    /// further apart than `TREE_TYPEAHEAD_WINDOW` reset the buffer to
    /// a single character and cycle to the next match, so re-pressing
    /// the same letter walks through siblings beginning with it.
    /// `now` is injected for deterministic tests.
    fn apply_tree_typeahead(&mut self, c: char, now: std::time::Instant) {
        let within_window = self
            .tree_typeahead
            .as_ref()
            .is_some_and(|t| now.duration_since(t.last) < TREE_TYPEAHEAD_WINDOW);
        let prefix = if within_window {
            let mut p = self.tree_typeahead.as_ref().unwrap().prefix.clone();
            p.push(c.to_ascii_lowercase());
            p
        } else {
            c.to_ascii_lowercase().to_string()
        };
        let n = self.tree.nodes.len();
        if n > 0 {
            let start = if within_window {
                self.tree.selected
            } else {
                (self.tree.selected + 1) % n
            };
            if let Some(idx) = self.tree.find_prefix(&prefix, start) {
                self.tree.selected = idx;
                self.tree.anchor = idx;
                self.tree.marked.clear();
            }
        }
        self.tree_typeahead = Some(TreeTypeahead { prefix, last: now });
    }

    fn dispatch_menu_action(&mut self, action: MenuAction, target_dir: PathBuf) {
        match action {
            MenuAction::Create(kind) => self.open_create_prompt(kind, target_dir),
            MenuAction::Delete { paths } => self.delete_paths(paths),
            MenuAction::Rename(path) => self.open_rename_prompt(path),
            MenuAction::Cut(paths) => {
                let n = paths.len();
                self.tree_clipboard = Some(ExplorerClipboard {
                    mode: ExplorerClipMode::Cut,
                    paths,
                });
                self.status = if n == 1 {
                    String::from("Cut 1 item")
                } else {
                    format!("Cut {n} items")
                };
            }
            MenuAction::Copy(paths) => {
                let n = paths.len();
                self.tree_clipboard = Some(ExplorerClipboard {
                    mode: ExplorerClipMode::Copy,
                    paths,
                });
                self.status = if n == 1 {
                    String::from("Copied 1 item")
                } else {
                    format!("Copied {n} items")
                };
            }
            MenuAction::Paste(dest) => self.paste_into(dest),
            MenuAction::SelectForCompare(path) => {
                let label = path
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| path.display().to_string());
                self.compare_anchor = Some(path);
                self.status = format!("Selected {label} for compare");
            }
            MenuAction::AddWorkspaceFolder => self.open_add_folder_picker(),
            MenuAction::RemoveWorkspaceFolder(path) => self.remove_workspace_folder(path),
            MenuAction::MakeRoot(folder) => {
                self.change_workspace_root(folder);
            }
            MenuAction::RevealInFinder(path) => self.reveal_in_finder(path),
            MenuAction::OpenInViewer(id, path) => {
                // The row was built when the menu opened; an extension
                // removed since then must not make the click a silent no-op.
                match crate::mcp::registry::viewer_by_id_in_dir(&self.config_dir, &id) {
                    Some(viewer) => self.open_in_viewer(&viewer, &path),
                    None => self.status = format!("{id} is no longer available"),
                }
            }
            MenuAction::CopyTabPath(path) => self.copy_path_to_clipboard(path),
            MenuAction::CopyTabRelativePath(path) => self.copy_relative_path_to_clipboard(path),
            MenuAction::RevealInExplorer(path) => self.reveal_in_explorer(path),
            MenuAction::CloseTab(idx) => {
                self.record_closed_tab_at(idx);
                if self.editor.close_tab(idx) {
                    self.sync_open_file_poll_mtime();
                    self.status = String::from("Closed tab");
                    self.poke_cursor();
                    self.collapse_split_if_empty();
                }
            }
            MenuAction::CloseOtherTabs(keep_idx) => {
                self.record_closed_tabs_where(|i, ed| i != keep_idx && !ed.pinned);
                let removed = self.editor.close_others(keep_idx);
                if removed > 0 {
                    self.sync_open_file_poll_mtime();
                    self.status = if removed == 1 {
                        String::from("Closed 1 other tab")
                    } else {
                        format!("Closed {removed} other tabs")
                    };
                    self.poke_cursor();
                }
            }
            MenuAction::CloseTabsToRight(from_idx) => {
                self.record_closed_tabs_where(|i, ed| i > from_idx && !ed.pinned);
                let removed = self.editor.close_to_right(from_idx);
                if removed > 0 {
                    self.sync_open_file_poll_mtime();
                    self.status = if removed == 1 {
                        String::from("Closed 1 tab to the right")
                    } else {
                        format!("Closed {removed} tabs to the right")
                    };
                    self.poke_cursor();
                }
            }
            MenuAction::CloseAllTabs => self.close_all_tabs(),
            MenuAction::CloseSavedTabs => self.close_saved_tabs(),
            MenuAction::KeepTabOpen(idx) => {
                if self.editor.keep_open(idx) {
                    self.status = String::from("Kept tab open");
                    self.poke_cursor();
                }
            }
            MenuAction::ToggleTabPin(idx) => {
                let pinned = self.editor.toggle_pin(idx);
                self.status = String::from(if pinned { "Pinned tab" } else { "Unpinned tab" });
                self.poke_cursor();
            }
            MenuAction::SplitEditor => self.split_editor(),
            MenuAction::SplitEditorLeft => {
                self.split_editor_dir(editor_layout::SplitDir::Horizontal, false)
            }
            MenuAction::SplitEditorUp => {
                self.split_editor_dir(editor_layout::SplitDir::Vertical, false)
            }
            MenuAction::SplitEditorDown => {
                self.split_editor_dir(editor_layout::SplitDir::Vertical, true)
            }
            MenuAction::MoveEditorUp => self.move_active_editor(editor_layout::Dir::Up),
            MenuAction::MoveEditorDown => self.move_active_editor(editor_layout::Dir::Down),
            MenuAction::MoveEditorLeft => self.move_active_editor(editor_layout::Dir::Left),
            MenuAction::MoveEditorRight => self.move_active_editor(editor_layout::Dir::Right),
            MenuAction::SplitInGroup => self.split_in_group(),
            MenuAction::FocusGroupLeft => self.focus_editor_group(true),
            MenuAction::FocusGroupRight => self.focus_editor_group(false),
            MenuAction::MoveIntoNewWindow(idx) => self.move_into_new_window(idx),
            MenuAction::CopyIntoNewWindow(idx) => self.copy_into_new_window(idx),
            MenuAction::CompareWithSelected { anchor, other } => {
                match self.editor.open_diff(&anchor, &other) {
                    Ok(()) => {
                        self.focus_pane(Pane::Editor);
                        self.compare_anchor = None;
                        self.sync_open_file_poll_mtime();
                        let l = anchor
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_else(|| anchor.display().to_string());
                        let r = other
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_else(|| other.display().to_string());
                        self.status = format!("Diff: {l} \u{2194} {r}");
                    }
                    Err(e) => {
                        self.status = format!("Diff failed: {e}");
                    }
                }
            }
            MenuAction::RenameSymbolAt { row, col } => {
                self.editor.collapse_carets();
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.start_rename_symbol();
            }
            MenuAction::ChangeAllOccurrencesAt { row, col } => {
                self.editor.collapse_carets();
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.start_change_all_occurrences();
            }
            MenuAction::NavigateBack => self.nav_back(),
            MenuAction::NavigateForward => self.nav_forward(),
            MenuAction::GoToDefinitionAt { row, col } => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.request_definition_at_cursor();
            }
            MenuAction::GoToDeclarationAt { row, col } => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.request_declaration_at_cursor();
            }
            MenuAction::GoToTypeDefinitionAt { row, col } => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.request_type_definition_at_cursor();
            }
            MenuAction::GoToImplementationAt { row, col } => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.request_implementation_at_cursor();
            }
            MenuAction::QuickFixAt { row, col } => {
                self.editor.collapse_carets();
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.start_code_action();
            }
            MenuAction::GoToReferencesAt { row, col } => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.request_references_at_cursor();
            }
            MenuAction::GoToLocation { path, line, col } => {
                self.go_to_definition(path, line, col);
            }
            MenuAction::ToggleBreakpointAt { line } => {
                self.focus_pane(Pane::Editor);
                self.debug_toggle_breakpoint_line(line);
            }
            MenuAction::EditBreakpointConditionAt { line } => {
                self.focus_pane(Pane::Editor);
                self.debug_edit_condition_line(line);
            }
            MenuAction::EditLogpointAt { line } => {
                self.focus_pane(Pane::Editor);
                self.debug_edit_logpoint_line(line);
            }
            MenuAction::AskNavigatorAt { line } => {
                self.focus_pane(Pane::Editor);
                self.open_ask_navigator((line, line), String::new());
            }
            MenuAction::AskNavigatorSelection { start, end } => {
                self.focus_pane(Pane::Editor);
                let selection = self.editor.selection_text();
                self.open_ask_navigator((start, end), selection);
            }
            MenuAction::AskNavigatorAboutCapture => self.ask_navigator_about_capture(),
            MenuAction::FixProblemWithNavigator { path, item } => {
                self.fix_problem_with_navigator(path, item, Vec::new());
            }
            MenuAction::ShowCallsAt { row, col, incoming } => {
                self.editor.cursor_row = row;
                self.editor.cursor_col = col;
                self.focus_pane(Pane::Editor);
                self.request_call_hierarchy_at_cursor(incoming);
            }
            MenuAction::OpenThemePicker => self.open_theme_picker(),
            MenuAction::SetTheme(theme) => self.apply_theme(theme),
            MenuAction::ToggleExplorerView(view) => self.toggle_explorer_view(view),
            MenuAction::OpenCustomizeLayout => self.open_customize_layout_menu(),
            MenuAction::ToggleActivityBar => {
                self.activity_bar_visible = !self.activity_bar_visible;
                // The bar is a structural auto-hide suppression, and unlike Zen
                // it flips here on its own. A pending collapse armed against the
                // old chrome would otherwise sit armed while `allowed()` declines
                // for it, then fire on the first idle tick after the bar comes
                // back, with no focus move of the user's own.
                //
                // Cancel the collapse. And when the bar goes AWAY, drop the pin
                // too — for the reason `toggle_side_bar` already refuses to bank
                // one in that state: no collapse can fire while the bar is
                // hidden, so a pin held across that period is unconsumable, and
                // it silently eats the first real collapse after the bar
                // returns. Those two sites disagreed about the same question
                // until this line; the bank-time answer is the right one.
                //
                // Revealing the bar leaves any pin alone: a pin banked while the
                // bar is visible belongs to a reveal that can still be honoured.
                self.sidebar_dwell.disarm();
                if !self.activity_bar_visible {
                    self.sidebar_pinned_open = false;
                }
                self.persist_layout();
                self.after_chrome_visibility_change();
                self.open_customize_layout_menu_on(&MenuAction::ToggleActivityBar);
            }
            MenuAction::ToggleSideBar => {
                self.toggle_side_bar();
                self.after_chrome_visibility_change();
                self.open_customize_layout_menu_on(&MenuAction::ToggleSideBar);
            }
            MenuAction::ToggleAutoHideSideBar => {
                self.toggle_sidebar_auto_hide();
                self.open_customize_layout_menu_on(&MenuAction::ToggleAutoHideSideBar);
            }
            MenuAction::ToggleSecondarySideBar => {
                self.toggle_secondary_side_bar();
                self.open_customize_layout_menu_on(&MenuAction::ToggleSecondarySideBar);
            }
            MenuAction::TogglePanel => {
                self.toggle_terminal();
                self.open_customize_layout_menu_on(&MenuAction::TogglePanel);
            }
            MenuAction::ToggleStatusBar => {
                self.status_bar_visible = !self.status_bar_visible;
                self.persist_layout();
                self.after_chrome_visibility_change();
                self.open_customize_layout_menu_on(&MenuAction::ToggleStatusBar);
            }
            MenuAction::SetSideBarPosition(pos) => {
                self.side_bar_position = pos;
                self.persist_layout();
                self.after_chrome_visibility_change();
                self.open_customize_layout_menu_on(&MenuAction::SetSideBarPosition(pos));
            }
            MenuAction::SetPanelAlignment(al) => {
                self.panel_alignment = al;
                self.persist_layout();
                self.open_customize_layout_menu_on(&MenuAction::SetPanelAlignment(al));
            }
            MenuAction::SetQuickInputPosition(pos) => {
                self.quick_input_position = pos;
                self.persist_layout();
                self.open_customize_layout_menu_on(&MenuAction::SetQuickInputPosition(pos));
            }
            MenuAction::ToggleZenMode => self.toggle_zen_mode(),
            MenuAction::RenameTerminal(idx) => self.begin_rename_terminal(idx),
            MenuAction::ClearTerminal(idx) => self.clear_terminal_at(idx),
            MenuAction::TerminalCopySelection => self.copy_terminal_selection(),
            MenuAction::TerminalPaste => self.paste_clipboard_into_terminal(),
            MenuAction::TerminalQuickSelect => self.open_terminal_quick_select(),
            MenuAction::TerminalCopyMode => self.open_terminal_copy_mode(),
            MenuAction::TerminalCommandHistory => self.open_command_history(),
            MenuAction::OpenScrollbackInEditor => self.open_scrollback_in_editor(),
            MenuAction::ToggleBroadcastInput => self.toggle_broadcast_input(),
            MenuAction::ToggleBroadcastExclusion => self.toggle_broadcast_exclusion(),
            MenuAction::UndoCloseTerminal => self.undo_close_terminal(),
            MenuAction::CopyCommandOutput(idx, d) => self.copy_command_output(idx, d),
            MenuAction::SelectCommandOutput(idx, d) => self.select_command_output(idx, d),
            MenuAction::RerunCommand(idx, d) => self.rerun_command(idx, d),
            MenuAction::ToggleMaximizeTerminal(idx) => {
                if !self.terminal_pane_maximized {
                    self.active_terminal = idx;
                }
                self.toggle_terminal_pane_maximize();
            }
            MenuAction::ToggleCollapseTerminal(idx) => self.toggle_terminal_collapse(idx),
            MenuAction::NewTerminalWithProfile(shell) => {
                let label = std::path::Path::new(&shell)
                    .file_name()
                    .and_then(|s| s.to_str())
                    .unwrap_or(&shell)
                    .to_string();
                match self.split_terminal_with_shell(&shell) {
                    Ok(()) => self.status = format!("Opened {label} terminal"),
                    Err(e) => self.status = format!("New terminal failed: {e}"),
                }
            }
            MenuAction::ToggleMinimap => self.toggle_minimap(),
            MenuAction::SetMinimapSide(side) => {
                self.minimap_side = side;
                // The strip jumps columns: evict the old placement so it
                // doesn't ghost, and force a rebake at the new position.
                self.disable_minimap_image();
            }
            MenuAction::SetLanguage(lang) => {
                self.editor.set_language(lang);
                self.status = format!("Language Mode: {}", self.editor.language_label());
            }
            MenuAction::SetLineEnding(eol) => {
                if self.editor.eol != eol {
                    self.editor.eol = eol;
                    // The content is unchanged but the on-disk bytes will differ:
                    // mark dirty so the user saves to apply the new EOL.
                    self.editor.dirty = true;
                }
                self.status = format!("End of Line: {}", eol.label());
            }
            MenuAction::SetEncoding(enc) => {
                // Reopening re-reads the file over the buffer and clears both
                // history stacks, so unsaved work would be gone with no way
                // back through Cmd+Z. The encoding segment sits a few cells
                // from the Ln/Col readout in the status bar, and picking the
                // encoding already in use looks like a no-op, so this is easy
                // to hit by accident. Never discard on its behalf.
                if self.editor.dirty {
                    // Deliberately NOT "save first": the buffer may be showing
                    // mojibake precisely because it was decoded wrongly, and
                    // saving writes those replacement characters over the
                    // original bytes. Undoing is the one route that loses
                    // nothing on either side.
                    self.status = String::from(
                        "Reopen with Encoding replaces the buffer from disk. Undo your unsaved changes first (Cmd+Z), or copy them elsewhere.",
                    );
                } else {
                    match self.editor.reopen_with_encoding(enc) {
                        Ok(()) => self.status = format!("Reopened with {}", enc.name()),
                        Err(e) => self.status = format!("Reopen failed: {e}"),
                    }
                }
            }
            MenuAction::SetIndentStyle(style) => {
                self.editor.set_indent_style(style);
                self.status = style.label();
            }
            MenuAction::ConvertIndentation(to_spaces) => {
                if to_spaces {
                    self.editor.indentation_to_spaces();
                    self.status = String::from("Converted indentation to spaces");
                } else {
                    self.editor.indentation_to_tabs();
                    self.status = String::from("Converted indentation to tabs");
                }
            }
        }
    }

    /// Cmd+K W / tab context "Close All": close every tab in EVERY editor
    /// group, not just the focused one, collapsing any split back to a single
    /// blank pane. A side-by-side layout (e.g. `cgr duplicates` diffs) would
    /// otherwise only empty the clicked group and look like a single close
    /// once the blank group collapsed away.
    fn close_all_tabs(&mut self) {
        let mut removed = self.editor.close_all();
        if self.editor_layout.is_split() {
            removed += self
                .editor_layout
                .inactive_groups()
                .iter()
                .map(|g| g.editors.len())
                .sum::<usize>();
            self.editor_layout = editor_layout::EditorLayout::single();
            self.editor_seams.clear();
            self.disable_editor_image(1);
            self.sync_focus_flags();
        }
        self.sync_open_file_poll_mtime();
        self.status = if removed == 1 {
            String::from("Closed 1 tab")
        } else {
            format!("Closed {removed} tabs")
        };
        self.poke_cursor();
    }

    /// Close every saved (non-dirty) editor tab, keeping any with unsaved
    /// changes. Shared by the tab context menu and the `Cmd+K U` chord so both
    /// surfaces produce the same status line and split-collapse behavior.
    fn close_saved_tabs(&mut self) {
        let removed = self.editor.close_saved();
        if removed == 0 {
            self.status = String::from("No saved tabs to close");
            return;
        }
        self.sync_open_file_poll_mtime();
        self.status = if removed == 1 {
            String::from("Closed 1 saved tab")
        } else {
            format!("Closed {removed} saved tabs")
        };
        self.poke_cursor();
        self.collapse_split_if_empty();
    }

    /// Copy `path` (an editor tab's absolute path) to the system clipboard via
    /// the NSPasteboard-first wrapper (OSC 52 fallback on a remote host). Shared
    /// by the tab context menu and the `Cmd+Opt+C` chord. Matches VS Code's
    /// "Copy Path".
    fn copy_path_to_clipboard(&mut self, path: PathBuf) {
        let text = path.display().to_string();
        self.status = if copy_to_clipboard(&text) {
            format!("Copied path: {text}")
        } else {
            String::from("Could not copy path to clipboard")
        };
    }

    /// VS Code "Copy Relative Path": copy `path` relative to the workspace
    /// root. Files outside the root (rare: a tab opened by absolute path above
    /// the workspace) fall back to the absolute path so the clipboard never
    /// holds a misleading `../../` walk or an empty string.
    fn copy_relative_path_to_clipboard(&mut self, path: PathBuf) {
        let text = relative_clipboard_text(&path, self.workspace_root());
        self.status = if copy_to_clipboard(&text) {
            format!("Copied relative path: {text}")
        } else {
            String::from("Could not copy path to clipboard")
        };
    }

    /// Reveal `path` (an editor tab's file) in the Explorer tree: switch the
    /// side bar to the Explorer, expand the file's parent folders, select its
    /// row, and focus the tree. Shared by the tab context menu and the
    /// `Cmd+K E` chord. Matches VS Code's "Reveal in Explorer View".
    fn reveal_in_explorer(&mut self, path: PathBuf) {
        self.set_sidebar_view(SidebarView::Explorer);
        // A sidebar-targeting command must work even with the sidebar hidden
        // (#260). `set_sidebar_view` above already forced it open and focuses
        // the tree, so nothing further is required here.
        let found = self.tree.reveal_path(&path);
        self.focus_pane(Pane::Tree);
        self.status = if found {
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| path.display().to_string());
            format!("Revealed {name} in Explorer")
        } else {
            String::from("File is outside the workspace")
        };
    }

    /// Reveal `path` in macOS Finder by spawning `open -R`, which selects the
    /// entry inside its containing folder. Fire-and-forget: `open` hands off to
    /// LaunchServices and returns immediately, so the TUI never blocks. Only
    /// reachable on a local macOS session because `maybe_add_reveal_in_finder`
    /// withholds the menu entry everywhere else; the `cfg` guard keeps the call
    /// out of non-macOS builds entirely.
    fn reveal_in_finder(&mut self, path: PathBuf) {
        #[cfg(target_os = "macos")]
        {
            self.status = if std::process::Command::new("open")
                .arg("-R")
                .arg(&path)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
                .is_ok()
            {
                String::from("Revealed in Finder")
            } else {
                String::from("Could not reveal in Finder")
            };
        }
        #[cfg(not(target_os = "macos"))]
        {
            let _ = path;
        }
    }

    /// The editor group occupying physical column `side` (0 = left,
    /// 1 = right). When not split only side 0 exists. `editor` is always
    /// the active group, so which physical column it sits in depends on the
    /// active leaf's depth-first index in `editor_layout`.
    fn group_on_side(&self, side: usize) -> Option<&EditorTabs> {
        // Physical column maps directly to depth-first leaf index only in
        // the two-column layout. Every other layout - unsplit, or a grid of
        // three or more groups - bakes the ACTIVE group into slot 0 and
        // leaves slot 1 dark (see the render path), the same clamp
        // `focused_image_side` applies: resolving by DFS position here made
        // the image gate and the layout key read one group while the baked
        // pixels came from another.
        if self.editor_layout.leaf_count() != 2 {
            return (side == 0).then_some(&self.editor);
        }
        // The active group is hoisted into `self.editor`.
        if side == self.editor_layout.active_dfs_index() {
            Some(&self.editor)
        } else {
            self.editor_layout.group_ref_at_dfs(side)
        }
    }

    /// Step the focused PDF preview by `delta` pages, wrapping at the
    /// document ends. The overlay re-bakes on its own (the page is part of
    /// its re-emit key). Deliberate gestures only - arrows, menu; the wheel
    /// goes through [`Self::wheel_pdf_page`].
    fn step_pdf_page(&mut self, delta: i32) {
        self.editor.change_pdf_page(delta);
    }

    /// Wheel paging for the PDF preview. Differs from the key path twice
    /// over: it clamps at the document ends (no scroll wheel wraps a PDF),
    /// and a same-direction repeat inside the cooldown is dropped - every
    /// page step is a synchronous rasteriser run on the UI thread, so a
    /// momentum flick's burst of wheel events must coalesce instead of
    /// freezing the TUI for one render per event. A reversal is deliberate
    /// and always passes.
    fn wheel_pdf_page(&mut self, delta: i32) {
        const COOLDOWN: std::time::Duration = std::time::Duration::from_millis(150);
        let doc = self.editor.path.clone();
        if let Some((at, dir, last_doc)) = &self.last_pdf_wheel
            && *dir == delta.signum()
            && *last_doc == doc
            && at.elapsed() < COOLDOWN
        {
            return;
        }
        let Some(cur) = self.editor.pdf_page() else {
            return;
        };
        let target = if delta >= 0 {
            cur.saturating_add(delta as u32)
        } else {
            cur.saturating_sub(delta.unsigned_abs()).max(1)
        };
        self.editor.set_pdf_page(target);
        // Stamped AFTER the rasterise: the flick's remaining events queued
        // while the render ran, so a stamp taken at entry had already aged
        // by the render's duration when they were processed — a render
        // slower than the cooldown let every queued event through, one
        // blocking render each.
        self.last_pdf_wheel = Some((std::time::Instant::now(), delta.signum(), doc));
    }

    fn jump_pdf_page(&mut self, page: u32) {
        self.editor.set_pdf_page(page);
    }

    /// Resolve the PDF link under a click at screen cell (`col`, `row`) on
    /// the focused PDF preview, extracting the current page's link regions
    /// on first use (and caching them on the tab until the page changes).
    fn pdf_link_target_at(&mut self, col: u16, row: u16) -> Option<crate::pdf::LinkTarget> {
        let side = self.focused_image_side();
        let (cw_px, ch_px) = self.cell_pixel?;
        let frac = {
            let image = self.editor.image.as_ref()?;
            let pdf = image.pdf.as_ref()?;
            let layout = self.overlays.editor[side].layout()?;
            // A stale overlay (different tab, or a page flip the next frame
            // hasn't baked yet) must not hit-test the wrong page's geometry.
            if layout.path != pdf.source_path || layout.page != pdf.current_page {
                return None;
            }
            crate::iterm2_inline::cell_source_fraction(
                (
                    col.checked_sub(layout.cell_x)?,
                    row.checked_sub(layout.cell_y)?,
                ),
                (cw_px, ch_px),
                (layout.cell_w, layout.cell_h),
                (image.pixel_w, image.pixel_h),
            )?
        };
        let pdf = self.editor.image.as_mut()?.pdf.as_mut()?;
        if pdf.links.is_none() {
            match crate::pdf::page_links(&pdf.source_path, pdf.current_page) {
                Ok(links) => pdf.links = Some(links),
                // Not cached: a mid-write extraction failure (pdflatex
                // rebuilding the file) heals on the next click.
                Err(e) => {
                    self.status = format!("PDF links unavailable: {e}");
                    return None;
                }
            }
        }
        Some(pdf.links.as_ref()?.link_at(frac)?.target.clone())
    }

    fn focused_image_side(&self) -> usize {
        // There are physically two overlay slots (left/right column), and
        // only the two-column split keys them by group: every other layout -
        // unsplit, or a grid of three or more groups - bakes the active
        // group into slot 0 (see the render path). Indexing by DFS position
        // here panicked on a PDF click in the third group of a grid.
        if self.editor_layout.leaf_count() == 2 {
            self.editor_layout.active_dfs_index()
        } else {
            0
        }
    }

    /// Re-bake both editor image slots on the next render. Used when a
    /// full-screen modal that covered both panes closes.
    fn invalidate_editor_image_layouts(&mut self) {
        self.overlays.editor[0].invalidate_layout();
        self.overlays.editor[1].invalidate_layout();
    }

    /// Bake an OSC-1337 inline-image escape sized to one editor column so
    /// the active image tab can be painted on top of ratatui's text
    /// buffer. `side` selects the physical column (and the overlay slot).
    /// Skipped when that column's active tab is text or when the host
    /// terminal can't render inline images (Terminal.app, raw SSH); in
    /// those cases the metadata header line painted by the editor widget
    /// is the entire preview the user sees.
    fn update_editor_image_overlay(&mut self, side: usize, editor_area: Rect) {
        // Cheap pre-checks that don't touch the (large) image bytes, so
        // the common per-frame path skips the clone+bake entirely.
        if self.group_on_side(side).is_none_or(|g| g.image.is_none()) {
            self.disable_editor_image(side);
            return;
        }
        let Some(path) = self.group_on_side(side).and_then(|g| g.path.clone()) else {
            self.disable_editor_image(side);
            return;
        };
        if !self.inline_images_enabled() {
            self.disable_editor_image(side);
            return;
        }
        let Some((cw_px, ch_px)) = self.cell_pixel else {
            return;
        };
        // The editor widget paints its own 1-cell border + a 1-row header
        // strip; the EditorTabs widget paints a 1-row tab strip above
        // that. Carve those off before baking the image so the OSC
        // doesn't bleed over the labels.
        let tab_strip = 1u16;
        let border = 1u16;
        let header = 1u16;
        if editor_area.height < tab_strip + 2 * border + header + 2
            || editor_area.width < 2 * border + 4
        {
            self.disable_editor_image(side);
            return;
        }
        let cell_x = editor_area.x + border;
        let cell_y = editor_area.y + tab_strip + border + header;
        let cell_w = editor_area.width.saturating_sub(2 * border);
        let cell_h = editor_area
            .height
            .saturating_sub(tab_strip + 2 * border + header);
        let desired = EditorImageLayout {
            cell_x,
            cell_y,
            cell_w,
            cell_h,
            path,
            page: self
                .group_on_side(side)
                .and_then(|g| g.image.as_ref())
                .and_then(|i| i.pdf.as_ref())
                .map_or(1, |p| p.current_page),
            generation: self
                .group_on_side(side)
                .and_then(|g| g.image.as_ref())
                .map_or(0, |i| i.generation),
        };
        // The cell-buffer protocols (iTerm2 OSC-1337, Sixel) have no
        // z-layer, so the post-frame image blit would overpaint an open
        // context menu (Kitty puts the image at deep-negative z instead).
        // Hold the overlay cleared while a menu overlaps it; the layout
        // was invalidated, so the first frame after the menu closes or
        // moves off re-bakes the picture.
        if self.context_menu_covers_rect(Rect {
            x: cell_x,
            y: cell_y,
            width: cell_w,
            height: cell_h,
        }) {
            self.overlays.editor[side].request_clear_if_displayed();
            self.overlays.editor[side].invalidate_layout();
            return;
        }
        // Skip the bake when nothing about the layout changed - this is
        // the hot path on every frame an image is on screen.
        if self.overlays.editor[side].layout_matches(&desired) {
            return;
        }
        self.overlays.editor[side].request_clear_if_displayed();
        let canvas_w = cell_w as u32 * cw_px;
        let canvas_h = cell_h as u32 * ch_px;
        let bg = self.theme_bg_pixel();
        // The bytes come from the same `group_on_side` resolution the gate
        // and the layout key above used, so all three always describe one
        // group; the borrow ends at the last use inside the bake, before we
        // store into the slot.
        let baked = {
            let Some(image) = self.group_on_side(side).and_then(|g| g.image.as_ref()) else {
                return;
            };
            crate::iterm2_inline::fit_image_auto(&image.bytes, canvas_w, canvas_h, bg)
        };
        if let Ok(baked) = baked
            && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
                self.inline_protocol,
                &baked,
                cell_w,
                cell_h,
                false,
                crate::iterm2_inline::KITTY_ID_EDITOR_BASE + side as u32,
                // Below text and below non-default background cells, so a
                // right-click menu or any other opaque popup paints fully on
                // top. The preview still shows: on Kitty the editor widget
                // keeps its canvas at the DEFAULT bg (`image_canvas_bg`),
                // which this z stays above — an explicit canvas fill would
                // paint over the picture. Same placement the sidebar
                // illustrations use.
                crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
            )
        {
            let osc = crate::iterm2_inline::maybe_tmux_wrap(
                self.inline_protocol,
                crate::iterm2_inline::detect_tmux(),
                raw,
            );
            self.overlays.editor[side].set(osc, desired);
        }
    }

    fn disable_editor_image(&mut self, side: usize) {
        self.overlays.editor[side].disable();
    }

    /// Returns true if the cached editor-image cells need to be repainted
    /// by ratatui this frame (because the user closed/switched away from
    /// the image, or the layout changed). Called from the main loop to
    /// force a full redraw before re-emitting. ORs both split slots and
    /// consumes BOTH latches (never short-circuits).
    pub fn consume_editor_image_clear(&mut self) -> bool {
        let left = self.overlays.editor[0].consume_clear();
        let right = self.overlays.editor[1].consume_clear();
        left || right
    }

    pub fn editor_image_payload(&self, side: usize) -> Option<(&str, &EditorImageLayout)> {
        if self.shortcuts_modal.is_some()
            || self.file_finder.is_some()
            || self.command_palette.is_some()
            || self.go_to_symbol.is_some()
            || self.workspace_symbols.is_some()
            || self.process_picker.is_some()
            || self.zoxide_jump.is_some()
            || self.command_history_popup.is_some()
            || self.branch_picker.is_some()
            || self.input_prompt.is_some()
            || self.list_picker.is_some()
        {
            return None;
        }
        self.overlays.editor[side].payload()
    }

    pub fn mark_editor_image_displayed(&mut self, side: usize) {
        self.overlays.editor[side].mark_displayed();
    }

    /// Bake the active terminal pane's newest captured inline image (imgcat
    /// / OSC 1337) into an overlay anchored at its grid row. One slot: older
    /// images scroll away like text, and only the active pane shows its
    /// picture (focus a pane to see what it printed). alacritty never
    /// reserved grid rows for the image, so it floats above any text
    /// printed after it — the honest best without forking the engine.
    fn update_terminal_image_overlay(&mut self) {
        if !self.show_terminal
            || self.bottom_panel_tab != BottomPanelTab::Terminal
            || !self.inline_images_enabled()
        {
            self.disable_terminal_image();
            return;
        }
        let Some((cw_px, ch_px)) = self.cell_pixel else {
            return;
        };
        let idx = self.active_terminal;
        let Some(t) = self.terminals.get(idx) else {
            self.disable_terminal_image();
            return;
        };
        let inner = t.last_inner;
        // The floors below reject a pane the last frame did not paint ONLY
        // because the pane-skip site zeroes `last_inner` first (#510). They
        // are magnitude checks, not freshness checks: a pane painted at a
        // real size that then stops being painted keeps a full-size rect and
        // passes both. That was the bug. Delete the clear and these floors
        // will not catch it.
        if t.alt_screen() || inner.width < 6 || inner.height < 3 {
            self.disable_terminal_image();
            return;
        }
        let Some(img) = t.pane_images().pop() else {
            self.disable_terminal_image();
            return;
        };
        // Anchor row in the viewport; off-screen anchors hide the picture.
        let vp = img.line + t.scroll_display_offset();
        if vp < 0 || vp >= inner.height as i32 {
            self.disable_terminal_image();
            return;
        }
        // Image pixels → cells, shrunk (never grown) to fit the pane below
        // the anchor. Reading dimensions only decodes the header.
        let Ok(Some((px_w, px_h))) =
            image::ImageReader::new(std::io::Cursor::new(img.data.as_slice()))
                .with_guessed_format()
                .map(|r| r.into_dimensions().ok())
        else {
            self.disable_terminal_image();
            return;
        };
        let want_w = (px_w.div_ceil(cw_px)).max(1) as f32;
        let want_h = (px_h.div_ceil(ch_px)).max(1) as f32;
        let max_w = (inner.width - 2) as f32;
        let max_h = ((inner.height as i32 - vp).max(1) as f32).min(inner.height as f32 - 1.0);
        let scale = (max_w / want_w).min(max_h / want_h).min(1.0);
        let cell_w = ((want_w * scale) as u16).max(1);
        let cell_h = ((want_h * scale) as u16).max(1);
        let desired = TerminalImageLayout {
            cell_x: inner.x,
            cell_y: inner.y + vp as u16,
            cell_w,
            cell_h,
            seq: img.seq,
            pane: idx,
        };
        // An open right-click menu over the picture wins on the protocols
        // whose post-frame blit would erase the overlapped menu rows
        // (iTerm2/Sixel; Kitty solves this with the below-text z instead).
        // The editor preview applies the same rule.
        if self.context_menu_covers_rect(Rect {
            x: desired.cell_x,
            y: desired.cell_y,
            width: desired.cell_w,
            height: desired.cell_h,
        }) {
            self.overlays.terminal_image.request_clear_if_displayed();
            self.overlays.terminal_image.invalidate_layout();
            return;
        }
        // Hot path: unchanged layout means nothing to rebake and no latch.
        if self.overlays.terminal_image.layout_matches(&desired) {
            return;
        }
        // A pure anchor move (output scrolled, viewport scrolled) keeps the
        // baked payload: same picture, same cell size, same protocol — only
        // the placement row changed. Re-running the decode + resize +
        // encode of a full-resolution photo per scrolled row stalled the
        // render thread for the whole pane height.
        let reusable = self.overlays.terminal_image.has_image()
            && self.overlays.terminal_image.layout().is_some_and(|l| {
                l.seq == desired.seq
                    && l.pane == desired.pane
                    && l.cell_w == desired.cell_w
                    && l.cell_h == desired.cell_h
            });
        self.overlays.terminal_image.request_clear_if_displayed();
        if reusable {
            self.overlays.terminal_image.set_layout(desired);
            return;
        }
        let bg = self.theme_bg_pixel();
        let baked = crate::iterm2_inline::fit_image_auto(
            &img.data,
            cell_w as u32 * cw_px,
            cell_h as u32 * ch_px,
            bg,
        );
        if let Ok(baked) = baked
            && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
                self.inline_protocol,
                &baked,
                cell_w,
                cell_h,
                true,
                crate::iterm2_inline::KITTY_ID_TERMINAL,
                // Below text and non-default background cells: the pane's
                // default-bg cells are Color::Reset so the picture shows,
                // while an opaque popup (the right-click menu) paints fully
                // on top. Same placement the editor preview uses.
                crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
            )
        {
            let osc = crate::iterm2_inline::maybe_tmux_wrap(
                self.inline_protocol,
                crate::iterm2_inline::detect_tmux(),
                raw,
            );
            self.overlays.terminal_image.set(osc, desired);
        }
    }

    fn disable_terminal_image(&mut self) {
        self.overlays.terminal_image.disable();
    }

    fn disable_markdown_image(&mut self) {
        self.overlays.markdown_image.disable();
    }

    /// See [`Self::consume_editor_image_clear`]; the markdown twin.
    pub fn consume_markdown_image_clear(&mut self) -> bool {
        self.overlays.markdown_image.consume_clear()
    }

    pub fn mark_markdown_image_displayed(&mut self) {
        self.overlays.markdown_image.mark_displayed();
    }

    /// The markdown-preview image escape to flush this frame; same modal
    /// gate as the terminal pane picture.
    pub fn markdown_image_payload(&self) -> Option<(&str, &MarkdownImageLayout)> {
        if self.shortcuts_modal.is_some()
            || self.file_finder.is_some()
            || self.command_palette.is_some()
            || self.go_to_symbol.is_some()
            || self.workspace_symbols.is_some()
            || self.process_picker.is_some()
            || self.zoxide_jump.is_some()
            || self.command_history_popup.is_some()
            || self.branch_picker.is_some()
            || self.input_prompt.is_some()
            || self.list_picker.is_some()
        {
            return None;
        }
        self.overlays.markdown_image.payload()
    }

    /// Bake/refresh the markdown preview's inline image (#176): the
    /// TOPMOST reserved block whose anchor row is on screen paints; a
    /// bake is keyed on (path, mtime, fitted cells) and a pure scroll
    /// reuses the payload (the terminal-pane picture's contract).
    fn update_markdown_image_overlay(&mut self) {
        if !self.inline_images_enabled() {
            self.disable_markdown_image();
            return;
        }
        let Some((cw_px, ch_px)) = self.cell_pixel else {
            return;
        };
        let Some(md) = self.editor.markdown_preview.as_ref() else {
            self.disable_markdown_image();
            return;
        };
        let area = md.last_area;
        let viewport_rows = self.editor.last_inner.height;
        if area.width < 6 || viewport_rows < 3 || md.images.is_empty() {
            self.disable_markdown_image();
            return;
        }
        let scroll = md.scroll as usize;
        let Some((img, anchor_row)) = md
            .images
            .iter()
            .zip(md.anchor_rows.iter())
            .find(|&(_, &row)| row >= scroll && row - scroll < viewport_rows as usize)
            .map(|(i, &r)| (i.clone(), r))
        else {
            self.disable_markdown_image();
            return;
        };
        let Ok(meta) = std::fs::metadata(&img.path) else {
            self.disable_markdown_image();
            return;
        };
        let mtime_ms = meta
            .modified()
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_millis())
            .unwrap_or(0);
        let Ok((px_w, px_h)) = image::image_dimensions(&img.path) else {
            self.disable_markdown_image();
            return;
        };
        let vp = (anchor_row - scroll) as u16;
        let want_w = (px_w.div_ceil(cw_px)).max(1) as f32;
        let want_h = (px_h.div_ceil(ch_px)).max(1) as f32;
        let max_w = area.width.saturating_sub(2) as f32;
        let max_h = (img.rows.min(viewport_rows.saturating_sub(vp))).max(1) as f32;
        let scale = (max_w / want_w).min(max_h / want_h).min(1.0);
        let cell_w = ((want_w * scale) as u16).max(1);
        let cell_h = ((want_h * scale) as u16).max(1);
        let desired = MarkdownImageLayout {
            cell_x: area.x,
            cell_y: area.y + vp,
            cell_w,
            cell_h,
            path: img.path.clone(),
            mtime_ms,
        };
        if self.context_menu_covers_rect(Rect {
            x: desired.cell_x,
            y: desired.cell_y,
            width: desired.cell_w,
            height: desired.cell_h,
        }) {
            self.overlays.markdown_image.request_clear_if_displayed();
            self.overlays.markdown_image.invalidate_layout();
            return;
        }
        if self.overlays.markdown_image.layout_matches(&desired) {
            return;
        }
        let reusable = self.overlays.markdown_image.has_image()
            && self.overlays.markdown_image.layout().is_some_and(|l| {
                l.path == desired.path
                    && l.mtime_ms == desired.mtime_ms
                    && l.cell_w == desired.cell_w
                    && l.cell_h == desired.cell_h
            });
        self.overlays.markdown_image.request_clear_if_displayed();
        if reusable {
            self.overlays.markdown_image.set_layout(desired);
            return;
        }
        let Ok(bytes) = std::fs::read(&img.path) else {
            self.disable_markdown_image();
            return;
        };
        let bg = self.theme_bg_pixel();
        let baked = crate::iterm2_inline::fit_image_auto(
            &bytes,
            cell_w as u32 * cw_px,
            cell_h as u32 * ch_px,
            bg,
        );
        if let Ok(baked) = baked
            && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
                self.inline_protocol,
                &baked,
                cell_w,
                cell_h,
                true,
                crate::iterm2_inline::KITTY_ID_MARKDOWN,
                crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
            )
        {
            let osc = crate::iterm2_inline::maybe_tmux_wrap(
                self.inline_protocol,
                crate::iterm2_inline::detect_tmux(),
                raw,
            );
            self.overlays.markdown_image.set(osc, desired);
        }
    }

    /// See [`Self::consume_editor_image_clear`]; the terminal-image twin.
    pub fn consume_terminal_image_clear(&mut self) -> bool {
        self.overlays.terminal_image.consume_clear()
    }

    /// The pane image escape to flush this frame, gated off while any modal
    /// popup is up so the picture never paints over it.
    pub fn terminal_image_payload(&self) -> Option<(&str, &TerminalImageLayout)> {
        if self.shortcuts_modal.is_some()
            || self.file_finder.is_some()
            || self.command_palette.is_some()
            || self.go_to_symbol.is_some()
            || self.workspace_symbols.is_some()
            || self.process_picker.is_some()
            || self.zoxide_jump.is_some()
            || self.command_history_popup.is_some()
            || self.branch_picker.is_some()
            || self.input_prompt.is_some()
            || self.list_picker.is_some()
        {
            return None;
        }
        self.overlays.terminal_image.payload()
    }

    pub fn mark_terminal_image_displayed(&mut self) {
        self.overlays.terminal_image.mark_displayed();
    }

    /// Bake/recomposite the editor minimap for `strip` (the text-aligned image
    /// rect on the chosen edge). Mirrors `update_editor_image_overlay`: the
    /// expensive whole-file raster is cached in `minimap_base` and only rebuilt
    /// when its signature (content / size / theme) changes; scrolling reuses the
    /// raster and just recomposites the viewport box. The per-frame hot path
    /// early-returns at `layout_matches` before any allocation.
    fn update_minimap_overlay(&mut self, strip: Rect) {
        if !self.minimap_visible || !self.inline_images_enabled() {
            self.disable_minimap_image();
            return;
        }
        let Some((cw_px, ch_px)) = self.cell_pixel else {
            self.disable_minimap_image();
            return;
        };
        if strip.width == 0 || strip.height == 0 {
            self.disable_minimap_image();
            return;
        }
        // The raster is emitted at Kitty z=0 after ratatui's diff, so anything
        // ratatui paints over the strip gets painted back over every frame.
        // Only a menu that actually reaches the strip may evict it: arming the
        // clear latch for every right-click anywhere would wipe and repaint the
        // whole screen on the cell-buffer protocols. The layout is kept, so the
        // raster comes back without a rebake once the menu closes.
        self.minimap_img_rect = strip;
        if self.menu_covers(strip) {
            self.overlays.minimap.hide_and_request_clear();
            return;
        }
        let cell_w = strip.width;
        let cell_h = strip.height;
        let bg = self.theme.editor_bg_rgb();
        let top = self.editor.scroll;
        let rows = self.editor.visible_rows();
        let total = self.editor.lines.len();
        let edit_seq = self.editor.edit_seq;
        let selection = self.editor.selection_rows();
        let desired = MinimapLayout {
            cell_x: strip.x,
            cell_y: strip.y,
            cell_w,
            cell_h,
            top,
            rows,
            total,
            edit_seq,
            side: self.minimap_side,
            bg,
            selection,
        };
        if self.overlays.minimap.layout_matches(&desired) {
            return;
        }
        // Only a moved or resized strip needs the full-screen eviction (image
        // cells outside the new rect would ghost). A content-only change
        // (edit, scroll, selection, theme) re-emits over the SAME cells - the
        // fixed Kitty id / same-cell OSC-1337 emit replaces the image in
        // place - so it must NOT arm the clear: that `2J` + full redraw is a
        // whole-app blink on every keystroke over an SSH round trip.
        let placement_moved = self.overlays.minimap.layout().is_none_or(|prev| {
            (prev.cell_x, prev.cell_y, prev.cell_w, prev.cell_h)
                != (
                    desired.cell_x,
                    desired.cell_y,
                    desired.cell_w,
                    desired.cell_h,
                )
        });
        if placement_moved {
            self.overlays.minimap.request_clear_if_displayed();
        }
        // Cold path only: clone the path into the rebake signature.
        let canvas_w = cell_w as u32 * cw_px;
        let canvas_h = cell_h as u32 * ch_px;
        // Cap each line's height so a short file stays a compact sliver at the
        // top rather than stretching down the whole strip; a file long enough
        // to fill the strip naturally reaches `canvas_h` and is unaffected.
        let content_h = (total as u32 * MINIMAP_MAX_LINE_PX).min(canvas_h).max(1);
        self.minimap_content_h = content_h;
        // Luminance picks the default text color and the viewport tint so the
        // box reads on either theme.
        let light = 0.299 * bg.0 as f32 + 0.587 * bg.1 as f32 + 0.114 * bg.2 as f32 > 140.0;
        let sig = (self.editor.path.clone(), edit_seq, canvas_w, canvas_h, bg);
        if self.minimap_base.as_ref().map(|b| &b.sig) != Some(&sig) {
            let fg = if light {
                (0x38, 0x3a, 0x41)
            } else {
                (0xc5, 0xcd, 0xd9)
            };
            let rgba = self
                .editor
                .minimap_rgba(canvas_w, canvas_h, content_h, bg, fg);
            self.minimap_base = Some(MinimapBase {
                rgba,
                w: canvas_w,
                h: canvas_h,
                sig,
            });
        }
        let Some(base) = self.minimap_base.as_ref() else {
            return;
        };
        let composited = composite_minimap_viewport(
            &base.rgba,
            base.w,
            base.h,
            MinimapOverlay {
                top,
                rows,
                total,
                light,
                selection,
                sel_rgb: self.theme.selection_rgb(),
                content_h,
            },
        );
        let (bw, bh) = (base.w, base.h);
        let Some(png) = rgba_to_png(composited, bw, bh) else {
            return;
        };
        if let Some(raw) = crate::iterm2_inline::build_inline_image(
            self.inline_protocol,
            &png,
            cell_w,
            cell_h,
            false,
            crate::iterm2_inline::KITTY_ID_MINIMAP,
        ) {
            let osc = crate::iterm2_inline::maybe_tmux_wrap(
                self.inline_protocol,
                crate::iterm2_inline::detect_tmux(),
                raw,
            );
            self.overlays.minimap.set(osc, desired);
        }
    }

    fn disable_minimap_image(&mut self) {
        self.overlays.minimap.disable();
        self.minimap_img_rect = Rect::default();
    }

    /// Show/hide the editor minimap (⌥⌘M, the minimap right-click menu, the
    /// Customize Layout menu, and the "View: Toggle Minimap" palette command
    /// all route here). Hiding evicts the cached strip image so it can't ghost.
    fn toggle_minimap(&mut self) {
        self.minimap_visible = !self.minimap_visible;
        if !self.minimap_visible {
            self.disable_minimap_image();
        }
        self.status = if self.minimap_visible {
            String::from("Minimap on")
        } else {
            String::from("Minimap off")
        };
    }

    /// Carve the minimap strip off `editor_area` when the minimap is on (v1:
    /// unsplit, image-capable terminals, enough width). Returns
    /// `(editor_rect, full_strip, image_rect)`: the editor renders into
    /// `editor_rect`, the whole `full_strip` column is bg-filled, and the
    /// raster image occupies `image_rect` (aligned to the editor's text rows).
    fn carve_minimap(&self, editor_area: Rect) -> Option<(Rect, Rect, Rect)> {
        if !self.minimap_visible
            || self.editor_layout.is_split()
            || !self.inline_images_enabled()
            || self.cell_pixel.is_none()
            || editor_area.width < MINIMAP_WIDTH_CELLS + MINIMAP_MIN_EDITOR_WIDTH
        {
            return None;
        }
        let w = MINIMAP_WIDTH_CELLS;
        let (ed_x, strip_x) = match self.minimap_side {
            MinimapSide::Right => (editor_area.x, editor_area.x + editor_area.width - w),
            MinimapSide::Left => (editor_area.x + w, editor_area.x),
        };
        let ed_rect = Rect {
            x: ed_x,
            y: editor_area.y,
            width: editor_area.width - w,
            height: editor_area.height,
        };
        let full_strip = Rect {
            x: strip_x,
            y: editor_area.y,
            width: w,
            height: editor_area.height,
        };
        // Align the image to the editor's text rows (tab strip + border +
        // header above, border below) so it tracks the text vertically.
        let (tab, border, header) = (1u16, 1u16, 1u16);
        let img = if editor_area.height > tab + 2 * border + header {
            Rect {
                x: strip_x,
                y: editor_area.y + tab + border + header,
                width: w,
                height: editor_area.height - (tab + 2 * border + header),
            }
        } else {
            full_strip
        };
        Some((ed_rect, full_strip, img))
    }

    /// Whether the open context menu (or its submenu, which floats further
    /// out) overlaps `r`. Menus are clamped to the frame, not snapped to it, so
    /// a right-click far from the minimap leaves the strip untouched.
    fn menu_covers(&self, r: Rect) -> bool {
        if r.width == 0 || r.height == 0 {
            return false;
        }
        [self.menu_rect(), self.submenu_rect()]
            .into_iter()
            .flatten()
            .any(|m| m.intersects(r))
    }

    pub fn minimap_image_payload(&self) -> Option<(&str, &MinimapLayout)> {
        if self.shortcuts_modal.is_some()
            || self.file_finder.is_some()
            || self.command_palette.is_some()
            || self.go_to_symbol.is_some()
            || self.workspace_symbols.is_some()
            || self.process_picker.is_some()
            || self.zoxide_jump.is_some()
            || self.command_history_popup.is_some()
            || self.branch_picker.is_some()
            || self.input_prompt.is_some()
            || self.list_picker.is_some()
            || self.menu_covers(self.minimap_img_rect)
        {
            return None;
        }
        self.overlays.minimap.payload()
    }

    pub fn consume_minimap_image_clear(&mut self) -> bool {
        self.overlays.minimap.consume_clear()
    }

    pub fn mark_minimap_image_displayed(&mut self) {
        self.overlays.minimap.mark_displayed();
    }

    /// Map a click row inside the minimap strip to a document line and jump
    /// there, centered. The vertical mapping uses the raster's `content_h`
    /// (the lines occupy only the top `content_h` px for a short file), so a
    /// click lands on the line actually under the cursor.
    fn minimap_scroll_to_row(&mut self, row: u16) {
        let r = self.minimap_img_rect;
        let total = self.editor.lines.len();
        if r.height == 0 || total == 0 {
            return;
        }
        let ch_px = self.cell_pixel.map(|(_, h)| h).unwrap_or(1).max(1);
        let dy_px = (row.saturating_sub(r.y)) as u32 * ch_px;
        let content_h = self.minimap_content_h.max(1);
        let line = (dy_px as usize * total / content_h as usize).min(total - 1);
        self.editor.goto_line_centered(line);
        self.poke_cursor();
    }

    /// Right-click on the minimap strip: a compact menu mirroring VS Code's
    /// (Minimap toggle + Side submenu).
    /// Build a status-bar popup menu at `(col, row)`. `menu_rect` clamps it up
    /// to fit, so opening at the bottom status row renders above the bar.
    fn open_status_menu(&mut self, col: u16, row: u16, items: Vec<MenuEntry>) {
        self.context_menu = Some(ContextMenu {
            origin: (col, row),
            items,
            selected: 0,
            open_submenu: None,
            submenu_selected: 0,
            target_dir: self.tree.root.clone(),
        });
    }

    /// Status-bar "Change Language Mode" picker. Editor-level only: it re-runs
    /// tree-sitter highlighting / indentation / comment rules under the chosen
    /// grammar. The LSP stays routed by file extension.
    fn open_status_language_menu(&mut self, col: u16, row: u16) {
        let check = |on: bool| if on { "\u{2713} " } else { "  " };
        let current = self.editor.language();
        let mut items = vec![MenuEntry::Item {
            label: format!("{}Plain Text", check(current.is_none())),
            action: MenuAction::SetLanguage(None),
        }];
        for &lang in crate::widgets::editor::SELECTABLE_LANGUAGES {
            items.push(MenuEntry::Item {
                label: format!(
                    "{}{}",
                    check(current == Some(lang)),
                    crate::widgets::editor::language_label(Some(lang))
                ),
                action: MenuAction::SetLanguage(Some(lang)),
            });
        }
        self.open_status_menu(col, row, items);
    }

    /// Status-bar EOL picker (LF / CRLF). Converts on the next save.
    fn open_status_eol_menu(&mut self, col: u16, row: u16) {
        use crate::widgets::editor::LineEnding;
        let check = |on: bool| if on { "\u{2713} " } else { "  " };
        let cur = self.editor.eol;
        let items = vec![
            MenuEntry::Item {
                label: format!("{}LF", check(cur == LineEnding::Lf)),
                action: MenuAction::SetLineEnding(LineEnding::Lf),
            },
            MenuEntry::Item {
                label: format!("{}CRLF", check(cur == LineEnding::Crlf)),
                action: MenuAction::SetLineEnding(LineEnding::Crlf),
            },
        ];
        self.open_status_menu(col, row, items);
    }

    /// Status-bar "Reopen with Encoding" picker over a common set; selecting one
    /// re-decodes the file (and re-encodes it on the next save).
    fn open_status_encoding_menu(&mut self, col: u16, row: u16) {
        use encoding_rs::{
            BIG5, EUC_JP, EUC_KR, GBK, KOI8_R, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251,
            WINDOWS_1252,
        };
        let check = |on: bool| if on { "\u{2713} " } else { "  " };
        let cur = self.editor.encoding;
        let encs: [&'static encoding_rs::Encoding; 11] = [
            UTF_8,
            UTF_16LE,
            UTF_16BE,
            WINDOWS_1252,
            WINDOWS_1251,
            SHIFT_JIS,
            EUC_JP,
            GBK,
            BIG5,
            EUC_KR,
            KOI8_R,
        ];
        let items = encs
            .iter()
            .map(|&enc| MenuEntry::Item {
                label: format!("{}{}", check(std::ptr::eq(enc, cur)), enc.name()),
                action: MenuAction::SetEncoding(enc),
            })
            .collect();
        self.open_status_menu(col, row, items);
    }

    /// Status-bar indentation picker, mirroring VS Code's "Select Indentation"
    /// quick pick: switch spaces-vs-tabs for future typing, change the width,
    /// and convert the buffer's existing indentation.
    fn open_status_indent_menu(&mut self, col: u16, row: u16) {
        use crate::widgets::editor::IndentStyle;
        let check = |on: bool| if on { "\u{2713} " } else { "  " };
        let cur = self.editor.indent_style();
        let mut items = vec![
            MenuEntry::Item {
                label: format!("{}Indent Using Spaces", check(cur.use_spaces)),
                action: MenuAction::SetIndentStyle(IndentStyle {
                    width: cur.width,
                    use_spaces: true,
                }),
            },
            MenuEntry::Item {
                label: format!("{}Indent Using Tabs", check(!cur.use_spaces)),
                action: MenuAction::SetIndentStyle(IndentStyle {
                    width: cur.width,
                    use_spaces: false,
                }),
            },
            MenuEntry::Separator,
        ];
        for width in [2u32, 4, 8] {
            items.push(MenuEntry::Item {
                label: format!("{}Tab Size: {width}", check(cur.width == width)),
                action: MenuAction::SetIndentStyle(IndentStyle {
                    width,
                    use_spaces: cur.use_spaces,
                }),
            });
        }
        items.push(MenuEntry::Separator);
        items.push(MenuEntry::Item {
            label: String::from("  Convert Indentation to Spaces"),
            action: MenuAction::ConvertIndentation(true),
        });
        items.push(MenuEntry::Item {
            label: String::from("  Convert Indentation to Tabs"),
            action: MenuAction::ConvertIndentation(false),
        });
        self.open_status_menu(col, row, items);
    }

    fn open_minimap_menu(&mut self, col: u16, row: u16) {
        let check = |on: bool| if on { "\u{2713} " } else { "  " };
        let items = vec![
            MenuEntry::Item {
                label: format!("{}Minimap", check(self.minimap_visible)),
                action: MenuAction::ToggleMinimap,
            },
            MenuEntry::Submenu {
                label: String::from("Side"),
                items: vec![
                    MenuEntry::Item {
                        label: format!("{}Left", check(self.minimap_side == MinimapSide::Left)),
                        action: MenuAction::SetMinimapSide(MinimapSide::Left),
                    },
                    MenuEntry::Item {
                        label: format!("{}Right", check(self.minimap_side == MinimapSide::Right)),
                        action: MenuAction::SetMinimapSide(MinimapSide::Right),
                    },
                ],
            },
        ];
        self.context_menu = Some(ContextMenu {
            origin: (col, row),
            items,
            selected: 0,
            open_submenu: None,
            submenu_selected: 0,
            target_dir: self.tree.root.clone(),
        });
    }

    pub fn welcome_image_emit_payload(&self) -> Option<(&str, &WelcomeLayout)> {
        if self.shortcuts_modal.is_some()
            || self.file_finder.is_some()
            || self.command_palette.is_some()
            || self.go_to_symbol.is_some()
            || self.workspace_symbols.is_some()
            || self.process_picker.is_some()
            || self.zoxide_jump.is_some()
            || self.command_history_popup.is_some()
            || self.branch_picker.is_some()
            || self.input_prompt.is_some()
            || self.list_picker.is_some()
            || self.context_menu.is_some()
            || self.connect_dialog.is_some()
            || !self.editor.is_blank_initial()
            || self.terminal_maximized
        {
            return None;
        }
        self.overlays.welcome.emit_payload()
    }

    pub fn mark_welcome_image_emitted(&mut self) {
        self.overlays.welcome.mark_emitted();
    }

    /// Keyboard navigation for spreadsheet preview tabs. All gestures are
    /// scroll-only: arrows pan one row/column, PageUp/PageDown jump by a
    /// full viewport, Home/End jump to the first/last row, Tab/Shift+Tab
    /// switch worksheets. Anything else is swallowed so a stray keystroke
    /// can't insert characters into a buffer the user can't see.
    /// Scroll the active diff to the next change hunk (forward=true) or
    /// the previous one (forward=false), wrapping around the ends so a
    /// user can keep clicking the same arrow to cycle through every
    /// hunk. Mirrors the F7 / Shift+F7 key path so click and keybinding
    /// stay in sync.
    fn jump_diff_change(&mut self, forward: bool) {
        let Some(diff) = self.editor.diff.as_mut() else {
            return;
        };
        if forward {
            diff.jump_next_change();
        } else {
            diff.jump_prev_change();
        }
    }

    /// Open the working-tree file the diff caret sits on at its line, the
    /// Enter action in the diff view. Resolves the row to a (file, line)
    /// via `DiffData::jump_target`, then reuses the explorer's pinned-tab
    /// open so the diff tab is left intact beside the opened file.
    fn jump_to_diff_file_under_caret(&mut self) {
        let target = {
            let Some(diff) = self.editor.diff.as_ref() else {
                return;
            };
            // A git-produced diff carries toplevel-relative `+++ b/` paths
            // (#139); croft's own snapshot diffs stay workspace-anchored.
            let root = if diff.left_is_git_head {
                self.scm_root()
            } else {
                self.tree.root.clone()
            };
            let row = diff.caret_row().unwrap_or(diff.scroll);
            diff.jump_target(row, &root)
        };
        let Some(j) = target else {
            return;
        };
        match self.editor.open_pinned(&j.path) {
            Ok(()) => {
                self.editor.goto_line(j.line);
                self.focus_pane(Pane::Editor);
                self.sync_open_file_poll_mtime();
                self.poke_cursor();
                self.status = format!("{}:{}", self.status_path(&j.path), j.line);
            }
            Err(err) => {
                self.status = format!("Could not open {}: {err}", j.path.display());
            }
        }
    }

    fn handle_diff_key(&mut self, key: KeyEvent) {
        // Cmd+C / Ctrl+Shift+C on a diff selection: copy the dragged
        // substring of whichever column the selection is anchored on.
        // Must run BEFORE the scroll match below so the keystroke isn't
        // dropped as "no scroll mapping". The general editor key handler
        // short-circuits to this function when a diff is open, so without
        // this branch Cmd+C in a diff view literally never copies.
        if is_editor_copy_key(key) {
            self.copy_editor_selection();
            return;
        }
        // Enter opens the file under the caret at the matching line. The
        // caret is the selection head a click leaves behind; with no
        // selection yet we fall back to the top visible row.
        if matches!(key.code, KeyCode::Enter) {
            self.jump_to_diff_file_under_caret();
            return;
        }
        // Hunk actions on the change under the caret (VS Code's Stage /
        // Unstage / Discard Selected Ranges, one keystroke each since the
        // diff pane owns no text input). R is destructive and routes
        // through the confirm popup.
        if let KeyCode::Char(c) = key.code
            && (key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT)
        {
            match c.to_ascii_lowercase() {
                's' => {
                    self.stage_hunk_at_caret();
                    return;
                }
                'u' => {
                    self.unstage_hunk_at_caret();
                    return;
                }
                'r' => {
                    self.request_revert_hunk_at_caret();
                    return;
                }
                _ => {}
            }
        }
        // Page = inner viewport rows minus the header + footer the diff
        // renderer reserves. Falls back to a sane default when the editor
        // hasn't laid out yet.
        let page = (self.editor.last_inner.height as usize)
            .saturating_sub(2)
            .max(1);
        let Some(diff) = self.editor.diff.as_mut() else {
            return;
        };
        // F7 / Shift+F7: jump to next / previous change hunk. Matches the
        // VS Code keybinding for "Next/Previous Change in Diff Editor" so
        // users can scan a long diff without scrolling line-by-line.
        if matches!(key.code, KeyCode::F(7)) {
            // Shared backend with the click arrows: the jump anchors on the
            // hunk the previous jump landed on (tracked in `nav_anchor`),
            // not on `scroll` — `render_diff` clamps `scroll` at the bottom,
            // which used to pin the forward arrow on the last hunk. Both
            // directions wrap so F7 at the last hunk loops to the first.
            if key.modifiers.contains(KeyModifiers::SHIFT) {
                diff.jump_prev_change();
            } else {
                diff.jump_next_change();
            }
            return;
        }
        match key.code {
            KeyCode::Up => diff.scroll_up_by(1),
            KeyCode::Down => diff.scroll_down_by(1),
            KeyCode::PageUp => diff.scroll_up_by(page),
            KeyCode::PageDown => diff.scroll_down_by(page),
            KeyCode::Home => diff.scroll_home(),
            KeyCode::End => diff.scroll_end(),
            KeyCode::Left => diff.scroll_left_by(4),
            KeyCode::Right => diff.scroll_right_by(4),
            _ => {}
        }
    }

    fn handle_sheet_key(&mut self, key: KeyEvent) {
        let visible = sheet_visible_rows(self.editor.last_inner);
        let Some(sheet) = self.editor.sheet.as_mut() else {
            return;
        };
        // Cell editing covers CSV/TSV and (via the umya write path,
        // #178) xlsx; the legacy binary kinds stay read-only.
        let editable = matches!(
            sheet.kind,
            crate::sheet::SheetKind::Csv
                | crate::sheet::SheetKind::Tsv
                | crate::sheet::SheetKind::Xlsx
        );
        let total_sheets = sheet.sheets.len();
        let current = sheet.current_sheet;
        let plain = !key.modifiers.contains(KeyModifiers::CONTROL)
            && !key.modifiers.contains(KeyModifiers::SUPER)
            && !key.modifiers.contains(KeyModifiers::ALT);
        // In-grid cell editor (#177): it owns every key while open.
        if sheet.editing.is_some() {
            let (commit, next) = {
                let edit = sheet.editing.as_mut().expect("checked");
                match key.code {
                    KeyCode::Esc => {
                        sheet.editing = None;
                        return;
                    }
                    KeyCode::Enter => (true, (1i64, 0i64)),
                    KeyCode::Tab => (true, (0, 1)),
                    KeyCode::BackTab => (true, (0, -1)),
                    KeyCode::Backspace => {
                        if edit.cursor > 0 {
                            let i = floor_char(&edit.value, edit.cursor - 1);
                            edit.value.remove(i);
                            edit.cursor = i;
                        }
                        (false, (0, 0))
                    }
                    KeyCode::Delete => {
                        if edit.cursor < edit.value.len() {
                            edit.value.remove(edit.cursor);
                        }
                        (false, (0, 0))
                    }
                    KeyCode::Left => {
                        if edit.cursor > 0 {
                            edit.cursor = floor_char(&edit.value, edit.cursor - 1);
                        }
                        (false, (0, 0))
                    }
                    KeyCode::Right => {
                        if edit.cursor < edit.value.len() {
                            edit.cursor = ceil_char(&edit.value, edit.cursor + 1);
                        }
                        (false, (0, 0))
                    }
                    KeyCode::Home => {
                        edit.cursor = 0;
                        (false, (0, 0))
                    }
                    KeyCode::End => {
                        edit.cursor = edit.value.len();
                        (false, (0, 0))
                    }
                    KeyCode::Char(c) if plain => {
                        edit.value.insert(edit.cursor, c);
                        edit.cursor += c.len_utf8();
                        (false, (0, 0))
                    }
                    _ => (false, (0, 0)),
                }
            };
            if commit {
                if !editable {
                    // Belt-and-braces (#201 review): editing should never
                    // start on a read-only kind, but a commit must not
                    // mutate one either.
                    sheet.editing = None;
                    self.status = String::from("This view is read-only");
                    return;
                }
                let edit = sheet.editing.take().expect("checked");
                let (r, c) = {
                    let data = &mut sheet.sheets[current];
                    data.set_cell(data.cur_row, data.cur_col, edit.value);
                    (data.cur_row, data.cur_col)
                };
                if !sheet.cell_edits.contains(&(current, r, c)) {
                    sheet.cell_edits.push((current, r, c));
                }
                sheet.dirty = true;
                self.editor.dirty = true;
                let data = &mut self.editor.sheet.as_mut().expect("checked").sheets[current];
                data.cur_row = r
                    .saturating_add_signed(next.0 as isize)
                    .min(data.row_count().saturating_sub(1));
                data.cur_col = c
                    .saturating_add_signed(next.1 as isize)
                    .min(data.col_count().saturating_sub(1));
                sheet_follow_cursor(
                    self.editor.sheet.as_mut().expect("checked"),
                    current,
                    visible,
                );
            }
            return;
        }
        let data = match sheet.sheets.get_mut(current) {
            Some(d) => d,
            None => return,
        };
        let row_count = data.rows.len();
        let col_count = data.col_widths.len();
        match key.code {
            KeyCode::Down => {
                data.cur_row = (data.cur_row + 1).min(row_count.saturating_sub(1));
            }
            KeyCode::Up => data.cur_row = data.cur_row.saturating_sub(1),
            KeyCode::Right => {
                data.cur_col = (data.cur_col + 1).min(col_count.saturating_sub(1));
            }
            KeyCode::Left => data.cur_col = data.cur_col.saturating_sub(1),
            KeyCode::PageDown => {
                // SQLite (#201 review): at the bottom of the loaded
                // batch, fetch the NEXT page instead of stopping.
                if sheet.kind == crate::sheet::SheetKind::Sqlite
                    && data.cur_row + visible.max(1) >= row_count
                {
                    self.sqlite_page_step(1);
                    return;
                }
                data.cur_row = (data.cur_row + visible).min(row_count.saturating_sub(1));
            }
            KeyCode::PageUp => {
                if sheet.kind == crate::sheet::SheetKind::Sqlite
                    && data.cur_row == 0
                    && data.scroll_row == 0
                {
                    self.sqlite_page_step(-1);
                    return;
                }
                data.cur_row = data.cur_row.saturating_sub(visible);
            }
            KeyCode::Home => {
                data.cur_col = 0;
                if key.modifiers.contains(KeyModifiers::CONTROL)
                    || key.modifiers.contains(KeyModifiers::SUPER)
                {
                    data.cur_row = 0;
                }
            }
            KeyCode::End => {
                data.cur_col = col_count.saturating_sub(1);
                if key.modifiers.contains(KeyModifiers::CONTROL)
                    || key.modifiers.contains(KeyModifiers::SUPER)
                {
                    data.cur_row = row_count.saturating_sub(1);
                }
            }
            KeyCode::Enter | KeyCode::F(2) => {
                if editable {
                    if row_count > 0 {
                        let value = data.cell(data.cur_row, data.cur_col).to_string();
                        let cursor = value.len();
                        sheet.editing = Some(crate::sheet::CellEdit { value, cursor });
                    }
                } else {
                    self.status = String::from("This workbook format is read-only (xls/ods/xlsb)");
                }
                return;
            }
            KeyCode::Delete if !editable => {
                self.status = String::from("This view is read-only");
                return;
            }
            KeyCode::Delete if editable && row_count > 0 => {
                let (r, c) = (data.cur_row, data.cur_col);
                data.set_cell(r, c, String::new());
                if !sheet.cell_edits.contains(&(current, r, c)) {
                    sheet.cell_edits.push((current, r, c));
                }
                sheet.dirty = true;
                self.editor.dirty = true;
                return;
            }
            KeyCode::Tab if total_sheets > 1 => {
                sheet.current_sheet = (current + 1) % total_sheets;
                return;
            }
            KeyCode::BackTab if total_sheets > 1 => {
                sheet.current_sheet = (current + total_sheets - 1) % total_sheets;
                return;
            }
            KeyCode::Char(c) if plain && (' '..='~').contains(&c) => {
                if editable {
                    if row_count > 0 {
                        // Spreadsheet convention: typing REPLACES the cell.
                        sheet.editing = Some(crate::sheet::CellEdit {
                            value: String::from(c),
                            cursor: c.len_utf8(),
                        });
                    }
                } else {
                    self.status = String::from("This workbook format is read-only (xls/ods/xlsb)");
                }
                return;
            }
            _ => return,
        }
        sheet_follow_cursor(sheet, current, visible);
    }

    /// Archive browser keys (#179): selection movement, Enter extracts
    /// the member to scratch and opens it through the normal dispatch,
    /// E prompts for an extraction folder.
    fn handle_archive_key(&mut self, key: KeyEvent) {
        let Some(view) = self.editor.archive.as_mut() else {
            return;
        };
        let rows = (view.rows_visible as usize).max(1);
        let last = view.entries.len().saturating_sub(1);
        match key.code {
            KeyCode::Down => view.selected = (view.selected + 1).min(last),
            KeyCode::Up => view.selected = view.selected.saturating_sub(1),
            KeyCode::PageDown => view.selected = (view.selected + rows).min(last),
            KeyCode::PageUp => view.selected = view.selected.saturating_sub(rows),
            KeyCode::Home => view.selected = 0,
            KeyCode::End => view.selected = last,
            KeyCode::Enter => self.open_selected_archive_member(),
            KeyCode::Char('e') | KeyCode::Char('E') => self.open_archive_extract_prompt(),
            _ => {}
        }
    }

    /// Extract the selected member into the session scratch dir and open
    /// the extracted FILE through the standard dispatch, so text, images,
    /// PDFs, sheets, and binaries all render with their real viewers.
    fn open_selected_archive_member(&mut self) {
        let Some((path, kind, member, dir)) = self.editor.archive.as_ref().and_then(|v| {
            let e = v.entries.get(v.selected)?;
            Some((self.editor.path.clone()?, v.kind, e.path.clone(), e.dir))
        }) else {
            return;
        };
        if dir {
            self.status = String::from("Directories only group members; open a file");
            return;
        }
        // Session-unique (#198 review): a shared path let another croft
        // instance overwrite a member between extraction and open.
        let dest = std::env::temp_dir().join(format!("croft-archive-{}", std::process::id()));
        match crate::archive::extract_member(&path, kind, &member, &dest) {
            Ok(extracted) => {
                if let Err(e) = self.open_at(&extracted, 0, 0) {
                    self.status = format!("Member open failed: {e}");
                } else {
                    self.status = format!("Opened {member} (extracted copy)");
                }
            }
            Err(e) => self.status = format!("Member open failed: {e}"),
        }
    }

    fn open_archive_extract_prompt(&mut self) {
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        let Some((member, dir)) = self
            .editor
            .archive
            .as_ref()
            .and_then(|v| v.entries.get(v.selected))
            .map(|e| (e.path.clone(), e.dir))
        else {
            return;
        };
        if dir {
            // extract_member extracts ONE member, not a subtree (#198
            // review): the prompt would fail or write an empty folder.
            self.status = String::from("Directories only group members; extract a file");
            return;
        }
        let suggestion = self.workspace_root().display().to_string();
        self.open_input_prompt(
            InputPrompt::new(
                InputPurpose::ArchiveExtract { member },
                String::from("Extract Member To"),
                "destination folder",
            )
            .with_value(&suggestion),
        );
    }

    /// Hex-tab navigation (#172): cursor movement over bytes, Shift
    /// extending the selection, F3 repeating the last find. The viewport
    /// row count comes from the last painted frame's layout (frame
    /// truth), so PageUp/PageDown match what the user sees.
    fn handle_hex_key(&mut self, key: KeyEvent) {
        // Cmd/Ctrl+F never reaches here — `is_editor_find_key` routes to
        // `open_editor_find` earlier in the dispatch, which forwards hex
        // tabs to the byte-query popup.
        let Some(view) = self.editor.hex.as_mut() else {
            return;
        };
        let rows = (view.layout.data_rows as usize).max(1);
        let bpr = view.bytes_per_row as i64;
        let select = key.modifiers.contains(KeyModifiers::SHIFT);
        let jump = key.modifiers.contains(KeyModifiers::CONTROL)
            || key.modifiers.contains(KeyModifiers::SUPER);
        // Editing (#173): undo/redo chords, then plain typing. The
        // chord check comes first so Cmd+Z is never read as the letter.
        if jump && matches!(key.code, KeyCode::Char('z') | KeyCode::Char('Z')) {
            let did = if select {
                view.redo_edit()
            } else {
                view.undo_edit()
            };
            if did {
                self.editor.dirty = self.editor.hex.as_ref().is_some_and(|v| v.has_edits());
            } else {
                self.status = String::from(if select {
                    "Nothing to redo"
                } else {
                    "Nothing to undo"
                });
            }
            return;
        }
        if let KeyCode::Char(c) = key.code
            && !jump
            && !key.modifiers.contains(KeyModifiers::ALT)
        {
            if view.read_only {
                self.status = String::from("Read-only file: no write permission");
                return;
            }
            let mut wrote = false;
            if view.ascii_focus {
                if (' '..='~').contains(&c) {
                    let off = view.cursor;
                    view.apply_edit(off, c as u8);
                    view.move_cursor(1, false, rows);
                    wrote = true;
                }
            } else if let Some(d) = c.to_digit(16) {
                if view.type_hex_digit(d as u8) {
                    view.move_cursor(1, false, rows);
                }
                wrote = true;
            }
            if wrote {
                self.editor.dirty = self.editor.hex.as_ref().is_some_and(|v| v.has_edits());
                return;
            }
            // Not a typable char for this pane: fall through to the
            // navigation matches below (F3 etc. are KeyCode variants,
            // never Char, so nothing else claims chars).
            return;
        }
        match key.code {
            KeyCode::Tab => {
                view.ascii_focus = !view.ascii_focus;
                view.pending_nibble = None;
                return;
            }
            KeyCode::Backspace => {
                view.pending_nibble = None;
                view.move_cursor(-1, false, rows);
                return;
            }
            KeyCode::Delete => {
                let off = view.cursor;
                view.revert_edit(off);
                self.editor.dirty = self.editor.hex.as_ref().is_some_and(|v| v.has_edits());
                return;
            }
            _ => {}
        }
        let Some(view) = self.editor.hex.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Left => view.move_cursor(-1, select, rows),
            KeyCode::Right => view.move_cursor(1, select, rows),
            KeyCode::Up => view.move_cursor(-bpr, select, rows),
            KeyCode::Down => view.move_cursor(bpr, select, rows),
            KeyCode::PageUp => view.move_cursor(-bpr * rows as i64, select, rows),
            KeyCode::PageDown => view.move_cursor(bpr * rows as i64, select, rows),
            KeyCode::Home if jump => view.set_cursor(0, select, rows),
            KeyCode::End if jump => view.set_cursor(u64::MAX, select, rows),
            KeyCode::Home => {
                let row_start = view.cursor - view.cursor % view.bytes_per_row;
                view.set_cursor(row_start, select, rows);
            }
            KeyCode::End => {
                let row_end =
                    view.cursor - view.cursor % view.bytes_per_row + (view.bytes_per_row - 1);
                view.set_cursor(row_end, select, rows);
            }
            KeyCode::Esc => {
                view.sel_anchor = None;
                view.pending_nibble = None;
            }
            KeyCode::F(3) => self.hex_find_next(),
            _ => {}
        }
    }

    /// Sheet row/column structure ops (#177), palette-driven, anchored
    /// on the selected cell. CSV/TSV only; the workbook kinds are still
    /// read-only (#178).
    fn sheet_structure_op(&mut self, cmd: crate::widgets::command_palette::Command) {
        use crate::widgets::command_palette::Command as Cmd;
        let Some(view) = self.editor.sheet.as_mut() else {
            self.status = String::from("The active tab is not a spreadsheet");
            return;
        };
        if !matches!(
            view.kind,
            crate::sheet::SheetKind::Csv | crate::sheet::SheetKind::Tsv
        ) {
            self.status = String::from(
                "Row/column structure edits are CSV/TSV only; xlsx supports cell edits",
            );
            return;
        }
        view.editing = None;
        let current = view.current_sheet;
        let Some(data) = view.sheets.get_mut(current) else {
            return;
        };
        let (r, c) = (data.cur_row, data.cur_col);
        let changed = match cmd {
            Cmd::SheetInsertRowBelow => {
                let at = if data.row_count() == 0 { 0 } else { r + 1 };
                data.insert_row(at);
                data.cur_row = at;
                true
            }
            Cmd::SheetDeleteRow => {
                let did = data.delete_row(r);
                data.cur_row = r.min(data.row_count().saturating_sub(1));
                did
            }
            Cmd::SheetInsertColRight => {
                let at = if data.col_count() == 0 { 0 } else { c + 1 };
                data.insert_col(at);
                data.cur_col = at;
                true
            }
            Cmd::SheetDeleteCol => {
                let did = data.delete_col(c);
                data.cur_col = c.min(data.col_count().saturating_sub(1));
                did
            }
            _ => false,
        };
        if changed {
            view.dirty = true;
            let visible = sheet_visible_rows(self.editor.last_inner);
            if let Some(view) = self.editor.sheet.as_mut() {
                sheet_follow_cursor(view, current, visible);
            }
            self.editor.dirty = true;
        } else {
            self.status = String::from("Nothing to remove there");
        }
    }

    /// Step the active SQLite table to an adjacent page (#201 review),
    /// replacing the sheet's rows and keeping the cursor sane.
    fn sqlite_page_step(&mut self, delta: i64) {
        let Some(path) = self.editor.path.clone() else {
            return;
        };
        let Some(view) = self.editor.sheet.as_mut() else {
            return;
        };
        let idx = view.current_sheet;
        let Some((table, page)) = view.sqlite_pages.get(idx).cloned() else {
            return;
        };
        let next = page.saturating_add_signed(delta as isize);
        if delta > 0 {
            // Do not run past the end: only step when a further page can
            // exist per the loaded batch being full.
            if view.sheets[idx].row_count() < crate::sqlite_view::ROW_CAP {
                self.status = String::from("Last page");
                return;
            }
        } else if page == 0 {
            return;
        }
        match crate::sqlite_view::table_page(&path, &table, next) {
            Ok((headers, rows, total)) if !rows.is_empty() || next == 0 => {
                let got = rows.len();
                let label = crate::sqlite_view::page_label(&table, next, got, total);
                view.sheets[idx] = crate::sheet::sheet_data_from_parts(label, headers, rows);
                if delta < 0 {
                    let last = view.sheets[idx].row_count().saturating_sub(1);
                    view.sheets[idx].cur_row = last;
                }
                view.sqlite_pages[idx].1 = next;
            }
            Ok(_) => self.status = String::from("Last page"),
            Err(e) => self.status = format!("Page fetch failed: {e}"),
        }
    }

    /// F3 / "Hex: Find Next": repeat the stored query from just past the
    /// cursor. The query itself is set by the find prompt
    /// (`InputPurpose::HexFind`), whose submit searches cursor-INCLUSIVE
    /// via `hex_find_run` directly.
    fn hex_find_next(&mut self) {
        let Some(view) = self.editor.hex.as_ref() else {
            return;
        };
        if view.last_find.is_none() {
            self.status = String::from("Hex: no find query yet (Cmd+F)");
            return;
        }
        self.hex_find_run(view.cursor.saturating_add(1));
    }

    /// Run the hex tab's stored find query from `from` (wrapping),
    /// selecting the match and reporting the outcome in the status line.
    fn hex_find_run(&mut self, from: u64) {
        let Some(view) = self.editor.hex.as_mut() else {
            return;
        };
        let Some(needle) = view.last_find.clone() else {
            return;
        };
        let rows = (view.layout.data_rows as usize).max(1);
        match view.find_forward(&needle, from) {
            Ok(crate::hex::FindOutcome::Found(off)) => {
                view.set_cursor(off, false, rows);
                view.sel_anchor = Some(off + needle.len() as u64 - 1);
                self.status = format!("Found at 0x{off:X}");
            }
            Ok(crate::hex::FindOutcome::NotFound) => {
                self.status = String::from("Not found");
            }
            Ok(crate::hex::FindOutcome::Capped) => {
                self.status = format!(
                    "Not found in the first {} MB scanned",
                    crate::hex::FIND_SCAN_CAP / (1024 * 1024)
                );
            }
            Err(e) => self.status = format!("Hex find failed: {e}"),
        }
    }

    /// Resize the sidebar / terminal pane while a splitter drag is in
    /// progress. The pointer's screen coordinate maps directly to the new
    /// edge: dragging horizontally sets the sidebar width to (column −
    /// activity-bar width); dragging vertically sets the terminal height
    /// to (right-pane bottom − row).
    fn handle_splitter_drag(&mut self, kind: SplitterDrag, column: u16, row: u16) {
        match kind {
            SplitterDrag::Sidebar => {
                let activity_w = if self.activity_bar_visible {
                    ACTIVITY_BAR_WIDTH
                } else {
                    0
                };
                let secondary_w = if self.secondary_side_bar_visible {
                    SECONDARY_SIDEBAR_WIDTH
                } else {
                    0
                };
                // Reconstruct the content width from the live regions rather
                // than the frame, so the drag is correct even before a real
                // render has stamped `last_frame_area`.
                let frame_x = self.last_frame_area.x;
                let total = activity_w + secondary_w + self.sidebar_width + self.last_content_width;
                let new_w = match self.side_bar_position {
                    // Left: sidebar starts after the activity bar; the seam is
                    // its right edge, so width = column - activity offset.
                    SideBarPosition::Left => {
                        column.saturating_sub(frame_x).saturating_sub(activity_w)
                    }
                    // Right: sidebar ends at the content's right edge (minus the
                    // activity bar); dragging the seam left grows it.
                    SideBarPosition::Right => (frame_x + total)
                        .saturating_sub(activity_w)
                        .saturating_sub(column),
                };
                let max_sidebar = total
                    .saturating_sub(activity_w)
                    .saturating_sub(secondary_w)
                    .saturating_sub(RIGHT_PANE_MIN);
                self.sidebar_width =
                    new_w.clamp(SIDEBAR_WIDTH_MIN, max_sidebar.max(SIDEBAR_WIDTH_MIN));
            }
            SplitterDrag::Terminal => {
                let Some(splitter_y) = self.terminal_splitter_y else {
                    return;
                };
                // Right pane spans [splitter_y - editor_h, splitter_y +
                // current_terminal_h). Compute the right-pane bottom from
                // the captured height so a drag past it just clamps.
                let bottom = splitter_y + self.terminal_height.unwrap_or(0);
                let actual_bottom = if bottom == splitter_y {
                    // Pre-drag we may have used a percent split; fall back
                    // to the captured content height.
                    splitter_y.saturating_add(self.last_content_height)
                } else {
                    bottom
                };
                let new_h = actual_bottom.saturating_sub(row);
                let max_h = self
                    .last_content_height
                    .saturating_sub(EDITOR_HEIGHT_MIN)
                    .max(TERMINAL_HEIGHT_MIN);
                self.terminal_height = Some(new_h.clamp(TERMINAL_HEIGHT_MIN, max_h));
            }
            SplitterDrag::EditorSeam(seam) => {
                if !self.editor_layout.is_split() {
                    return;
                }
                // Map the pointer onto the seam's axis (column for a vertical
                // seam line, row for a horizontal one) and repartition only the
                // two groups it separates. The seam carries no dedicated cell,
                // so the two groups tile the boundary exactly.
                let pointer = match seam.dir {
                    editor_layout::SplitDir::Horizontal => column,
                    editor_layout::SplitDir::Vertical => row,
                };
                self.editor_layout
                    .drag_seam(&seam, pointer, EDITOR_SPLIT_MIN);
            }
        }
    }

    /// Trash every entry in the tree's current action set (the multi-
    /// selection if non-empty, otherwise just the focused row). Workspace
    /// root rows are filtered by `delete_paths` — the shared choke point —
    /// even if some other path in the set proceeds.
    fn delete_selection(&mut self) {
        let paths = self.tree.action_paths();
        if paths.is_empty() {
            return;
        }
        self.delete_paths(paths);
    }

    fn delete_paths(&mut self, paths: Vec<PathBuf>) {
        // No workspace root row is ever a delete target, whichever flow
        // assembled the set: the context menu forwards a mixed multi-
        // selection wholesale, and Select All marks the root rows too, so
        // the per-node `delete_target_for` guard alone cannot protect a
        // root riding along in the batch. Filter here — the one choke
        // point every delete flow funnels through — with the same
        // canonicalized comparison the old primary-root guard used, so a
        // root reached through a symlinked path is still refused.
        let canon_roots: Vec<PathBuf> = self
            .tree
            .root_paths()
            .filter_map(|r| r.canonicalize().ok())
            .collect();
        let is_root = |p: &PathBuf| {
            self.tree.root_paths().any(|r| r == p)
                || p.canonicalize()
                    .ok()
                    .is_some_and(|cp| canon_roots.contains(&cp))
        };
        let paths: Vec<PathBuf> = paths.into_iter().filter(|p| !is_root(p)).collect();
        let total = paths.len();
        if total == 0 {
            self.status = String::from("Workspace roots cannot be deleted");
            return;
        }
        // Confirm before trashing — Delete (or the context menu's Delete) must
        // not remove files from a single action. Enter performs it; Esc keeps
        // them. Files go to the OS Trash (recoverable), so the wording reflects that.
        use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
        let title = if total == 1 {
            let name = paths[0]
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| paths[0].display().to_string());
            format!("Move '{name}' to Trash?")
        } else {
            format!("Move {total} items to Trash?")
        };
        self.open_input_prompt(
            InputPrompt::new(
                InputPurpose::TreeDelete { paths },
                title,
                "Enter to trash · Esc to keep",
            )
            .with_value("trash"),
        );
    }

    /// Perform the confirmed trash of `paths` (the popup's Enter path).
    fn perform_delete_paths(&mut self, paths: Vec<PathBuf>) {
        let total = paths.len();
        if total == 0 {
            return;
        }
        let mut affected_dirs: BTreeSet<PathBuf> = BTreeSet::new();
        for path in &paths {
            let parent = path
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| self.tree.root.clone());
            affected_dirs.insert(parent);
        }
        // One trash call for the whole batch — on macOS this routes through
        // Finder so the trash sound effect fires once for the operation
        // instead of once per file. The single-path path keeps the cheaper
        // NSFileManager backend.
        let result = if total == 1 {
            crate::widgets::file_tree::move_to_trash(&paths[0])
        } else {
            crate::widgets::file_tree::move_to_trash_bulk(&paths)
        };
        match result {
            Ok(()) => {
                for path in &paths {
                    if self.editor.matches_open_path(path) {
                        if !self.editor.close_active() {
                            *self.editor = Editor::new();
                        }
                        self.sync_open_file_poll_mtime();
                    }
                }
                for dir in &affected_dirs {
                    if let Some(idx) = self.tree.index_of_dir(dir) {
                        self.tree.refresh_children(idx);
                    }
                }
                self.tree.clear_marks();
                self.status = if total == 1 {
                    format!("Moved {} to Trash", paths[0].display())
                } else {
                    format!("Moved {total} items to Trash")
                };
            }
            Err(e) => {
                for dir in &affected_dirs {
                    if let Some(idx) = self.tree.index_of_dir(dir) {
                        self.tree.refresh_children(idx);
                    }
                }
                self.status = if total == 1 {
                    format!("Delete failed: {e}")
                } else {
                    format!("Bulk delete failed: {e}")
                };
            }
        }
    }

    /// Stash the current action paths into the explorer clipboard. The
    /// system text clipboard is left untouched so editor/terminal text
    /// copy gestures still work elsewhere in the app.
    fn copy_selection_to_explorer_clipboard(&mut self, mode: ExplorerClipMode) {
        let paths = self.tree.action_paths();
        if paths.is_empty() {
            return;
        }
        let n = paths.len();
        self.tree_clipboard = Some(ExplorerClipboard { mode, paths });
        self.status = match (mode, n) {
            (ExplorerClipMode::Copy, 1) => String::from("Copied 1 item"),
            (ExplorerClipMode::Copy, _) => format!("Copied {n} items"),
            (ExplorerClipMode::Cut, 1) => String::from("Cut 1 item"),
            (ExplorerClipMode::Cut, _) => format!("Cut {n} items"),
        };
    }

    /// Resolve the directory that an explorer paste/drop should land in,
    /// based on the currently focused node. Mirrors `create_target_dir_for`
    /// but for keyboard paste (no right-click coordinates).
    fn paste_target_dir(&self) -> PathBuf {
        let node = self.tree.nodes.get(self.tree.selected);
        crate::widgets::file_tree::create_target_dir_for(node, &self.tree.root)
    }

    /// Move (Cut) or copy (Copy) every clipboard path into `dest_dir`,
    /// then refresh affected directories and select the freshly-pasted
    /// items. Cut clears the explorer clipboard on success; Copy preserves
    /// it so the user can paste again.
    fn paste_explorer_clipboard(&mut self) {
        let dest_dir = self.paste_target_dir();
        self.paste_into(dest_dir);
    }

    /// `Ctrl/Cmd+D` from the explorer: smart toggle that mirrors the right-
    /// click "Select for Compare" / "Compare with Selected" / clear-anchor
    /// chain in a single key press.
    fn toggle_compare_on_selected_file(&mut self) {
        let Some(node) = self.tree.nodes.get(self.tree.selected) else {
            self.status = String::from("No file selected to compare");
            return;
        };
        if node.is_dir {
            self.status = String::from("Compare needs a file, not a folder");
            return;
        }
        let path = node.path.clone();
        match self.compare_anchor.as_ref() {
            Some(anchor) if anchor == &path => {
                self.compare_anchor = None;
                self.status = String::from("Cleared compare anchor");
            }
            Some(anchor) => {
                let anchor_clone = anchor.clone();
                match self.editor.open_diff(&anchor_clone, &path) {
                    Ok(()) => {
                        self.focus_pane(Pane::Editor);
                        self.compare_anchor = None;
                        self.sync_open_file_poll_mtime();
                        let l = anchor_clone
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_else(|| anchor_clone.display().to_string());
                        let r = path
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_else(|| path.display().to_string());
                        self.status = format!("Diff: {l} \u{2194} {r}");
                    }
                    Err(e) => {
                        self.status = format!("Diff failed: {e}");
                    }
                }
            }
            None => {
                let label = path
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| path.display().to_string());
                self.compare_anchor = Some(path);
                self.status =
                    format!("Selected {label} for compare — Ctrl/Cmd+D again on another file");
            }
        }
    }

    fn paste_into(&mut self, dest_dir: PathBuf) {
        let Some(clip) = self.tree_clipboard.clone() else {
            self.status = String::from("Explorer clipboard is empty");
            return;
        };
        self.apply_paste_or_drop(&dest_dir, &clip.paths, clip.mode);
        if matches!(clip.mode, ExplorerClipMode::Cut) {
            self.tree_clipboard = None;
        }
    }

    /// Shared implementation for explorer paste and drag-drop. `mode`
    /// distinguishes a move (Cut/drag) from a copy (Copy/Alt-drag).
    fn apply_paste_or_drop(&mut self, dest_dir: &Path, paths: &[PathBuf], mode: ExplorerClipMode) {
        let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
        affected.insert(dest_dir.to_path_buf());
        let mut placed: Vec<PathBuf> = Vec::new();
        let mut errors: Vec<String> = Vec::new();
        for src in paths {
            let result = match mode {
                ExplorerClipMode::Cut => {
                    let parent = src
                        .parent()
                        .map(Path::to_path_buf)
                        .unwrap_or_else(|| self.tree.root.clone());
                    affected.insert(parent);
                    crate::widgets::file_tree::move_into(dest_dir, src)
                }
                ExplorerClipMode::Copy => crate::widgets::file_tree::copy_into(dest_dir, src),
            };
            match result {
                Ok(p) => {
                    if matches!(mode, ExplorerClipMode::Cut) && self.editor.matches_open_path(src) {
                        self.editor.rename_open_path(src, &p);
                        self.rename_review_boxes_path(src, &p);
                    }
                    placed.push(p);
                }
                Err(e) => errors.push(format!("{}: {e}", src.display())),
            }
        }
        for dir in &affected {
            if let Some(idx) = self.tree.index_of_dir(dir) {
                self.tree.refresh_children(idx);
            }
        }
        self.tree.marked.clear();
        for p in &placed {
            self.tree.marked.insert(p.clone());
        }
        if let Some(first) = placed.first()
            && let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
        {
            self.tree.selected = idx;
            self.tree.anchor = idx;
        }
        let verb = match mode {
            ExplorerClipMode::Cut => "Moved",
            ExplorerClipMode::Copy => "Copied",
        };
        if !errors.is_empty() {
            self.status = format!(
                "{verb} {}/{}; failed: {}",
                placed.len(),
                paths.len(),
                errors.join("; ")
            );
        } else if placed.len() == 1 {
            self.status = format!("{verb} 1 item to {}", self.status_path(dest_dir));
        } else {
            self.status = format!(
                "{verb} {} items to {}",
                placed.len(),
                self.status_path(dest_dir)
            );
        }
    }

    fn open_create_prompt(&mut self, kind: CreateKind, target_dir: PathBuf) {
        let label = match kind {
            CreateKind::File => format!("New File in {}", self.status_path(&target_dir)),
            CreateKind::Folder => format!("New Folder in {}", self.status_path(&target_dir)),
        };
        self.prompt = Some(Prompt {
            label,
            buffer: String::new(),
            kind: PromptKind::Create(kind),
            target_dir,
            error: None,
        });
    }

    /// Workspace-relative rendering for status transients and prompt
    /// labels: tabs and breadcrumbs already speak root-relative, and an
    /// absolute path under a deep root pushed the one informative part —
    /// the filename — off the visible end of the bar (#100). Paths outside
    /// the root (`~/.ssh/config`, files opened by absolute path) keep
    /// their absolute form.
    fn status_path(&self, path: &Path) -> String {
        // Folder-relative via the OWNING root (#143): identical to a plain
        // primary-root strip while the set holds one entry, and already the
        // multi-root label rule once it holds more.
        let rel = self
            .roots
            .owning_root(path)
            .and_then(|r| path.strip_prefix(r).ok())
            .unwrap_or(path);
        if rel.as_os_str().is_empty() {
            String::from(".")
        } else {
            rel.display().to_string()
        }
    }

    fn open_rename_prompt(&mut self, path: PathBuf) {
        let parent = path
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| self.tree.root.clone());
        let current = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let label = format!("Rename {}", self.status_path(&path));
        self.prompt = Some(Prompt {
            label,
            buffer: current,
            kind: PromptKind::Rename(path),
            target_dir: parent,
            error: None,
        });
    }

    fn handle_prompt_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                self.prompt = None;
                // Abandon any in-flight prepare-rename too: its verdict would
                // otherwise reopen this prompt at the caret the user just
                // walked away from (#254 item 6).
                self.prepare_rename_request = None;
                self.status = String::from("Cancelled");
            }
            KeyCode::Enter => self.commit_prompt(),
            KeyCode::Backspace => {
                if let Some(p) = self.prompt.as_mut() {
                    p.buffer.pop();
                    p.error = None;
                }
            }
            KeyCode::Char(c) => {
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !key.modifiers.contains(KeyModifiers::SUPER)
                    && let Some(p) = self.prompt.as_mut()
                {
                    p.buffer.push(c);
                    p.error = None;
                }
            }
            _ => {}
        }
    }

    fn commit_prompt(&mut self) {
        let Some(prompt) = self.prompt.as_ref() else {
            return;
        };
        let kind = prompt.kind.clone();
        match kind {
            PromptKind::Create(create_kind) => {
                let name = prompt.buffer.trim().to_string();
                if let Err(msg) = crate::widgets::file_tree::validate_new_name(&name) {
                    if let Some(p) = self.prompt.as_mut() {
                        p.error = Some(msg.to_string());
                    }
                    return;
                }
                let target_dir = prompt.target_dir.clone();
                let result = match create_kind {
                    CreateKind::File => {
                        crate::widgets::file_tree::create_file_in(&target_dir, &name)
                    }
                    CreateKind::Folder => {
                        crate::widgets::file_tree::create_folder_in(&target_dir, &name)
                    }
                };
                match result {
                    Ok(path) => {
                        self.prompt = None;
                        self.status = match create_kind {
                            CreateKind::File => format!("Created file {}", self.status_path(&path)),
                            CreateKind::Folder => {
                                format!("Created folder {}", self.status_path(&path))
                            }
                        };
                        if let Some(idx) = self.tree.index_of_dir(&target_dir) {
                            self.tree.refresh_children(idx);
                            if let Some(new_idx) =
                                self.tree.nodes.iter().position(|n| n.path == path)
                            {
                                self.tree.select(new_idx);
                            }
                        }
                        if create_kind == CreateKind::File {
                            if let Err(e) = self.editor.open(&path) {
                                self.status = format!("Created but could not open: {e}");
                            } else {
                                self.sync_open_file_poll_mtime();
                                self.focus_pane(Pane::Editor);
                            }
                        }
                    }
                    Err(e) => {
                        if let Some(p) = self.prompt.as_mut() {
                            p.error = Some(e.to_string());
                        }
                    }
                }
            }
            PromptKind::Rename(old_path) => {
                let new_name = prompt.buffer.trim().to_string();
                let parent = prompt.target_dir.clone();
                match crate::widgets::file_tree::rename_in(&parent, &old_path, &new_name) {
                    Ok(new_path) => {
                        self.prompt = None;
                        self.status = format!("Renamed to {}", self.status_path(&new_path));
                        if let Some(idx) = self.tree.index_of_dir(&parent) {
                            self.tree.refresh_children(idx);
                            if let Some(new_idx) =
                                self.tree.nodes.iter().position(|n| n.path == new_path)
                            {
                                self.tree.select(new_idx);
                            }
                        }
                        self.editor.rename_open_path(&old_path, &new_path);
                        self.rename_review_boxes_path(&old_path, &new_path);
                        self.sync_open_file_poll_mtime();
                    }
                    Err(e) => {
                        if let Some(p) = self.prompt.as_mut() {
                            p.error = Some(e.to_string());
                        }
                    }
                }
            }
            PromptKind::RenameSymbol { path, row, col } => {
                let new_name = prompt.buffer.trim().to_string();
                if new_name.is_empty() {
                    if let Some(p) = self.prompt.as_mut() {
                        p.error = Some("Name cannot be empty".to_string());
                    }
                    return;
                }
                // The prompt captured buffer coordinates; the server wants
                // UTF-16, so convert here rather than casting the char column.
                let (line, character) = self.editor.pos_to_utf16(row, col);
                let Some(lsp) = self.lsp.as_mut() else {
                    if let Some(p) = self.prompt.as_mut() {
                        p.error = Some("No language server for this file".to_string());
                    }
                    return;
                };
                let id = lsp.request_rename(path, line, character, new_name);
                self.rename_request_id = Some(id);
                self.prompt = None;
                self.status = String::from("Renaming symbol");
            }
            PromptKind::BreakpointCondition { path, line } => {
                let expr = prompt.buffer.clone();
                self.prompt = None;
                self.commit_breakpoint_condition(path, line, &expr);
            }
            PromptKind::Logpoint { path, line } => {
                let message = prompt.buffer.clone();
                self.prompt = None;
                self.commit_logpoint(path, line, &message);
            }
            PromptKind::RenameTerminal(idx) => {
                let name = prompt.buffer.trim().to_string();
                self.prompt = None;
                if let Some(t) = self.terminals.get_mut(idx) {
                    let cleared = name.is_empty();
                    t.set_manual_name(if cleared { None } else { Some(name.clone()) });
                    self.status = if cleared {
                        String::from("Cleared terminal name")
                    } else {
                        format!("Renamed terminal to {name}")
                    };
                    self.save_terminal_session();
                }
            }
            PromptKind::AnnotateTerminal {
                pane,
                line,
                clock,
                start,
                len,
                existing,
            } => {
                let text = prompt.buffer.trim().to_string();
                self.prompt = None;
                if let Some(t) = self.terminals.get_mut(pane) {
                    self.status = String::from(match (existing, text.is_empty()) {
                        (Some(i), true) => {
                            t.remove_annotation(i);
                            "Deleted annotation"
                        }
                        (Some(i), false) => {
                            t.set_annotation_text(i, text);
                            "Updated annotation"
                        }
                        (None, true) => "Annotation cancelled (empty note)",
                        (None, false) => {
                            t.add_annotation(line, clock, start, len, text);
                            "Annotated selection (click the span to read it)"
                        }
                    });
                }
            }
        }
    }
}

/// Kitty keyboard-protocol flags croft requests on startup.
///
/// `DISAMBIGUATE_ESCAPE_CODES` is the bit that makes terminals deliver
/// modifier keys (notably Cmd/Super on macOS in iTerm2 ≥3.5, Ghostty, kitty,
/// WezTerm) as real key events rather than swallowing them or routing them to
/// menus. We deliberately do NOT request `REPORT_ALL_KEYS_AS_ESCAPE_CODES`
/// because that re-encodes ordinary printable input and would break typing.
fn keyboard_enhancement_flags() -> KeyboardEnhancementFlags {
    KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
        | KeyboardEnhancementFlags::REPORT_EVENT_TYPES
}

/// The terminal modes croft turns on whenever it takes over a screen: alt
/// screen, mouse tracking, bracketed paste, steady-bar cursor. SINGLE SOURCE
/// OF TRUTH — the startup takeover, the post-scp TUI restore, and the
/// dtach-reattach re-assert all emit exactly this block, so the mode lists
/// can never drift apart. A mode enabled at startup but missing from the
/// reattach re-assert is the "mouse dead after reconnecting to a persisted
/// remote session" bug (0.1.611); add any new startup mode HERE, never as an
/// inline `execute!` at a call site. The kitty keyboard flags are the one
/// deliberate exception: startup pushes them (the push pairs with the
/// teardown pop), while [`mode_reassert_seq`] appends the SET form.
fn takeover_mode_seq() -> Vec<u8> {
    let mut seq = Vec::new();
    let _ = execute!(
        seq,
        EnterAlternateScreen,
        EnableMouseCapture,
        EnableBracketedPaste,
        crossterm::cursor::SetCursorStyle::SteadyBar,
    );
    seq
}

/// Escape bytes re-asserting every terminal mode croft set at startup. A
/// dtach reattach (`-r winch`) delivers only a SIGWINCH: the newly attached
/// terminal never received the startup DECSETs, so the alt screen, mouse
/// tracking, bracketed paste, and kitty keyboard flags are all off — the
/// "mouse dead after reconnecting to a persisted remote session" bug. The
/// main loop emits this on every Resize when `CROFT_SESSION_PERSISTENT` is
/// set (the dtach branch of the remote launch command); every sequence is
/// idempotent on a terminal that already has the mode enabled. The kitty
/// keyboard flags use the SET form (`CSI = flags ; 1 u`), not the push the
/// startup path uses: a push per WINCH would stack entries the single pop at
/// exit can't unwind, leaving the user's shell with enhanced keys on.
fn mode_reassert_seq() -> Vec<u8> {
    use std::io::Write;
    let mut seq = takeover_mode_seq();
    let _ = write!(seq, "\x1b[={};1u", keyboard_enhancement_flags().bits());
    seq
}

/// Shrink `s` to at most `max` chars by cutting the middle, keeping roughly
/// a third of the head and two thirds of the tail — for path-shaped
/// messages the tail carries the filename, the part worth keeping. Never
/// appends a trailing ellipsis (the cut is interior by construction).
fn elide_middle(s: &str, max: usize) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= max {
        return s.to_string();
    }
    if max < 3 {
        return chars.iter().take(max).collect();
    }
    let keep = max - 1; // one cell for the ellipsis
    let head = keep / 3;
    let tail = keep - head;
    let mut out: String = chars[..head].iter().collect();
    out.push('\u{2026}');
    out.extend(&chars[chars.len() - tail..]);
    out
}

/// The excerpt window for a Peek popup: up to `total` lines, at most
/// `above` of them before `target`, clamped to the file. Returns the start
/// line index and the excerpt slice (cloned).
fn peek_excerpt(
    lines: &[String],
    target: usize,
    above: usize,
    total: usize,
) -> (usize, Vec<String>) {
    if lines.is_empty() {
        return (0, Vec::new());
    }
    let target = target.min(lines.len() - 1);
    let start = target.saturating_sub(above);
    let end = (start + total).min(lines.len());
    let start = end.saturating_sub(total).min(start);
    (start, lines[start..end].to_vec())
}

/// True when the "command" modifier is effectively held. That is `Super`
/// (Cmd) everywhere; on Termux (Android, no Cmd key) `Ctrl` stands in for it
/// too, mirroring VS Code's Linux keymap so the Super-only chords stay
/// reachable. `termux` is threaded in explicitly to keep the decision pure
/// and testable.
fn cmd_active(mods: KeyModifiers, termux: bool) -> bool {
    mods.contains(KeyModifiers::SUPER) || (termux && mods.contains(KeyModifiers::CONTROL))
}

/// `cmd_active` over the live environment (cached Termux detection).
fn has_cmd(mods: KeyModifiers) -> bool {
    cmd_active(mods, crate::iterm2_inline::detect_termux())
}

/// Build the OSC 0 escape sequence that sets the terminal's window/icon title.
///
/// Format: `ESC ] 0 ; <title> BEL`.  Control bytes that would break the escape
/// (BEL, ESC, newlines) are stripped from `title` so untrusted input cannot
/// inject further sequences.
fn set_title_seq(title: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(title.len() + 5);
    out.extend_from_slice(b"\x1b]0;");
    for byte in title.as_bytes() {
        match *byte {
            0x00..=0x1f | 0x7f => continue,
            b => out.push(b),
        }
    }
    out.push(0x07);
    out
}

/// iTerm2 proprietary OSC that overrides the *session* (not profile-on-disk)
/// bg colour. The `srgb:` prefix forces iTerm2 to interpret the hex bytes
/// as sRGB regardless of the user's "Use sRGB colour space" profile setting,
/// so combining this with an OSC-1337 PNG canvas filled with the same hex
/// guarantees both surfaces display the same physical pixel.
/// Format: `ESC ] 1 3 3 7 ; SetColors=bg=srgb:RRGGBB BEL`.
fn set_session_bg_srgb_seq(rgb: (u8, u8, u8)) -> String {
    format!(
        "\x1b]1337;SetColors=bg=srgb:{:02x}{:02x}{:02x}\x07",
        rgb.0, rgb.1, rgb.2,
    )
}

/// Revert the iTerm2 session bg to the user's profile default. Emitted on
/// exit so the user's shell doesn't inherit croft's forced bg colour.
fn reset_session_bg_seq() -> String {
    String::from("\x1b]1337;SetColors=bg=default\x07")
}

/// Standard dynamic-color OSCs setting the HOST terminal's default
/// background (OSC 11) and foreground (OSC 10) to the theme's. iTerm2 gets
/// its proprietary sRGB variant on top, but this portable pair is what
/// recolors Ghostty, Kitty, WezTerm, xterm and friends, so a light theme
/// turns the whole session white (the issue's "including the terminal it
/// runs on") and `Color::Reset` cells inherit the theme on every host. The
/// host fg is the theme's default code foreground, the color plain text
/// renders in anyway.
fn host_colors_seq(theme: crate::theme::Theme) -> String {
    let (br, bg, bb) = theme.editor_bg_rgb();
    let (fr, fg, fb) = theme.syntax().fg;
    format!("\x1b]11;rgb:{br:02x}/{bg:02x}/{bb:02x}\x07\x1b]10;rgb:{fr:02x}/{fg:02x}/{fb:02x}\x07")
}

/// Reset the host terminal's default foreground and background to its own
/// configuration (OSC 110/111), undoing [`host_colors_seq`] on exit.
fn reset_host_colors_seq() -> &'static str {
    "\x1b]110\x07\x1b]111\x07"
}

/// The host terminal croft is running inside, for spawning a new window of the
/// SAME terminal (Move/Copy into New Window). Detected from `$TERM_PROGRAM` /
/// `$TERM`, the same signals croft's inline-image detection keys off.
#[cfg(target_os = "macos")]
#[derive(Clone, Debug, PartialEq, Eq)]
enum HostTerminal {
    Ghostty,
    ITerm2,
    AppleTerminal,
    /// A terminal we don't know how to drive; carries its reported name so the
    /// status line can say which one rather than failing silently.
    Unknown(String),
}

#[cfg(target_os = "macos")]
fn detect_host_terminal(term_program: Option<&str>, term: Option<&str>) -> HostTerminal {
    match term_program {
        Some("ghostty") => HostTerminal::Ghostty,
        Some("iTerm.app") => HostTerminal::ITerm2,
        Some("Apple_Terminal") => HostTerminal::AppleTerminal,
        Some(other) if !other.is_empty() => HostTerminal::Unknown(other.to_string()),
        // Some setups only export TERM (e.g. `xterm-ghostty`).
        _ if term.is_some_and(|t| t.contains("ghostty")) => HostTerminal::Ghostty,
        _ => HostTerminal::Unknown(term.unwrap_or("unknown").to_string()),
    }
}

/// Spawn a brand-new OS window of the terminal croft is running in, opening
/// `croft <root> --open-file <file> --zen` — VS Code's "Move/Copy into New
/// Window", realised as a genuine separate window so the originating croft is
/// never disturbed. The new window opens in `--zen` (Explorer + terminal hidden)
/// so it focuses on just the file. The croft binary is referenced by its
/// resolved ABSOLUTE path: a GUI-launched croft inherits a stripped launchd
/// PATH, so the bare name would not resolve in the new window's shell (see the
/// project memory on PATH stripping). macOS only.
#[cfg(target_os = "macos")]
fn spawn_new_window(root: &std::path::Path, file: &std::path::Path) -> std::io::Result<()> {
    let exe = std::env::current_exe()?;
    let host = detect_host_terminal(
        std::env::var("TERM_PROGRAM").ok().as_deref(),
        std::env::var("TERM").ok().as_deref(),
    );
    match host {
        // Ghostty on macOS has no IPC (`+new-window` is Linux/GTK-only), so a
        // new window must come from `open -na` (a fresh instance). A fresh
        // instance would ALSO open its default window → two windows
        // (ghostty-org/ghostty#8669; verified empirically). `--initial-window=false`
        // suppresses that default (verified: it adds zero windows), so `-e`'s
        // command window is the only one. `--quit-after-last-window-closed` makes
        // the spawned instance exit once that window closes. `-e` is exec'd
        // directly (no shell), so the croft argv is passed token-by-token.
        HostTerminal::Ghostty => {
            std::process::Command::new("open")
                .args(ghostty_open_argv(&exe, root, file))
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()?;
            Ok(())
        }
        // iTerm2 and Terminal have no `open --args` command path; both are driven
        // by AppleScript, and both run the `command` / `do script` string through
        // a shell, so the croft invocation is shell-quoted.
        HostTerminal::ITerm2 => {
            std::process::Command::new("osascript")
                .arg("-e")
                .arg(iterm2_new_window_script(&exe, root, file))
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()?;
            Ok(())
        }
        HostTerminal::AppleTerminal => {
            std::process::Command::new("osascript")
                .arg("-e")
                .arg(apple_terminal_new_window_script(&exe, root, file))
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()?;
            Ok(())
        }
        HostTerminal::Unknown(name) => Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            format!("unsupported terminal '{name}'"),
        )),
    }
}

/// `open` argv for a new Ghostty window running croft, focused on the file
/// (`--zen`). `--initial-window=false` stops the fresh instance opening a stray
/// default window beside the `-e` one. Split out so the shape is unit-testable
/// without launching a window.
#[cfg(target_os = "macos")]
fn ghostty_open_argv(
    exe: &std::path::Path,
    root: &std::path::Path,
    file: &std::path::Path,
) -> Vec<std::ffi::OsString> {
    use std::ffi::OsString;
    vec![
        OsString::from("-na"),
        OsString::from("Ghostty"),
        OsString::from("--args"),
        OsString::from("--initial-window=false"),
        OsString::from("--quit-after-last-window-closed=true"),
        OsString::from("-e"),
        exe.as_os_str().to_os_string(),
        root.as_os_str().to_os_string(),
        OsString::from("--open-file"),
        file.as_os_str().to_os_string(),
        OsString::from("--zen"),
    ]
}

/// `croft <root> --open-file <file> --zen` as a single shell command line, with
/// every path single-quoted so spaces and shell metacharacters survive (iTerm2
/// `command` and Terminal `do script` both run it via a shell). `--zen` opens
/// the new window focused on the file (no sidebar/terminal).
#[cfg(target_os = "macos")]
fn new_window_shell_command(
    exe: &std::path::Path,
    root: &std::path::Path,
    file: &std::path::Path,
) -> String {
    fn shq(p: &std::path::Path) -> String {
        format!("'{}'", p.to_string_lossy().replace('\'', r"'\''"))
    }
    format!("{} {} --open-file {} --zen", shq(exe), shq(root), shq(file))
}

/// Escape a Rust string for embedding inside an AppleScript double-quoted
/// string literal (backslash and double-quote are the only specials).
#[cfg(target_os = "macos")]
fn applescript_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// AppleScript to open a new iTerm2 window running croft. iTerm2's `command`
/// argument overrides the profile's default `login`, running our shell command.
#[cfg(target_os = "macos")]
fn iterm2_new_window_script(
    exe: &std::path::Path,
    root: &std::path::Path,
    file: &std::path::Path,
) -> String {
    let cmd = applescript_escape(&new_window_shell_command(exe, root, file));
    format!(r#"tell application "iTerm" to create window with default profile command "{cmd}""#)
}

/// AppleScript to open a new Terminal.app window running croft. `do script`
/// with no target opens a fresh window and runs the command there.
#[cfg(target_os = "macos")]
fn apple_terminal_new_window_script(
    exe: &std::path::Path,
    root: &std::path::Path,
    file: &std::path::Path,
) -> String {
    let cmd = applescript_escape(&new_window_shell_command(exe, root, file));
    format!(r#"tell application "Terminal" to do script "{cmd}""#)
}

/// Non-macOS builds have no supported window-spawn path yet (each terminal's
/// CLI differs per platform); the caller surfaces the error as a status line.
#[cfg(not(target_os = "macos"))]
fn spawn_new_window(_root: &std::path::Path, _file: &std::path::Path) -> std::io::Result<()> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "opening a new window is only supported on macOS",
    ))
}

fn build_title(workspace: &std::path::Path) -> String {
    let name = workspace
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| workspace.display().to_string());
    format!("{APP_NAME}  {name}")
}

/// Returns true if the given key event should copy the terminal pane's
/// current selection to the clipboard.  Recognises:
///   * `Ctrl+Shift+C` — universal Linux terminal copy convention; doesn't
///     collide with `Ctrl+C` (SIGINT).
///   * `Cmd+C`        — for terminals that deliver Super via the kitty
///     keyboard protocol.
fn is_terminal_copy_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'c') {
        return false;
    }
    let ctrl_shift = key.modifiers.contains(KeyModifiers::CONTROL)
        && key.modifiers.contains(KeyModifiers::SHIFT);
    let super_only = key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::CONTROL);
    ctrl_shift || super_only
}

/// Returns true if the given key event should jump to the Search sidebar
/// view (VS Code's Ctrl/Cmd+Shift+F "Find in Files" gesture).
/// `Ctrl+D` / `Cmd+D` (no Shift). Used in the Explorer to drive the
/// "compare two files" flow:
///   * no anchor yet → stash the highlighted file as the anchor;
///   * anchor + different file → open a side-by-side diff;
///   * anchor + same file → clear the anchor (toggle off).
fn is_compare_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'d') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

fn is_search_jump_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'f') {
        return false;
    }
    let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
    let has_ctrl_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER);
    has_shift && has_ctrl_or_super
}

/// VS Code-style `Cmd+F` / `Ctrl+F` inside the editor: open the inline
/// Find bar. Same chord as the Explorer's "New File" — the dispatch in
/// `handle_key` gives the Explorer handler first refusal so this only
/// fires when the editor is the focused pane.
fn is_editor_find_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'f') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// The terminal pane's find chord: Cmd+F everywhere, plus Ctrl+F off macOS
/// only (VS Code's terminal find defaults). On macOS Ctrl+F must reach the
/// child as 0x06 — it is a control byte programs bind — so the editor's
/// looser Ctrl-or-Cmd predicate must not gate the terminal pane there.
fn is_terminal_find_key(key: KeyEvent) -> bool {
    if !is_editor_find_key(key) {
        return false;
    }
    cfg!(not(target_os = "macos")) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// VS Code-style `Cmd+Opt+F` / `Ctrl+Alt+F` inside the editor: open the
/// find bar expanded with the replace row (VS Code's
/// `editor.action.startFindReplaceAction`). The iTerm2 / Ghostty
/// forwarders deliver the macOS chord as CSI-u decoding to ALT|SUPER;
/// Linux kitty-protocol terminals report Ctrl+Alt+F as ALT|CONTROL.
/// Shift excluded: `Cmd+Opt+Shift+F` is Format Document.
fn is_editor_replace_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'f') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || !key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// VS Code-style `Cmd+P` / `Ctrl+P`: open the Quick Open file finder.
/// Plain `p` with no modifier (or with Shift / Alt only) falls through so
/// the editor still receives literal `p` keystrokes.
fn is_file_finder_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'p') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// `Ctrl/Cmd+Shift+P`: open the Command Palette from any pane, mirroring VS
/// Code. Shares the `is_cmd_shift_letter` helper with the sidebar-view jumps
/// so the SHIFT / case handling is identical, and sits after
/// `is_file_finder_key` in the dispatch (which rejects SHIFT, so `Cmd+P` and
/// `Cmd+Shift+P` never collide).
fn is_command_palette_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'p')
}

/// `Cmd+Shift+O` (macOS) / `Ctrl+Shift+O` (Linux): VS Code's "Go to Symbol in
/// Editor". Opens the symbol picker (also Go to Line via a `:` prefix).
fn is_go_to_symbol_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'o')
}

/// `Cmd+K` (macOS) / `Ctrl+K` (Linux / Termux): the leader for croft's
/// `Cmd+K`-prefixed chords (Color Theme, Close to the Right, Select for /
/// Compare with Selected, Close All). Rejects Shift and Alt so it never
/// shadows a future `Cmd+K`+modifier chord.
fn is_cmd_k_leader_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'k') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    // SUPER everywhere; CONTROL only on Termux (where Ctrl is the cmd
    // surrogate). Off Termux a bare Ctrl+K must fall through to the editor's
    // kill-to-end-of-line rather than arming the leader — using `has_cmd`
    // keeps this consistent with every other croft chord (e.g. Cmd+\ split).
    has_cmd(key.modifiers)
}

/// `Cmd+/` (macOS) / `Ctrl+/` (Linux / Termux): Toggle Line Comment. Rejects
/// Shift and Alt so it never collides with a future chord on `/`.
fn is_toggle_line_comment_key(key: KeyEvent) -> bool {
    if key.code != KeyCode::Char('/') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// `Shift+Alt+A`: Toggle Block Comment (the VS Code default). Requires both
/// Shift and Alt and rejects the command modifier. Also reachable from the
/// Command Palette, which is the parity path on terminals that swallow the
/// Alt+letter chord.
fn is_toggle_block_comment_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'a') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SHIFT)
        && key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
}

/// `Alt+Z`: View: Toggle Word Wrap (the VS Code default). Rejects Shift and
/// the command modifier. Also reachable from the Command Palette.
fn is_toggle_wrap_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'z') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
}

/// Explorer-pane shortcut: `Cmd+Z` — open the zoxide jump popup. `z` for
/// **z**oxide; the user's shell still uses `j` for the same jump. Requires
/// SUPER (iTerm2 already forwards Cmd+Z as `Char('z') + SUPER` for the
/// editor's undo via the `CMD_Z` GlobalKeyMap entry). Off Termux it rejects
/// CONTROL so a terminal `Ctrl+Z` suspend never reaches it and it stays
/// distinct from the Ctrl-based terminal-toggle chords on `j`; on Termux,
/// where Ctrl is the Cmd surrogate, `Ctrl+Z` opens the popup (this predicate
/// only runs while the Explorer is focused, so there is no suspend to clash).
/// SHIFT is rejected because `Cmd+Shift+Z` is the reserved redo chord.
/// Editor-pane `Cmd+Z` is untouched: this predicate is only consulted from
/// `handle_explorer_shortcut`, which runs solely when the Explorer is
/// focused (and gets first refusal in the dispatch chain).
fn is_tree_zoxide_jump_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'z') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    // `has_cmd` is SUPER-only off Termux (so a terminal `Ctrl+Z` suspend is
    // never swallowed); on Termux Ctrl is the command key, and this predicate
    // only runs while the Explorer is focused, so there is no suspend to clash.
    has_cmd(key.modifiers)
}

/// Explorer-pane shortcut: `Cmd+F` / `Ctrl+F` (no Shift, no Alt) - "New File".
fn is_tree_new_file_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'f') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Explorer-pane shortcut: `Cmd+Shift+N` / `Ctrl+Shift+N` - "New Folder".
/// The global dispatcher gives the Explorer-context handler first refusal
/// so this only fires when the tree is the focused pane; outside Explorer
/// the chord is unbound and falls through to the focused pane.
fn is_tree_new_folder_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'n') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Explorer-pane shortcut: `Cmd+R` / `Ctrl+R` (no Shift) OR plain `F2` -
/// "Rename". F2 is the cross-IDE convention; Cmd+R matches the user-
/// requested chord (overrides iTerm's "Clear buffer" via setup-iterm2).
fn is_tree_rename_key(key: KeyEvent) -> bool {
    if matches!(key.code, KeyCode::F(2)) {
        return true;
    }
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'r') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// `Cmd+Opt+R` / `Ctrl+Opt+R` - "Reveal in Finder". Used by both the Explorer
/// (reveals the selected entry) and the editor (reveals the active file's path).
/// The Alt requirement keeps this disjoint from `Cmd+R` (Rename), which rejects
/// Alt, so the two R chords never collide. The caller additionally gates this to
/// a local macOS session, matching the context-menu entry.
fn is_reveal_in_finder_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'r') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// `Cmd+Opt+C` / `Ctrl+Opt+C` - "Copy Path": put the active file's absolute
/// path on the system clipboard. The Alt requirement keeps it disjoint from
/// plain `Cmd+C` (Copy selection), and rejecting Shift keeps it disjoint from
/// `Cmd+Opt+Shift+C` (Copy Relative Path). Mirrors VS Code's binding.
fn is_copy_path_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'c') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Explorer-pane shortcut: `Cmd+/` / `Ctrl+/` - "Make root". Re-roots the
/// workspace at the selected folder.
fn is_tree_make_root_key(key: KeyEvent) -> bool {
    if !matches!(key.code, KeyCode::Char('/')) {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Explorer-pane shortcut: `Cmd+Shift+/` / `Ctrl+Shift+/` - "Make root at
/// parent". Re-roots the workspace at the parent of the selected node
/// (file or folder). The selected node itself remains on disk and the
/// new root is one filesystem level up. Terminals that strip Shift on
/// shifted punctuation report `?`; we accept both `/+Shift` and `?` to
/// cover the spread.
fn is_tree_make_parent_root_key(key: KeyEvent) -> bool {
    if key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    let has_ctrl_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER);
    if !has_ctrl_or_super {
        return false;
    }
    match key.code {
        KeyCode::Char('/') => key.modifiers.contains(KeyModifiers::SHIFT),
        KeyCode::Char('?') => true,
        _ => false,
    }
}

/// `Ctrl/Cmd+Shift+E`: jump to the Explorer sidebar view from any pane.
/// Matches VS Code's "View: Show Explorer" command.
fn is_explorer_jump_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'e')
}

/// `Ctrl/Cmd+Shift+S`: jump to the Source Control sidebar view from any pane.
/// This is croft's Source Control gesture. Croft has no editor Save-As (Cmd+S
/// alone saves), so claiming Cmd+Shift+S is collision-free even while editing.
fn is_source_control_jump_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 's')
}

/// `Ctrl/Cmd+Shift+D`: jump to the Run and Debug sidebar view from any pane.
/// Matches VS Code's "View: Show Run and Debug" command. iTerm2 binds the
/// same chord to "Split Horizontally with Same Profile" — `setup-iterm2`
/// relocates that menu item to Cmd+Opt+Shift+D so this chord reaches croft.
fn is_run_debug_jump_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'd')
}

/// `Ctrl/Cmd+Shift+R`: jump to the Remote (SSH) sidebar view from any pane.
/// VS Code uses this for "Remote Explorer" in the Remote Development pack —
/// same intent.
fn is_remote_jump_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'r')
}

/// `Ctrl/Cmd+Shift+X`: jump to the Extensions sidebar view from any pane.
/// Matches VS Code's "View: Show Extensions". Cmd+Shift+X is unbound by any
/// default macOS / iTerm2 menu item, so `setup-iterm2` only needs the
/// GlobalKeyMap forwarder (no menu relocation) to deliver it here.
fn is_extensions_jump_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'x')
}

/// The TurnDone status fragment for a turn's notes: the file is named only
/// when every note landed in the SAME file. "3 comments in b.rs" was a lie
/// when two of them sat in a.rs (F4 only cycles the active file, so the
/// name tells the user where to look).
fn turn_note_summary(notes: usize, files: &std::collections::BTreeSet<String>) -> String {
    let plural = if notes == 1 { "comment" } else { "comments" };
    match files.len() {
        0 => format!("{notes} {plural}"),
        1 => format!(
            "{notes} {plural} in {}",
            files.iter().next().expect("len checked")
        ),
        n => format!("{notes} {plural} across {n} files"),
    }
}

/// Index of the next navigator note to visit from `here` = (row, index of
/// the currently focused note, or `usize::MAX` when the walk starts from a
/// bare caret row): the note with the smallest (row, index) strictly greater
/// than `here`, wrapping to the smallest overall. The index tie-break makes
/// every note on a shared row reachable - the reply flow anchors the
/// navigator's answer on the answered note's own row, and a row-only walk
/// could never step from the first co-anchored note to the second.
fn next_note_by_row(notes: &[(u64, usize, String)], here: (usize, usize)) -> usize {
    notes
        .iter()
        .enumerate()
        .filter(|(i, (_, row, _))| (*row, *i) > here)
        .min_by_key(|(i, (_, row, _))| (*row, *i))
        .or_else(|| {
            notes
                .iter()
                .enumerate()
                .min_by_key(|(i, (_, row, _))| (*row, *i))
        })
        .map(|(i, _)| i)
        .unwrap_or(0)
}

fn is_drop_to_local_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'l')
}

/// `Ctrl/Cmd+Shift+B`: run the project's auto-detected build task, VS
/// Code's "Tasks: Run Build Task" chord. iTerm2 binds the same chord to
/// "Show Toolbelt" — `setup-iterm2` relocates that menu item to
/// Cmd+Ctrl+B so this chord reaches croft.
fn is_run_build_task_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'b')
}

/// `Cmd/Ctrl+Shift+V`: Markdown: Toggle Preview (the VS Code default chord).
/// iTerm2 binds the same chord to Paste Special > "Paste Selection" —
/// `setup-iterm2` relocates that menu item so this chord reaches croft.
fn is_markdown_preview_key(key: KeyEvent) -> bool {
    is_cmd_shift_letter(key, 'v')
}

/// Cmd+Enter (#353): run the shell fence under the caret in a Markdown
/// source buffer.
fn is_run_fence_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Enter)
        && key.modifiers.contains(KeyModifiers::SUPER)
        // Cmd+Shift+Enter is "insert line above"; Alt chords stay the
        // editor's.
        && !key
            .modifiers
            .intersects(KeyModifiers::SHIFT | KeyModifiers::ALT)
}

/// The command typed into a pane for a fenced block (#353): a shell block
/// as written (a trailing newline runs its last line); python and node
/// through a quoted heredoc so the block runs whole. The terminator is
/// chosen not to occur in the block, or a line inside it could close the
/// heredoc early and hand the rest to the shell.
fn fence_command(interpreter: &str, code: &str) -> String {
    let code = code.trim_end_matches('\n');
    match interpreter {
        "sh" => format!("{code}\r"),
        other => {
            let mut end = String::from("CROFT_BLOCK");
            let mut n = 0u32;
            while code.contains(&end) {
                n += 1;
                end = format!("CROFT_BLOCK_{n}");
            }
            format!("{other} - <<'{end}'\n{code}\n{end}\r")
        }
    }
}

/// Milliseconds since the Unix epoch, for stamping local-history snapshots
/// and dating TIMELINE rows.
fn now_millis() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

fn is_cmd_shift_letter(key: KeyEvent, letter: char) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&letter) {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
    let has_ctrl_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER);
    has_shift && has_ctrl_or_super
}

/// The status line shown after a keybindings reload.
///
/// Split out of `reload_config_for_path` so it can be tested against a keymap
/// built in memory. The alternative — a test that writes the real
/// `~/.config/croft/keybindings.json` — would leak into every one of the
/// thousands of concurrent tests that construct an `App`, since `App::new`
/// loads that path unconditionally.
fn keybindings_reload_status(warns: &[String]) -> String {
    if warns.is_empty() {
        String::from(
            "Keybindings reloaded (for new Cmd chords, re-run croft setup-iterm2 / setup-ghostty)",
        )
    } else {
        // One assignment: a second unconditional one below used to clobber
        // this, so the user never saw the warning count and a refused row
        // looked like croft ignoring them.
        format!(
            "Keybindings reloaded with {} warning{} — see OUTPUT · Keybindings",
            warns.len(),
            if warns.len() == 1 { "" } else { "s" }
        )
    }
}

/// `Cmd+B` (macOS) / `Ctrl+B` (Linux): toggle the primary side bar (left
/// pane) visibility, mirroring VS Code's "View: Toggle Primary Side Bar".
/// Accepts SUPER *or* CONTROL so the chord behaves identically whether
/// iTerm2 forwards `Cmd+B` as the CSI-u Super sequence (see `src/iterm2.rs`)
/// or a raw `Ctrl+B` control byte arrives on a remote Linux session. SHIFT
/// and ALT must not be held, so it never collides with a future bracketed
/// or word-motion chord on `b`.
fn is_sidebar_toggle_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'b') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// `⌥⌘B` (macOS) / `Ctrl+Alt+B` (Linux): toggle the secondary side bar (the
/// Outline), the edge opposite the primary side bar. ALT distinguishes it from
/// the plain ⌘B/Ctrl+B primary-side-bar toggle.
fn is_secondary_sidebar_toggle_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'b') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Returns true for `Cmd+Opt+M` (the CSI-u forwarders decode it as ALT|SUPER):
/// VS Code's "View: Toggle Minimap". SHIFT must not be held.
fn is_minimap_toggle_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'m') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Returns true if the given key event should toggle the terminal pane.
/// VS Code uses `Ctrl+`` ` `` (backtick); we use `Ctrl+J` to match its
/// "Toggle Terminal Panel" shortcut, which is more reliable to type on
/// non-US keyboards. Case-insensitive on the letter. SHIFT must NOT be
/// held — Ctrl+Shift+J is reserved for the maximize-terminal chord and
/// must not double-fire as a toggle.
fn is_terminal_toggle_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'j') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) && !key.modifiers.contains(KeyModifiers::SHIFT)
}

/// `Ctrl+Shift+J`: toggle "maximize terminal" — the editor / welcome pane
/// collapses and the terminal fills the right column next to the Explorer.
/// Pressing it again restores the previous editor↔terminal split.
fn is_terminal_maximize_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'j') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        && key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SUPER)
}

/// `Cmd+T` (or legacy `Ctrl+Shift+T`): spawn an additional terminal next
/// to the active one. iTerm2's GlobalKeyMap forwards `Cmd+T` as
/// `ESC [ 116 ; 9 u`, which crossterm decodes to `Char('t') + SUPER`.
/// In the SUPER branch we reject SHIFT so the `Cmd+Shift+T` focus chord
/// (see `is_terminal_focus_key`) does not double-fire as a split, and
/// reject ALT so `Cmd+Opt+T` (iTerm2's relocated New Tab) is left alone.
/// `Ctrl+Shift+Space`: WezTerm's quick-select chord. No Cmd involved, so it
/// needs no host-terminal forwarder — it arrives disambiguated through the
/// kitty keyboard protocol exactly like the Ctrl+Shift+T split chord.
/// One compiled per-host accent rule: hostname glob, accent color, badge.
type HostAccent = (globset::GlobMatcher, (u8, u8, u8), Option<String>);

/// Compile the prefs' host-accent rules: glob matcher + color (danger red
/// when unset) + badge. A rule with an invalid glob is skipped.
fn compile_host_accents(rules: &[crate::prefs::HostAccentRule]) -> Vec<HostAccent> {
    rules
        .iter()
        .filter_map(|r| {
            let m = globset::Glob::new(&r.pattern).ok()?.compile_matcher();
            let color = r
                .accent
                .as_deref()
                .and_then(crate::prefs::parse_hex)
                .unwrap_or((0xf1, 0x4c, 0x4c));
            Some((m, color, r.badge.clone()))
        })
        .collect()
}

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

/// `Ctrl+Shift+Y` (Y for yank; WezTerm's Ctrl+Shift+X is croft's
/// Extensions jump). Arrives via the kitty keyboard protocol, so no
/// iTerm2/Ghostty forwarder is needed.
fn is_copy_mode_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char('y' | 'Y'))
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && key.modifiers.contains(KeyModifiers::SHIFT)
}

/// `Ctrl+Shift+H` (H for history; atuin's Ctrl+R belongs to the shell and
/// Ctrl+Shift+R is croft's Remote jump). Kitty-protocol chord, no
/// forwarder needed.
fn is_command_history_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char('h' | 'H'))
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && key.modifiers.contains(KeyModifiers::SHIFT)
}

fn is_terminal_split_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'t') {
        return false;
    }
    if has_cmd(key.modifiers)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
    {
        return true;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) && key.modifiers.contains(KeyModifiers::SHIFT)
}

/// `Cmd+\`: split the editor into two side-by-side columns (VS Code's
/// `workbench.action.splitEditor`). iTerm2's GlobalKeyMap forwards it as
/// `ESC [ 92 ; 9 u`, which crossterm decodes to `Char('\\') + SUPER`.
/// SUPER-only; reject SHIFT/ALT so it can't double-fire with a future
/// modified backslash chord.
fn is_editor_split_key(key: KeyEvent) -> bool {
    let KeyCode::Char('\\') = key.code else {
        return false;
    };
    // SUPER off Termux; on Termux `Ctrl+\` is the command surrogate (note this
    // shadows the shell's SIGQUIT there, the accepted cost of Ctrl parity).
    has_cmd(key.modifiers)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// `Cmd+Shift+\`: Go to Bracket (VS Code's `editor.action.jumpToBracket`). The
/// same `\` key as the split chord but with Shift, so the two are disjoint.
fn is_goto_bracket_key(key: KeyEvent) -> bool {
    let KeyCode::Char('\\') = key.code else {
        return false;
    };
    has_cmd(key.modifiers)
        && key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// `Cmd+Opt+\`: Select to Bracket (VS Code's `editor.action.selectToBracket`).
/// The `\` bracket-family key with Opt (not Shift), disjoint from the split
/// chord (`Cmd+\`) and Go to Bracket (`Cmd+Shift+\`).
fn is_select_to_bracket_key(key: KeyEvent) -> bool {
    let KeyCode::Char('\\') = key.code else {
        return false;
    };
    has_cmd(key.modifiers)
        && key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
}

/// VS Code "Go Back" (Ctrl+-). The kitty keyboard protocol delivers the
/// chord as `-` + CONTROL; the legacy encoding folds Ctrl+- into 0x1F,
/// which decodes as `_` + CONTROL, so both spellings are accepted.
fn is_navigate_back_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    (c == '-' || c == '_')
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
}

/// VS Code "Go Forward" (Ctrl+Shift+-). Only the explicitly SHIFT-tagged
/// spellings count: the kitty protocol reports the chord as `-` (or the
/// shifted `_`) with CONTROL|SHIFT, while the legacy 0x1F byte decodes as
/// `_` + CONTROL with no SHIFT and must stay Go Back (a legacy host cannot
/// distinguish Ctrl+- from Ctrl+Shift+-, and Back is the safer meaning).
fn is_navigate_forward_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    (c == '-' || c == '_')
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// `Ctrl+T`: Transpose Characters around the Cursor (VS Code's
/// `editor.action.transpose`). A raw control byte, so it needs no iTerm2 /
/// Ghostty forwarder; the editor intercepts it only when focused, leaving the
/// shell's own `Ctrl+T` intact when the terminal is focused.
fn is_transpose_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'t') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
}

/// `Cmd+Opt+Shift+S`: Convert Indentation to Spaces
/// (`editor.action.indentationToSpaces`).
fn is_indentation_to_spaces_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 's')
}

/// `Cmd+Opt+Shift+T`: Convert Indentation to Tabs
/// (`editor.action.indentationToTabs`).
fn is_indentation_to_tabs_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 't')
}

/// `Cmd+Opt+Shift+N`: Trim Final Newlines (VS Code's `files.trimFinalNewlines`
/// surfaced as a command).
fn is_trim_final_newlines_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'n')
}

/// `Cmd+Opt+Shift+J`: Join Lines (`editor.action.joinLines`).
fn is_join_lines_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'j')
}

/// `Cmd+Opt+Shift+U`: Transform to Uppercase (`editor.action.transformToUppercase`).
fn is_transform_upper_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'u')
}

/// `Cmd+Opt+Shift+L`: Transform to Lowercase (`editor.action.transformToLowercase`).
fn is_transform_lower_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'l')
}

/// `Cmd+Opt+Shift+C` / `Ctrl+Opt+Shift+C` - "Copy Relative Path": put the
/// active file's path, relative to the workspace root, on the clipboard. The
/// Shift distinguishes it from plain `Cmd+Opt+C` (Copy Path, absolute). Mirrors
/// VS Code's binding; Transform to Title Case keeps its Command Palette entry
/// but gives up this chord (VS Code assigns Title Case no default key).
fn is_copy_relative_path_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'c')
}

/// `Cmd+Opt+Shift+A`: Sort Lines Ascending (`editor.action.sortLinesAscending`).
fn is_sort_lines_asc_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'a')
}

/// `Cmd+Opt+Shift+D`: Sort Lines Descending (`editor.action.sortLinesDescending`).
fn is_sort_lines_desc_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'd')
}

/// `Cmd+Opt+Shift+W`: Trim Trailing Whitespace (`editor.action.trimTrailingWhitespace`).
fn is_trim_trailing_whitespace_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'w')
}

/// `Cmd+Opt+Shift+F`: Format Document (`editor.action.formatDocument`, VS Code's
/// `Shift+Alt+F`). Reformats the whole buffer through the language server.
fn is_format_document_key(key: KeyEvent) -> bool {
    is_cmd_alt_shift_letter(key, 'f')
}

/// The breadcrumb scope chain for `line`: the indices of every outline symbol
/// whose range encloses the caret line, ordered outermost first (the enclosing
/// class before the method inside it). Sibling symbols never overlap, so the
/// enclosing symbols form a single nesting chain and ordering by decreasing
/// span puts the outermost first.
fn breadcrumb_symbol_chain(
    symbols: &[crate::lsp::manager::OutlineSymbol],
    line: u32,
) -> Vec<usize> {
    let mut hits: Vec<usize> = symbols
        .iter()
        .enumerate()
        .filter(|(_, s)| line >= s.range_start_line && line <= s.range_end_line)
        .map(|(i, _)| i)
        .collect();
    hits.sort_by(|&a, &b| {
        let span = |i: usize| symbols[i].range_end_line - symbols[i].range_start_line;
        span(b).cmp(&span(a)).then(
            symbols[a]
                .range_start_line
                .cmp(&symbols[b].range_start_line),
        )
    });
    hits
}

/// VS Code "Quick Fix": `Cmd+.` on macOS (delivered as `Char('.')` + SUPER by
/// the iTerm2 / Ghostty CSI-u forwarder) and `Ctrl+.` on Linux / Termux. Plain
/// `.`, `Shift+.` ('>'), and `Alt+.` (the shell's last-argument) are excluded.
fn is_quick_fix_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char('.'))
        && (key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL))
        && !key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
}

/// True for `Cmd+Opt+Shift+<letter>` (or `Ctrl+Opt+Shift+<letter>` on Termux):
/// the three-modifier sibling of [`is_cmd_shift_letter`], used for editor
/// commands VS Code leaves unbound so croft can still honor "everything has a
/// shortcut" without colliding with the two-modifier `Cmd+Shift+<letter>` set.
fn is_cmd_alt_shift_letter(key: KeyEvent, letter: char) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&letter) {
        return false;
    }
    let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
    let has_alt = key.modifiers.contains(KeyModifiers::ALT);
    let has_cmd_or_ctrl = key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER);
    has_shift && has_alt && has_cmd_or_ctrl
}

/// `Cmd+Opt+Left`: move keyboard focus to the LEFT editor group while
/// split. Distinct from the plain `Opt+Left` word-left motion (no SUPER)
/// by requiring both SUPER and ALT. iTerm2 forwards it as `ESC [ 1 ; 12 D`.
fn is_focus_group_left_key(key: KeyEvent) -> bool {
    let KeyCode::Left = key.code else {
        return false;
    };
    has_cmd(key.modifiers) && key.modifiers.contains(KeyModifiers::ALT)
}

/// `Cmd+Opt+Right`: move keyboard focus to the RIGHT editor group while
/// split. Mirror of `is_focus_group_left_key`. iTerm2 forwards it as
/// `ESC [ 1 ; 12 C`.
fn is_focus_group_right_key(key: KeyEvent) -> bool {
    let KeyCode::Right = key.code else {
        return false;
    };
    has_cmd(key.modifiers) && key.modifiers.contains(KeyModifiers::ALT)
}

/// `Cmd+Shift+T` (Mac SUPER+SHIFT+T): focus the Terminal pane from any
/// pane, un-hiding it if it was collapsed via Ctrl+J. SUPER-only so the
/// cross-platform `Ctrl+Shift+T` (split-terminal) chord keeps its
/// historical meaning - the two chords share the same letter but are
/// disambiguated by the modifier.
fn is_terminal_focus_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'t') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::CONTROL) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) && key.modifiers.contains(KeyModifiers::SHIFT)
}

/// `Cmd+W` (or legacy `Ctrl+Shift+W`): close the active terminal (no-op if
/// it's the only one). Plain `Ctrl+W` is intentionally excluded so the shell's
/// delete-word-backward keeps working; the close action requires either the
/// Super (Cmd) modifier or the Ctrl+Shift pair.
fn is_terminal_close_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'w') {
        return false;
    }
    let cmd_w =
        key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::META);
    let ctrl_shift_w = key.modifiers.contains(KeyModifiers::CONTROL)
        && key.modifiers.contains(KeyModifiers::SHIFT);
    cmd_w || ctrl_shift_w
}

/// `Cmd+]`: cycle to the next (right) terminal in the pane. iTerm2's
/// GlobalKeyMap forwards it as `ESC [ 93 ; 9 u` (modifier 9 = base +
/// Super), which crossterm decodes to `Char(']') + SUPER`. Brackets are
/// used because every arrow option is blocked: Ctrl+arrows by macOS
/// Spaces, Option+arrows by shell word-motion, Cmd+arrows by user choice.
/// Accepts the shifted glyph `}` defensively in case a terminal pre-applies
/// the shift.
fn is_terminal_cycle_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    (c == ']' || c == '}') && has_cmd(key.modifiers)
}

/// `Cmd+[`: cycle to the previous (left) terminal in the pane. Mirror of
/// `is_terminal_cycle_key` for the reverse direction.
fn is_terminal_cycle_back_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    (c == '[' || c == '{') && has_cmd(key.modifiers)
}

/// Returns true if the given key event should trash the currently-selected
/// node in the file tree. Recognises:
///
/// * `KeyCode::Delete` — the Forward-Delete key on full-size keyboards
///   (and `fn+Delete` on Mac laptops).
/// * `KeyCode::Backspace` — the key labeled "delete" on every Mac keyboard.
///   The tree pane has no text input that needs Backspace, so plain
///   Backspace is safe here.
/// * `Cmd+Backspace` — the macOS Finder gesture for trashing.
///
/// This helper is only called from `handle_tree_key`, so plain Backspace is
/// only swallowed when the tree pane has focus; the editor and terminal panes
/// continue to consume Backspace for their own purposes.
fn is_delete_node_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Delete | KeyCode::Backspace)
}

/// Returns true if the given key event should trigger "Save".
/// Recognises Ctrl+S (cross-platform) and Cmd/Super+S (macOS-style).
/// Case-insensitive on the letter so Shift+Ctrl+S also works.
fn is_word_continuation(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// Characters that open or advance a call, triggering parameter hints.
fn is_signature_help_trigger(c: char) -> bool {
    c == '(' || c == ','
}

/// Which starter contents to seed when a JSON config file is opened for the
/// first time from the palette.
#[derive(Debug, Clone, Copy)]
enum ConfigFileSeed {
    Settings,
    /// A settings overlay layer (#251): `.croft/config.json`, its gitignored
    /// `.local` sibling, or the machine-local user overlay. Seeded with a
    /// commented template rather than a full prefs dump — overlays should
    /// carry only the keys they actually set.
    SettingsLayer,
    Keybindings,
    Snippets,
    Triggers,
    Matchers,
    Agents,
}

/// Starter contents for a fresh settings overlay layer.
const SETTINGS_LAYER_TEMPLATE: &str = r#"{
  // A croft settings overlay: later layers win key-by-key over the user
  // config (see docs/SETTINGS.md for the chain, "extends", and platform
  // blocks). Workspace files may set appearance and editor/terminal
  // behavior keys only; trust-related settings are user-config only and
  // warn in OUTPUT · Settings.
}
"#;

/// Build a completion-popup item for a user snippet: the row shows the prefix,
/// filters on it, and carries the snippet body as `is_snippet` insertion text
/// the accept path expands through the editor's tab-stop engine.
fn snippet_completion_item(snip: &crate::snippets::Snippet) -> crate::lsp::CompletionItem {
    crate::lsp::CompletionItem {
        label: snip.prefix.clone(),
        detail: Some(String::from("snippet")),
        insert_text: Some(snip.body.clone()),
        filter_text: Some(snip.prefix.clone()),
        kind: Some(lsp_types::CompletionItemKind::SNIPPET),
        is_snippet: true,
    }
}

/// Which mouse region a binding's `when` context refers to, or `None` when
/// the pointer is somewhere no context covers (a panel, a seam, the status
/// bar) — a user binding must not fire there.
fn mouse_context_for(
    m: &MouseEvent,
    in_editor: bool,
    in_terminal: bool,
    in_tree: bool,
    app: &App,
) -> Option<crate::keymap::MouseContext> {
    use crate::keymap::MouseContext;
    // The tab strip has no focus notion, so it is recognised positionally and
    // checked first: it overlaps the editor pane's full area.
    if app.editor.tab_at(m.column, m.row).is_some() {
        return Some(MouseContext::TabStrip);
    }
    if in_terminal {
        return Some(MouseContext::Terminal);
    }
    // `in_tree` is true anywhere in the ACTIVE SIDEBAR, whichever view it is
    // showing, so it alone would make a `file_tree` binding fire over Search
    // results, the Remote list, the Testing panel and the commit graph. The
    // context is named for the file tree and documented as the file tree, so
    // it is narrowed to the view that actually is one; the other sidebar
    // views have their own row semantics and no binding context yet, and
    // firing a tree binding over them would act on a row it never meant.
    if in_tree && app.sidebar_view == SidebarView::Explorer {
        return Some(MouseContext::FileTree);
    }
    if in_editor {
        return Some(MouseContext::Editor);
    }
    None
}

/// The gesture a mouse event spells, or `None` for events that are not
/// bindable (motion, drags, button releases).
///
/// A left press reports `DoubleClick` when croft's own click tracker already
/// considers it one, so a binding agrees with the built-in select-word
/// behaviour rather than disagreeing about the same physical click. Triple
/// click is NOT reported: the tracker distinguishes single from double only,
/// and inventing a third level here would make `triple_click` bindings fire
/// on the second click. `Gesture::parse` therefore rejects it with a load
/// warning rather than accepting a binding that could never behave.
fn gesture_for(
    m: &MouseEvent,
    app: &App,
    ctx: crate::keymap::MouseContext,
    now: std::time::Instant,
) -> Option<crate::keymap::Gesture> {
    use crate::keymap::{Gesture, GestureKind, MouseContext};
    // Only the three modifiers a terminal actually reports for mouse; Super
    // is never present (see `Gesture::parse`).
    let mods = m.modifiers & (KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT);
    let kind = match m.kind {
        MouseEventKind::Down(MouseButton::Left) if !mods.is_empty() => {
            // A modified click reads its OWN tracker. The unmodified ones are
            // shared with built-ins that ignore modifiers, so the dispatch
            // deliberately never records a modified click into them — which
            // left `ctrl+double_click` unable to fire at all, since nothing
            // remembered the first click of the pair.
            if app.modified_click.is_double(now, m.column, m.row, mods) {
                GestureKind::DoubleClick
            } else {
                GestureKind::Click
            }
        }
        MouseEventKind::Down(MouseButton::Left) => {
            // The tracker has to match the region: each pane records into its
            // own, so consulting `editor_click` everywhere left `double_click`
            // permanently false in the tree, tab strip, and terminal — a
            // binding there would silently never match.
            let tracker = match ctx {
                MouseContext::Terminal => &app.terminal_click,
                MouseContext::FileTree => &app.tree_click,
                MouseContext::Editor => &app.editor_click,
                // The tab strip writes to no tracker of its own, so a double
                // there can only be seen because the dispatch itself records
                // into `editor_click` above. Sharing it with the editor body
                // is acceptable: a double needs both clicks within 500ms at
                // the SAME cell, and the strip and the body do not overlap.
                MouseContext::TabStrip => &app.editor_click,
            };
            // `mods` is empty in this arm by construction (the modified case
            // is matched above and reads its own tracker), and passing it
            // rather than a literal keeps that true if the guard ever moves:
            // #317 makes the built-in tracker refuse a modified pair, which is
            // exactly what should happen if a modified click ever reached here.
            if tracker.is_double(now, m.column, m.row, mods) {
                GestureKind::DoubleClick
            } else {
                GestureKind::Click
            }
        }
        MouseEventKind::Down(MouseButton::Middle) => GestureKind::MiddleClick,
        MouseEventKind::Down(MouseButton::Right) => GestureKind::RightClick,
        MouseEventKind::ScrollUp => GestureKind::WheelUp,
        MouseEventKind::ScrollDown => GestureKind::WheelDown,
        _ => return None,
    };
    Some(Gesture { kind, mods })
}

/// A chord eligible for a user rebind: it carries a real modifier
/// (Ctrl/Alt/Super) or is a function key. Bare keys, unmodified letters, and
/// Shift-only chords (which are just typing) are excluded so the user keymap
/// can never shadow plain text entry. Intentionally not named `is_*_key`: it is
/// a gate, not a shortcut the F1 overlay documents.
fn is_rebindable_chord(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(_))
        || key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
}

/// Whether a key should keep an active snippet tab-stop session alive: plain
/// typing (an unmodified char), Backspace, and Tab (which advances the session).
/// Every other key ends it so Tab reverts to indenting.
fn snippet_key_continues(key: KeyEvent) -> bool {
    match key.code {
        KeyCode::Tab | KeyCode::Backspace => true,
        KeyCode::Char(_) => !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER),
        _ => false,
    }
}

fn is_completion_trigger_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c != ' ' {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

fn is_save_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'s') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    let has_super = key.modifiers.contains(KeyModifiers::SUPER);
    let has_ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
    // Cmd+Shift+S is reserved for the Source Control jump
    // (`is_source_control_jump_key`), so reject Shift when Super is
    // held. Ctrl+Shift+S still triggers Save because some terminals
    // capitalise the letter when Ctrl is held and the user genuinely
    // means Ctrl+S — that's the existing `shift_ctrl_s_is_save_key`
    // contract we want to preserve.
    if has_super && has_shift {
        return false;
    }
    has_super || has_ctrl
}

/// Read the system clipboard. Used by the search input when Cmd+V arrives as
/// a key event rather than bracketed paste content.
fn read_system_clipboard() -> Option<String> {
    crate::clipboard::read_string()
}

/// Copy `text` to the host system clipboard.
///
/// Order of attempts:
///   1. **macOS native** — `clipboard::write_string` posts directly to
///      `NSPasteboard.generalPasteboard` (with `pbcopy` as a process-level
///      fall-back inside the same helper). This is the canonical Cocoa
///      clipboard API and is the *only* path that survives every iTerm2
///      configuration we have seen in the wild. OSC 52 is, empirically,
///      silently dropped by iTerm2 in some setups even with
///      `AllowClipboardAccess` enabled in `com.googlecode.iterm2` — and
///      writing escape bytes directly to the alt-screen stdout always
///      risks racing with the next ratatui frame.
///   2. **OSC 52 fall-back** — only if the native write returned false
///      (non-macOS croft binary on a Linux remote host, where the only
///      hand-shake with the user's local terminal is via escape bytes
///      through the SSH PTY). The fall-back is best-effort.
///
/// Returns true when the native path acknowledged the write so the call
/// site can downgrade the status message if it ever needs to. Today all
/// call sites discard the boolean; the return value is here so future
/// code can branch on it.
/// VS Code "Copy Relative Path" text: `path` relative to the workspace `root`,
/// or the absolute `path` when it lives outside the root (never a `../` walk).
/// Pure so the relativization is unit-tested without touching the clipboard.
fn relative_clipboard_text(path: &Path, root: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
}

/// The text a lane's Explorer root row wears after its name (#348): the
/// branch, then the seated agent as the pane pill shows it (`◆ claude ●`),
/// or the configured agent's bare name while nothing is seated yet, or
/// nothing more for a plain-shell lane.
fn lane_root_badge(
    branch: &str,
    seated: Option<&crate::agents::AgentLane>,
    configured: Option<&str>,
) -> String {
    match (seated, configured) {
        (Some(agent), _) => format!(
            "{branch} \u{b7} \u{25c6} {} {}",
            agent.name,
            agent.status.glyph()
        ),
        (None, Some(agent)) => format!("{branch} \u{b7} {agent}"),
        (None, None) => branch.to_string(),
    }
}

/// What a lane pane's fresh shell is fed to start its agent (#348):
/// Ctrl-E + Ctrl-U first, as `run_project_task` does, so a half-typed line
/// cannot concatenate with the command.
fn lane_launch_input(cmd: &str) -> String {
    format!("\x05\x15{cmd}\r")
}

/// Whether `t` is the idle pane named `pane_name` whose shell is standing
/// at `root` — or whose directory croft cannot read at all. The one
/// predicate behind every "reuse a pane rather than stack a new one"
/// decision (#430).
///
/// Shared deliberately. This guard existed as two copies, and when #392
/// fixed the runnable-fence copy the task copy kept both defects: a
/// `starts_with` that accepted any DESCENDANT, so a shell that had `cd`'d
/// into a subdirectory was reused and the command ran there; and an
/// `is_none_or` that opened the guard whenever the cwd could not be read.
/// One predicate means a future correction cannot land on one caller and
/// miss the other.
///
/// The comparison is exact on purpose. Both sides are resolved paths — the
/// kernel reports the shell's cwd fully resolved, and `canonicalize()`
/// resolves symlinks and never emits a trailing separator — so equality
/// holds wherever reuse is genuinely wanted, including through a
/// `/tmp` -> `/private/tmp` symlink. When it does not hold, the caller
/// opens a fresh pane at the right directory, so the worst case is a spare
/// pane rather than a command run somewhere the user was not told about.
///
/// When `canonicalize()` itself fails — a root deleted or renamed under a
/// live session — `unwrap_or` leaves an unresolved path and the comparison
/// cannot match, which costs a spare pane and never a misdirected command.
///
/// The cwd decision itself lives in [`cwd_matches`], which distinguishes a
/// shell that moved from a platform that cannot say where it is.
///
/// A DEAD shell never reaches that decision: `foreground_is_shell` is
/// checked first and answers false for one (#155), so the unreadable arm
/// only ever sees panes croft cannot ask about. Relaxing that check would
/// make identity-fallback start reusing corpses, so the two belong
/// together.
fn pane_is_idle_at(
    t: &crate::widgets::terminal::PtyTerminal,
    pane_name: &str,
    root: &Path,
) -> bool {
    t.label() == pane_name
        && t.foreground_is_shell()
        && cwd_matches(t.kernel_shell_cwd().as_deref(), root, cwd_is_observable())
}

use crate::widgets::terminal::cwd_is_observable;

/// The cwd half of [`pane_is_idle_at`], as a pure function so both arms are
/// testable on any platform (#430).
///
/// Three cases, not two. A cwd croft READ and that differs is a shell that
/// wandered off — refuse. A cwd croft read and that matches is this
/// command's pane — reuse. A cwd croft could not read splits on whether
/// the platform can read one at all: where it can, `None` is the failure
/// the guard exists for and stays closed; where it cannot (Android), a
/// closed guard would stack a new pane on every single run, so reuse falls
/// back to the pane's identity, which is all croft had before the guard
/// existed.
fn cwd_matches(cwd: Option<&Path>, root: &Path, observable: bool) -> bool {
    match cwd {
        Some(c) => c == root,
        None => !observable,
    }
}

fn copy_to_clipboard(text: &str) -> bool {
    if crate::clipboard::write_string(text) {
        return true;
    }
    use std::io::Write;
    let bytes = crate::widgets::terminal::osc52_copy_seq(text);
    let mut out = std::io::stdout();
    let _ = out.write_all(&bytes);
    let _ = out.flush();
    false
}

/// Returns true if the given key event should copy the editor's current
/// selection to the system clipboard. Recognises plain `Ctrl+C` and `Cmd+C`
/// — there's no SIGINT collision since the editor pane is not a shell.
fn is_editor_copy_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'c') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Cut: `Ctrl+X` / `Cmd+X`.
fn is_editor_cut_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'x') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Paste in the search input. Normal terminal paste is handled via
/// `Event::Paste`; `setup-iterm2` maps Cmd+V to a CSI-u Cmd+V sequence, and
/// the raw Ctrl+V byte is accepted as a fallback for older setups.
fn is_search_paste_key(key: KeyEvent) -> bool {
    is_clipboard_paste_key(key)
}

/// Human-readable name of a Search input field, for status-line messages.
fn search_field_name(field: crate::widgets::search::SearchField) -> &'static str {
    use crate::widgets::search::SearchField;
    match field {
        SearchField::Query => "search",
        SearchField::Replace => "replace",
        SearchField::Include => "files-to-include",
        SearchField::Exclude => "files-to-exclude",
    }
}

fn is_editor_paste_key(key: KeyEvent) -> bool {
    is_clipboard_paste_key(key)
}

fn is_clipboard_paste_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c == '\u{16}' {
        return true;
    }
    if !c.eq_ignore_ascii_case(&'v') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

fn is_search_editing_shortcut(key: KeyEvent) -> bool {
    is_search_paste_key(key)
        || is_editor_select_all_key(key)
        || is_editor_copy_key(key)
        || is_editor_cut_key(key)
}

/// Select-all: `Ctrl+A` / `Cmd+A`.
fn is_editor_select_all_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'a') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Undo: `Ctrl+Z` / `Cmd+Z`. Plain Shift is rejected so it stays distinct from
/// the redo chord `Shift+Cmd+Z` / `Shift+Ctrl+Z` (see `is_editor_redo_key`).
fn is_editor_undo_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'z') {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Redo: `Shift+Cmd+Z` / `Shift+Ctrl+Z` (VS Code's default). `Cmd+Y` is not a
/// redo alias here because it is already the `Cmd+y y` yank-line leader.
fn is_editor_redo_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'z') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}

/// Editor-pane Rename Symbol: plain `F2` (VS Code's binding). In the Explorer
/// tree the same key renames the selected file (`is_tree_rename_key`); the
/// pane in focus decides which fires.
fn is_rename_symbol_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(2))
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// True for `.ts`/`.tsx`/`.js`/`.jsx` paths — the languages served by the
/// croft-managed vtsls, used to re-open just those docs after vtsls installs.
/// Collapse a language to the server "family" it shares a managed server with.
/// vtsls serves the whole TypeScript/JS family but reports its config language
/// as `TypeScript`, so all four map together; every other language is its own
/// family. Used to decide which open docs to re-open after a managed install.
fn lsp_server_family(lang: crate::lsp::Language) -> crate::lsp::Language {
    lang.server_family()
}

/// True when `path`'s language is served by one of the just-installed servers,
/// so its LSP sync state should be dropped to force a re-open + re-probe.
fn just_installed_covers_path(installed: &[crate::lsp::Language], path: &Path) -> bool {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let Some(lang) = crate::lsp::Language::from_extension(ext) else {
        return false;
    };
    installed
        .iter()
        .any(|&i| lsp_server_family(i) == lsp_server_family(lang))
}

/// Editor-pane Change All Occurrences: `Cmd+F2` (macOS) or `Ctrl+F2` (Linux),
/// matching VS Code on each platform so local and remote behave identically.
/// iTerm2 may deliver Cmd folded onto the Meta/ALT bit (the same reason
/// Cmd+click arrives as ALT for go-to-definition), so any of SUPER / CONTROL /
/// ALT alongside F2 counts. Plain F2 (no modifiers) stays Rename Symbol.
fn is_change_all_occurrences_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(2))
        && (key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL)
            || key.modifiers.contains(KeyModifiers::ALT))
}

/// VS Code "Add Selection to Next Find Match" (`Cmd+D` on macOS, `Ctrl+D`
/// elsewhere). Neither Shift nor Alt may be held, so this never collides with
/// `Cmd+Shift+D` (Run and Debug) or `Cmd+Opt+Shift+D` (Sort Lines Descending).
fn is_select_next_occurrence_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char('d') | KeyCode::Char('D'))
        && (key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL))
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// VS Code "Delete Line" (`Cmd+Shift+K` on macOS, `Ctrl+Shift+K` elsewhere).
/// Requires Shift (to distinguish it from the `Cmd+K` chord leader) and no Alt.
fn is_delete_line_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char('k') | KeyCode::Char('K'))
        && (key.modifiers.contains(KeyModifiers::SUPER)
            || key.modifiers.contains(KeyModifiers::CONTROL))
        && key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// Editor-pane Go to Definition: plain `F12` (VS Code's binding). The F12
/// navigation family splits on the modifier, matching VS Code: bare F12 is
/// Definition, `Shift+F12` is Declaration, `Ctrl+F12` is Type Definition, and
/// `Cmd+F12` (SUPER) is Implementations. Definition therefore requires F12 with
/// none of Shift / Ctrl / Super held. (Alt is still accepted: iTerm2 can fold a
/// held Cmd onto the Meta/Alt bit for some events, and Option+F12 is otherwise
/// unused, so leaving Alt on Definition is harmless.)
fn is_go_to_definition_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(12))
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

/// Editor-pane Peek Definition: `Alt+F12`, VS Code's default (#115). This
/// claims the ALT bit Definition used to tolerate as iTerm2 Cmd-fold noise —
/// on those rare folded events the user now gets a peek popup instead of a
/// jump, strictly less disruptive than the old mis-jump.
fn is_peek_definition_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(12))
        && key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
}

/// Editor-pane Go to References: `Shift+F12`, VS Code's real binding for this
/// action. This is the chord croft previously gave to Go to Declaration; with
/// References taking its rightful VS Code default, Declaration moved one
/// modifier over to `Ctrl+Shift+F12`. References therefore requires F12 with
/// Shift held but neither Ctrl (that is Declaration) nor Super (Implementations).
fn is_go_to_references_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(12))
        && key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
}

/// Editor-pane Go to Declaration: `Ctrl+Shift+F12`. VS Code leaves Declaration
/// unbound, so croft assigns it within the F12 navigation family. It moved off
/// the bare `Shift+F12` it once held when Go to References (added later) claimed
/// that VS Code default, so Declaration now needs both Shift and Ctrl (Super
/// would be Implementations). iTerm2 emits `CSI 24 ; 6 ~` for Ctrl+Shift+F12,
/// which crossterm decodes to `F(12) + SHIFT + CONTROL`; `iterm2.rs` also
/// installs a defensive GlobalKeyMap forwarder emitting exactly those bytes so a
/// future iTerm2 default cannot swallow the chord.
fn is_go_to_declaration_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(12))
        && key.modifiers.contains(KeyModifiers::SHIFT)
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
}

/// Editor-pane Go to Type Definition: `Ctrl+F12`. VS Code leaves Type
/// Definition unbound, so croft assigns it within the F12 navigation family.
/// iTerm2 emits `CSI 24 ; 5 ~` for Ctrl+F12, which crossterm decodes to
/// `F(12) + CONTROL` (the same legacy-tilde path that delivers plain F12 and
/// Shift+F12), so no iTerm2 GlobalKeyMap forwarder is needed.
fn is_go_to_type_definition_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(12))
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
}

/// Editor-pane Go to Implementations: `Cmd+F12` (SUPER), VS Code's real macOS
/// binding for this action. Unlike its F12-family siblings, Cmd+F12 is captured
/// by macOS, so `iterm2.rs` installs a GlobalKeyMap forwarder emitting
/// `CSI 24 ; 9 ~`; crossterm decodes that to `F(12) + SUPER`. This must not
/// collide with the three siblings: bare F12 is Definition, `Shift+F12` is
/// Declaration, `Ctrl+F12` is Type Definition.
fn is_go_to_implementation_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::F(12))
        && key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
}

fn chord_status_text(op: char, count: usize) -> String {
    if count > 0 {
        format!("Pending: {op} (count {count})")
    } else {
        format!("Pending: {op}")
    }
}

fn is_vim_chord_letter(key: KeyEvent, letter: char) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c != letter {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}

fn is_vim_chord_g(key: KeyEvent) -> bool {
    is_vim_chord_letter(key, 'g')
}

fn is_vim_chord_y(key: KeyEvent) -> bool {
    is_vim_chord_letter(key, 'y')
}

fn is_vim_goto_bottom(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'g') {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}

fn chord_digit_value(key: KeyEvent) -> Option<usize> {
    let KeyCode::Char(c) = key.code else {
        return None;
    };
    let d = c.to_digit(10)? as usize;
    if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
        return None;
    }
    Some(d)
}

fn cmd_only_digit_value(key: KeyEvent) -> Option<usize> {
    let d = chord_digit_value(key)?;
    if !key.modifiers.contains(KeyModifiers::SUPER) {
        return None;
    }
    Some(d)
}

/// Cmd+E toggles native modal (vim) editing in the editor pane. A plain
/// Cmd+letter reaches croft reliably as SUPER (the same path as Cmd+S / Cmd+C),
/// unlike Option+letter which emits a glyph on macOS; and it stays out of the
/// Cmd+Shift+letter space reserved for activity-bar view jumps.
fn is_vim_toggle_key(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Char('e') | KeyCode::Char('E'))
        && key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
}

fn reverse_find(kind: crate::vim::FindKind) -> crate::vim::FindKind {
    use crate::vim::FindKind;
    match kind {
        FindKind::CharForward => FindKind::CharBackward,
        FindKind::CharBackward => FindKind::CharForward,
        FindKind::TillForward => FindKind::TillBackward,
        FindKind::TillBackward => FindKind::TillForward,
    }
}

/// Vertical / whole-file motions operate linewise under an operator (`dj`,
/// `dG`), unlike the charwise horizontal and word motions.
fn vim_motion_is_linewise(motion: crate::vim::Motion) -> bool {
    use crate::vim::Motion;
    matches!(
        motion,
        Motion::Up | Motion::Down | Motion::FileStart | Motion::FileEnd | Motion::GotoLine(_)
    )
}

/// `f`/`t`/`e` land on a char that the operator should include, so the
/// deletion range needs to extend one past the landing column.
fn vim_motion_is_forward_inclusive(motion: crate::vim::Motion) -> bool {
    use crate::vim::{FindKind, Motion};
    matches!(
        motion,
        Motion::WordEnd
            | Motion::Find(FindKind::CharForward, _)
            | Motion::Find(FindKind::TillForward, _)
    )
}

/// First char index `>= from` where `term` begins in `line`, comparing by
/// char (not byte) so the result indexes the editor's char-based cursor.
fn find_char_index(line: &str, term: &str, from: usize) -> Option<usize> {
    let chars: Vec<char> = line.chars().collect();
    let needle: Vec<char> = term.chars().collect();
    let tlen = needle.len();
    if tlen == 0 || chars.len() < tlen {
        return None;
    }
    (from..=chars.len() - tlen).find(|&i| chars[i..i + tlen] == needle[..])
}

/// Last char index `< limit` where `term` begins in `line`.
fn rfind_char_index(line: &str, term: &str, limit: usize) -> Option<usize> {
    let chars: Vec<char> = line.chars().collect();
    let needle: Vec<char> = term.chars().collect();
    let tlen = needle.len();
    if tlen == 0 || chars.len() < tlen {
        return None;
    }
    let upper = limit.min(chars.len() - tlen + 1);
    (0..upper).rev().find(|&i| chars[i..i + tlen] == needle[..])
}

fn is_plain_letter(key: KeyEvent, letter: char) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c != letter {
        return false;
    }
    !(key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER)
        || key.modifiers.contains(KeyModifiers::ALT))
}

fn is_editor_line_home_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'a') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

fn is_editor_line_end_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'e') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

fn is_editor_kill_to_eol_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'k') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

fn is_editor_kill_to_bol_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'u') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::ALT)
}

fn is_editor_open_line_below_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if c != 'o' {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}

/// Insert line above: `Cmd+Shift+Enter` (macOS) / `Ctrl+Shift+Enter` (Linux),
/// matching VS Code's `editor.action.insertLineBefore`. (Previously bound to
/// `Cmd+Shift+O`, which VS Code reserves for Go to Symbol; relocated to its
/// real chord so `Cmd+Shift+O` can open the symbol picker.)
fn is_editor_open_line_above_key(key: KeyEvent) -> bool {
    if !matches!(key.code, KeyCode::Enter) {
        return false;
    }
    if !key.modifiers.contains(KeyModifiers::SHIFT) {
        return false;
    }
    if key.modifiers.contains(KeyModifiers::ALT) {
        return false;
    }
    key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}

/// Close active tab: `Ctrl+W` / `Cmd+W`.
fn is_close_tab_key(key: KeyEvent) -> bool {
    let KeyCode::Char(c) = key.code else {
        return false;
    };
    if !c.eq_ignore_ascii_case(&'w') {
        return false;
    }
    key.modifiers.contains(KeyModifiers::CONTROL)
        || key.modifiers.contains(KeyModifiers::SUPER)
        || key.modifiers.contains(KeyModifiers::META)
}

/// Cmd+1..9 / Ctrl+1..9 — jump straight to that tab (1-based; returns the
/// 0-based index). Anything outside that range returns `None`.
fn jump_to_tab_index(key: KeyEvent) -> Option<usize> {
    let KeyCode::Char(c) = key.code else {
        return None;
    };
    if !key.modifiers.contains(KeyModifiers::SUPER)
        && !key.modifiers.contains(KeyModifiers::META)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
    {
        return None;
    }
    let d = c.to_digit(10)?;
    if !(1..=9).contains(&d) {
        return None;
    }
    Some((d - 1) as usize)
}

/// Map a screen row to the tree row that should be highlighted as a drop
/// target. Hovering a directory targets that directory; hovering a file
/// targets its parent directory (so dragging onto a file row drops the
/// payload as siblings of that file). Returns `None` when the pointer is
/// over empty tree space, when the row would be a no-op (hovering an
/// item that's part of the drag set), or when the resolved directory is
/// inside one of the dragged folders.
fn drag_target_index(
    tree: &crate::widgets::file_tree::FileTree,
    y: u16,
    drag_paths: &[PathBuf],
) -> Option<usize> {
    // The sticky band wins the row resolution: a drop on a pinned ancestor
    // targets THAT directory, not whatever row the band covers (#126 — files
    // used to land in the covered row's directory, silently).
    let idx = tree.sticky_row_at(y).or_else(|| tree.node_at_y(y))?;
    let node = tree.nodes.get(idx)?;
    let dir_idx = if node.is_dir {
        idx
    } else {
        let parent = node.path.parent()?;
        tree.index_of_dir(parent)?
    };
    let dir_path = tree.nodes.get(dir_idx)?.path.clone();
    for src in drag_paths {
        if crate::widgets::file_tree::is_descendant_or_same(&dir_path, src) {
            return None;
        }
        if let Some(parent) = src.parent()
            && parent == dir_path
            && drag_paths.len() == 1
        {
            // Dropping a single source onto its own parent is a no-op;
            // don't show a highlight so the user knows nothing will move.
            return None;
        }
    }
    Some(dir_idx)
}

fn drop_target_dir(tree: &crate::widgets::file_tree::FileTree, target_idx: usize) -> PathBuf {
    tree.nodes
        .get(target_idx)
        .map(|n| n.path.clone())
        .unwrap_or_else(|| tree.root.clone())
}

/// Parse a bracketed-paste payload that originated from a Finder-style
/// drag-and-drop into the host terminal. Returns the absolute existing
/// paths the user dropped, or an empty Vec when the payload is plain text
/// (in which case the caller falls back to the normal paste path). Each
/// candidate token survives only if it resolves to an existing absolute
/// path on disk, so a stray paste of "/usr/bin" worth of typed text still
/// behaves like text.
pub fn parse_dropped_paths(s: &str) -> Vec<PathBuf> {
    parsed_drop_tokens(s)
        .into_iter()
        .filter(|p| p.is_absolute() && p.exists())
        .filter(|p| !is_iterm2_inline_image_drop(p))
        .collect()
}

/// Parse a bracketed-paste payload as candidate filesystem paths WITHOUT
/// requiring the paths to exist on this machine. Used by the remote-
/// launched croft to recognise drops whose paths refer to files on the
/// user's local Mac, which the relay will fetch over scp.
pub fn parse_foreign_dropped_paths(s: &str) -> Vec<PathBuf> {
    parsed_drop_tokens(s)
        .into_iter()
        .filter(|p| p.is_absolute())
        .filter(|p| !is_iterm2_inline_image_drop(p))
        .collect()
}

/// True when every token in a bracketed-paste payload normalises to an absolute
/// path (and there is at least one). This is the signature of a genuine Finder
/// drag, which carries only the dragged file path(s). A real drag does NOT move
/// keyboard focus to the Explorer tree, so a focus-only gate silently dropped
/// every drag where the user had last clicked the terminal or editor. A text
/// paste that merely *contains* a path — a shell command like `cat /etc/hosts`,
/// a pasted code snippet — always has at least one non-path token, so it returns
/// false and is left to land as ordinary text rather than being hijacked into a
/// relay pull that has no local file to fetch.
fn is_pure_path_payload(s: &str) -> bool {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return false;
    }
    let tokens = shell_split_drop_payload(trimmed);
    if tokens.is_empty() {
        return false;
    }
    tokens.iter().all(|t| {
        normalise_dropped_token(t)
            .map(|p| p.is_absolute())
            .unwrap_or(false)
    })
}

/// True when the dropped path is iTerm2's temp file for an inline-image
/// drag. iTerm2 lets the user drag any OSC-1337 inline image out of the
/// terminal; on mouse-up it writes the image bytes to `$TMPDIR/iTerm2.<rand>.png`
/// and re-injects the path into the same terminal as a bracketed paste.
/// Croft renders the activity-bar icons, welcome wordmark, run-debug
/// hero, no-repo hero, and SSH empty-state hero as OSC-1337 image cells,
/// so a click-with-microdrag on any of those triggers iTerm2's drag-
/// handler and croft would otherwise open the resulting PNG as an image
/// preview tab or import it into the Explorer. Filtering these paths is
/// always safe — the user has no legitimate reason to drop iTerm2's own
/// temp image into croft, and matching by filename pattern is iTerm2-
/// specific enough that it cannot collide with real user assets.
fn is_iterm2_inline_image_drop(p: &Path) -> bool {
    let Some(name) = p.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    if !name.starts_with("iTerm2.") || !name.ends_with(".png") {
        return false;
    }
    let middle = &name["iTerm2.".len()..name.len() - ".png".len()];
    if middle.is_empty() || !middle.chars().all(|c| c.is_ascii_alphanumeric()) {
        return false;
    }
    // Defence in depth: only treat it as an iTerm2 drag artefact when
    // the file lives under a temp directory. macOS puts iTerm2's drag
    // temp under `/var/folders/.../TemporaryItems/` or `$TMPDIR`; both
    // resolve through `std::env::temp_dir()` ancestry. The starts_with
    // chain is forgiving because the path may be a symlinked variant
    // (e.g. `/private/var/...` vs `/var/...`).
    let parent = p.parent().unwrap_or(p);
    let parent_str = parent.to_string_lossy();
    parent_str.contains("/T/")
        || parent_str.contains("/TemporaryItems")
        || parent_str.starts_with("/tmp")
        || parent_str.starts_with("/var/folders")
        || parent_str.starts_with("/private/var/folders")
}

fn parsed_drop_tokens(s: &str) -> Vec<PathBuf> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Vec::new();
    }
    shell_split_drop_payload(trimmed)
        .into_iter()
        .filter_map(|raw| normalise_dropped_token(&raw))
        .collect()
}

/// Split a Finder / iTerm2 drag-drop payload into individual path tokens
/// the way a POSIX-ish shell would. Backslash escapes the next char (so
/// `\ ` keeps a literal space inside a filename); single- and double-
/// quoted runs stay intact; unescaped whitespace (space, tab, CR, LF)
/// separates tokens. Quote/backslash characters are *retained* in the
/// emitted token so downstream `normalise_dropped_token` can reuse its
/// existing un-escape + un-quote logic.
fn shell_split_drop_payload(s: &str) -> Vec<String> {
    let mut tokens: Vec<String> = Vec::new();
    let mut cur = String::new();
    let mut in_double = false;
    let mut in_single = false;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\\' && !in_single {
            // Carry the backslash and its escapee through verbatim;
            // `normalise_dropped_token` strips them later.
            cur.push('\\');
            if let Some(next) = chars.next() {
                cur.push(next);
            }
            continue;
        }
        if c == '"' && !in_single {
            in_double = !in_double;
            cur.push(c);
            continue;
        }
        if c == '\'' && !in_double {
            in_single = !in_single;
            cur.push(c);
            continue;
        }
        if (c == ' ' || c == '\t' || c == '\n' || c == '\r') && !in_single && !in_double {
            if !cur.is_empty() {
                tokens.push(std::mem::take(&mut cur));
            }
            continue;
        }
        cur.push(c);
    }
    if !cur.is_empty() {
        tokens.push(cur);
    }
    tokens
}

/// Strip surrounding quotes, decode `file://` URLs (with %xx escapes), and
/// unescape `\<space>` style backslash escapes that some shells / drag
/// sources produce. Anything that isn't a plausible filesystem path
/// returns None and is dropped by the caller.
fn normalise_dropped_token(raw: &str) -> Option<PathBuf> {
    let mut s = raw.trim().to_string();
    if (s.starts_with('"') && s.ends_with('"') && s.len() >= 2)
        || (s.starts_with('\'') && s.ends_with('\'') && s.len() >= 2)
    {
        s = s[1..s.len() - 1].to_string();
    }
    if let Some(rest) = s.strip_prefix("file://") {
        // Decode into BYTES and build the string once. A `%xx` escape is one
        // byte of a UTF-8 sequence, not a character; pushing it `as char`
        // read it as Latin-1 and opened a path that does not exist (#414).
        // A sequence that is not valid UTF-8 names no path this process can
        // open, so per this function's contract the token is dropped rather
        // than turned into a plausible-looking path of replacement
        // characters, which would pass every caller's "is this a path"
        // screen and open the wrong thing.
        let decoded = crate::shell_integration::percent_decode(rest.as_bytes());
        s = String::from_utf8(decoded).ok()?;
    }
    let mut unescaped = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\'
            && let Some(next) = chars.next()
        {
            unescaped.push(next);
            continue;
        }
        unescaped.push(c);
    }
    if unescaped.is_empty() {
        return None;
    }
    Some(PathBuf::from(unescaped))
}

/// Cap a string at `max` characters by inserting an ellipsis in the
/// end so the start (scheme/host) stays visible. No ellipsis marker anywhere in
/// croft, so overflow is cut plainly from the right rather than elided in the
/// middle. `max <= 8` returns the original.
fn truncate_for_display(s: &str, max: usize) -> String {
    if s.chars().count() <= max || max <= 8 {
        return s.to_string();
    }
    s.chars().take(max).collect()
}

fn append_to_relay_log(log_path: &Path, payload: &str) -> std::io::Result<()> {
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_path)?;
    f.write_all(payload.as_bytes())?;
    f.sync_data().ok();
    Ok(())
}

/// Map a screen cell to a sheet grid cell (#177) using the frame-truth
/// layout the render wrote: row from the vertical band, column by
/// walking the visible column widths from `scroll_col`.
fn sheet_cell_at(view: &crate::sheet::SheetView, col: u16, row: u16) -> Option<(usize, usize)> {
    let g = view.grid;
    if g.data_rows == 0 || row < g.data_top || row >= g.data_top + g.data_rows {
        return None;
    }
    let data = view.sheets.get(view.current_sheet)?;
    let r = data.scroll_row + (row - g.data_top) as usize;
    if r >= data.row_count() {
        return None;
    }
    if col < g.body_x {
        return None;
    }
    let mut x_off = 0u16;
    for (c, w) in data.col_widths.iter().enumerate().skip(data.scroll_col) {
        if x_off + w + 1 > g.body_w {
            break;
        }
        if col >= g.body_x + x_off && col < g.body_x + x_off + w {
            return Some((r, c));
        }
        x_off += w + 1;
    }
    None
}

/// Char-boundary helpers for the in-grid cell editor (#177): byte
/// cursor stepped to valid boundaries.
fn floor_char(s: &str, i: usize) -> usize {
    let mut i = i.min(s.len());
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

fn ceil_char(s: &str, i: usize) -> usize {
    let mut i = i.min(s.len());
    while i < s.len() && !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

/// Keep the selected cell visible: rows directly, columns by advancing
/// `scroll_col` until the cumulative widths place `cur_col` inside the
/// last painted body width (frame truth from the render).
fn sheet_follow_cursor(view: &mut crate::sheet::SheetView, idx: usize, visible: usize) {
    let body_w = view.grid.body_w.max(8) as usize;
    let Some(data) = view.sheets.get_mut(idx) else {
        return;
    };
    if data.cur_row < data.scroll_row {
        data.scroll_row = data.cur_row;
    } else if visible > 0 && data.cur_row >= data.scroll_row + visible {
        data.scroll_row = data.cur_row + 1 - visible;
    }
    if data.cur_col < data.scroll_col {
        data.scroll_col = data.cur_col;
    } else {
        // Advance until the cursor column's right edge fits.
        while data.scroll_col < data.cur_col {
            let used: usize = data.col_widths[data.scroll_col..=data.cur_col]
                .iter()
                .map(|&w| w as usize + 1)
                .sum();
            if used <= body_w {
                break;
            }
            data.scroll_col += 1;
        }
    }
}

fn sheet_visible_rows(inner: Rect) -> usize {
    // Renderer reserves 1 row for the header line, 1 row for the column
    // labels, and 1 row for the bottom status. Anything left is data.
    inner.height.saturating_sub(3) as usize
}

/// Whether a semantic-token reply may be applied, given the newest request
/// generation already applied for that path. Replies for one path overlap:
/// `sync_lsp` and a server-driven refresh can both have a full request in
/// flight at the same `seq`, and the request's retry loop emits an EMPTY
/// batch once its backoff is exhausted. Without this ordering check a late
/// empty loser blanks a good overlay and — being `is_full` — is persisted to
/// the content-keyed cache and replayed on every future open.
fn semantic_reply_is_current(seen: Option<u64>, incoming: u64) -> bool {
    seen.is_none_or(|s| incoming >= s)
}

/// The absolute (line, char column) a screen cell lands on in a rendered log
/// body. The body starts one row below the header and the view scrolls by
/// whole lines, so the mapping is a straight offset.
///
/// A cell is mapped back to a character through the same `CellMap` the
/// renderer painted with (#404): a double-width character is two cells and
/// one column, and a click on either half is a click on that character.
/// The two must move together; a mapping that measured width differently
/// from the painter would disagree with what is actually on screen.
fn log_cell_at(
    log: &crate::log_view::LogView,
    scroll: usize,
    col: u16,
    row: u16,
) -> (usize, usize) {
    let body = log.last_body;
    let line = (scroll + row.saturating_sub(body.y) as usize).min(log.len().saturating_sub(1));
    let cell = col.saturating_sub(body.x);
    // Clamp the COLUMN to the line's own length, not just the line to the
    // file's. The renderer paints to the endpoint it is given while the copy
    // reads `min(len)`, so an unclamped column let a drag past the end of a
    // short line paint sixty cells and copy three characters. Clamping here
    // means both readers see one value rather than each clamping its own way.
    // `char_at_cell` already answers the character count for a cell past
    // the end, which is that clamp.
    //
    // A line outside the parsed window has no text to map through; the raw
    // cell stands as the column, which is what the old behaviour was
    // everywhere.
    let column = log
        .visible_text(line)
        .map(|t| crate::cell_map::CellMap::new(t).char_at_cell(cell))
        .unwrap_or(cell as usize);
    (line, column)
}

/// Create `dir` (0700) if needed and write `contents` to `file` (0600). On
/// non-unix hosts the modes do not exist and the plain write is used.
fn write_private(dir: &Path, file: &Path, contents: &str) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
        // `recursive` also creates any missing parent (`~/.cache/croft`
        // itself on a first run) at 0700. Its other tenants are `sessions/`
        // (session.rs), `tmp/` (pdf.rs) and the MCP registry cache
        // (registry_index.rs), every one of them private per-user state
        // that gains nothing from a wider parent.
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(dir)?;
        // A pre-existing dir is tightened, a link is refused: `create` adopts
        // an existing symlink to a dir, `symlink_metadata` reports the link's
        // own mode (always loose), and `set_permissions` follows the link, so
        // without this check a scrollback dir pointed at any dir the user
        // owns would silently re-mode that dir on the first dump.
        let meta = std::fs::symlink_metadata(dir)?;
        if meta.file_type().is_symlink() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!(
                    "{} is a symlink; refusing to write through it",
                    dir.display()
                ),
            ));
        }
        if meta.permissions().mode() & 0o077 != 0 {
            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
        }
        // The same for the file: `create(true).truncate(true)` follows a link
        // planted where the dump goes, and the chmod below would re-mode its
        // target after the truncate had emptied it. The dir is 0700, so the
        // planter is this user's own tooling or a restored backup, and the
        // answer is still a refusal rather than a destroyed file.
        if let Ok(fmeta) = std::fs::symlink_metadata(file)
            && fmeta.file_type().is_symlink()
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!(
                    "{} is a symlink; refusing to write through it",
                    file.display()
                ),
            ));
        }
        // `O_NOFOLLOW` makes the open itself refuse a link, so a link swapped
        // in between the check above and this open cannot be followed either
        // (the same pair config_layers.rs uses); the check above only buys
        // the clearer error. `mode` applies on creation alone, hence the
        // chmod below for a file left by an earlier dump.
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true).create(true).truncate(true).mode(0o600);
        opts.custom_flags(libc::O_NOFOLLOW);
        let mut f = opts.open(file)?;
        f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
        f.write_all(contents.as_bytes())
    }
    #[cfg(not(unix))]
    {
        std::fs::create_dir_all(dir)?;
        std::fs::write(file, contents)
    }
}

/// Remove the dumps under `dir` whose croft process is gone. A dump is named
/// `<pane>-<pid>-<uid>-scrollback.log` and is overwritten only by the process
/// that wrote it, so every exited croft would otherwise leave its dumps
/// behind for good, each the size of a pane's scrollback; the other cache
/// dirs here all bound themselves the same way. Anything not shaped like a
/// dump is left alone, and so is every live process's file.
fn reap_dead_scrollback_dumps(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    let me = std::process::id();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(stem) = name
            .to_str()
            .and_then(|n| n.strip_suffix("-scrollback.log"))
        else {
            continue;
        };
        // `<pane>-<pid>-<uid>`, read from the right since a pane label may
        // itself contain dashes.
        let mut parts = stem.rsplitn(3, '-');
        let (Some(_uid), Some(pid), Some(_pane)) = (parts.next(), parts.next(), parts.next())
        else {
            continue;
        };
        let Ok(pid) = pid.parse::<u32>() else {
            continue;
        };
        if pid != me && !process_is_alive(pid) {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// Whether a process with `pid` exists. Signal 0 delivers nothing and only
/// checks; a process this user may not signal still exists, so `EPERM`
/// reads as alive. Off unix nothing is reaped, on the conservative side.
/// Existence, not liveness, is enough here (unlike `session::is_alive`,
/// which probes by connecting): a pid that was reused reads as alive and
/// only leaks a file, and every wrong answer this can give errs that way.
#[cfg(unix)]
fn process_is_alive(pid: u32) -> bool {
    let Ok(pid) = libc::pid_t::try_from(pid) else {
        return true;
    };
    // SAFETY: `kill` with signal 0 only checks for the process; no signal is
    // delivered and no memory is touched.
    if unsafe { libc::kill(pid, 0) } == 0 {
        return true;
    }
    std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

#[cfg(not(unix))]
fn process_is_alive(_pid: u32) -> bool {
    true
}

/// Whether a scrollback dump goes to the rendered log view or to the plain
/// scratch buffer (#257). Must agree with the open path's own sniff, which
/// reads only the first 8 KiB of the file: a dump this says is a log but the
/// sniff says is text would open as an editable file full of raw escapes.
fn scrollback_opens_as_log(rows: &[String]) -> bool {
    // The same 8 KiB the file sniff reads, over the same bytes it will read.
    let mut prefix = String::new();
    for row in rows {
        if prefix.len() >= 8192 {
            break;
        }
        prefix.push_str(row);
        prefix.push('\n');
    }
    let cut = prefix.floor_char_boundary(prefix.len().min(8192));
    crate::ansi_text::looks_like_ansi(&prefix[..cut])
}

fn rect_contains(r: Rect, x: u16, y: u16) -> bool {
    r.width > 0 && r.height > 0 && x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
}

/// Push a log-highlight setting into the log view's process-wide opening
/// default (#466), from the toggle and from a settings remerge.
pub(crate) fn seed_log_highlight_default(on: bool) {
    crate::log_view::set_default_highlight(on);
}

/// The startup seed of that default from the saved preference (#466). In
/// the shipped binary it is the same write; under test it RECORDS the value
/// per thread instead, because the suite builds hundreds of apps on
/// parallel threads and each write would race the tests that read the
/// process-wide default. The record keeps the call site observable: a test
/// asserts what `App::new` decided to seed, not merely that a setter sets.
#[cfg(not(test))]
fn seed_log_highlight_default_at_startup(on: bool) {
    crate::log_view::set_default_highlight(on);
}

#[cfg(test)]
thread_local! {
    /// What the most recent `App::new` on this thread would have seeded.
    pub(crate) static STARTUP_LOG_HIGHLIGHT_SEED: std::cell::Cell<Option<bool>> =
        const { std::cell::Cell::new(None) };
}

#[cfg(test)]
fn seed_log_highlight_default_at_startup(on: bool) {
    STARTUP_LOG_HIGHLIGHT_SEED.with(|cell| cell.set(Some(on)));
}

/// Build the up-to-date version of an open diff view from its recorded
/// source (#471), or `None` when there is nothing new to build: a `Static`
/// view, a file-backed view whose sides have not moved on disk, a git-command
/// view on a filesystem-only trigger, or a side that can no longer be read
/// (the reader keeps the last good view). The result carries fresh disk
/// stamps but none of the reader's view state; `DiffData::carry_view_from`
/// adds that.
fn rebuild_diff_view(
    old: &crate::widgets::diff::DiffData,
    git_too: bool,
    heads_moved: &[PathBuf],
    touched: &[PathBuf],
) -> Option<crate::widgets::diff::DiffData> {
    use crate::widgets::diff::{DiffData, DiffSource, GitDiffKind};
    // A side the watcher just reported written, matched on the canonical
    // path so a symlinked root cannot hide it. Bypasses the stamp gate.
    let written = |side: &Path| {
        if touched.is_empty() {
            return false;
        }
        let canon = std::fs::canonicalize(side).unwrap_or_else(|_| side.to_path_buf());
        touched.iter().any(|t| *t == canon || t == side)
    };
    let lines = |t: &str| -> Vec<String> { t.lines().map(str::to_string).collect() };
    let two_sided = |left_text: &str, right_text: &str| {
        DiffData::build_with_byte_check(
            old.left_path.clone(),
            old.right_path.clone(),
            lines(left_text),
            lines(right_text),
            Some(left_text),
            Some(right_text),
        )
    };
    let mut fresh = match &old.source {
        DiffSource::Static => return None,
        DiffSource::HeadVsWorking { root, rel } => {
            // Canonical on both sides: git canonicalises `--show-toplevel`
            // (macOS's /tmp -> /private/tmp), while a root the app carries
            // as typed may not be, so the same repository can be spelled two
            // ways between the tag and the drain's record.
            let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
            let head_moved = git_too
                && heads_moved
                    .iter()
                    .any(|r| r == root || canon(r) == canon(root));
            if !head_moved && !written(&old.right_path) && !old.sides_moved_on_disk() {
                return None;
            }
            let head = crate::git::read_file_at_head(root, rel).ok()?;
            let right = std::fs::read_to_string(&old.right_path).ok()?;
            two_sided(&head, &right)
        }
        DiffSource::FixedLeft { left_text } => {
            if !written(&old.right_path) && !old.sides_moved_on_disk() {
                return None;
            }
            let right = std::fs::read_to_string(&old.right_path).ok()?;
            two_sided(left_text, &right)
        }
        DiffSource::TwoFiles => {
            if !written(&old.left_path) && !written(&old.right_path) && !old.sides_moved_on_disk() {
                return None;
            }
            let left = std::fs::read_to_string(&old.left_path).ok()?;
            let right = std::fs::read_to_string(&old.right_path).ok()?;
            DiffData::build(
                old.left_path.clone(),
                old.right_path.clone(),
                lines(&left),
                lines(&right),
            )
        }
        DiffSource::GitCommand { root, kind } => {
            if !git_too {
                return None;
            }
            let raw = match kind {
                GitDiffKind::Staged => crate::git::diff_staged(root),
                GitDiffKind::AgainstBranch(branch) => crate::git::diff_against_branch(root, branch),
                GitDiffKind::PreviousCommit => crate::git::diff_previous_commit(root),
            }
            .ok()?;
            DiffData::build_side_by_side_from_git_text(old.left_path.clone(), &raw)
        }
    };
    fresh.source = old.source.clone();
    fresh.left_is_real_file = old.left_is_real_file;
    fresh.stamp_sides();
    Some(fresh)
}

/// Fold a mouse event's Shift/Alt/Ctrl state into the form `report_mouse`
/// wants, so a forwarded wheel notch or left-button event carries the same
/// modifiers the child would have seen natively.
fn mouse_mods(m: &MouseEvent) -> MouseMods {
    MouseMods {
        shift: m.modifiers.contains(KeyModifiers::SHIFT),
        alt: m.modifiers.contains(KeyModifiers::ALT),
        ctrl: m.modifiers.contains(KeyModifiers::CONTROL),
    }
}

/// The SGR prefix (reset + truecolor fg/bg) for one ratatui cell, used when
/// blitting a buffer region straight to the terminal in
/// `flush_tooltip_over_image`. The tooltip only uses RGB and reset colors, so
/// other `Color` variants fall through to the terminal default.
fn sgr_for_cell(cell: &ratatui::buffer::Cell) -> String {
    let mut s = String::from("\x1b[0m");
    if let Color::Rgb(r, g, b) = cell.fg {
        s.push_str(&format!("\x1b[38;2;{r};{g};{b}m"));
    }
    if let Color::Rgb(r, g, b) = cell.bg {
        s.push_str(&format!("\x1b[48;2;{r};{g};{b}m"));
    }
    s
}

/// True when two cell rectangles share at least one cell. Used to decide
/// whether a text overlay (the chrome tooltip) lands on top of an OSC-1337
/// inline image; since terminal images composite ABOVE text cells, the
/// overlapping tooltip must be re-painted last to win those cells.
fn rects_intersect(a: Rect, b: Rect) -> bool {
    a.width > 0
        && a.height > 0
        && b.width > 0
        && b.height > 0
        && a.x < b.x.saturating_add(b.width)
        && b.x < a.x.saturating_add(a.width)
        && a.y < b.y.saturating_add(b.height)
        && b.y < a.y.saturating_add(a.height)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunSpec {
    pub program: String,
    pub args: Vec<String>,
    pub cwd: PathBuf,
}

/// Walk from `start` up to and including `workspace_root` looking for a
/// venv-style Python interpreter. Returns `(interpreter_path, owning_dir)`
/// where `owning_dir` is the directory that contains the venv folder — the
/// natural cwd for the run.
///
/// The walk stops at `workspace_root`: a venv that lives ABOVE the workspace
/// would belong to a different project the user has not opened, and using it
/// silently would surprise them.
fn find_python_venv(start: &Path, workspace_root: &Path) -> Option<(PathBuf, PathBuf)> {
    let mut probe = start.to_path_buf();
    loop {
        for venv_name in [".venv", "venv", ".env"] {
            let py = probe.join(venv_name).join("bin").join("python");
            if py.is_file() {
                return Some((py, probe));
            }
        }
        if probe == workspace_root {
            return None;
        }
        match probe.parent() {
            Some(parent) if parent != probe => {
                if !parent.starts_with(workspace_root) && parent != workspace_root {
                    return None;
                }
                probe = parent.to_path_buf();
            }
            _ => return None,
        }
    }
}

const TERMINAL_ADD_LABEL: &str = " + ";
const TERMINAL_CLOSE_LABEL: &str = " - ";
/// Codicon chevron-down, matching the OUTPUT dropdown caret. Opens the terminal
/// profile picker (VS Code's `∨` beside `+`).
const TERMINAL_PROFILE_LABEL: &str = " \u{eab4} ";
/// Codicon screen-full (Nerd Fonts `cod-screen_full` = U+EB4C): maximize this
/// terminal pane across the panel, parking the other panes in the right rail.
const TERMINAL_MAX_LABEL: &str = " \u{eb4c} ";
/// Codicon screen-normal (Nerd Fonts `cod-screen_normal` = U+EB4D): restore
/// the even split. Swapped in for the `⛶` while a pane is maximized.
const TERMINAL_RESTORE_LABEL: &str = " \u{eb4d} ";
/// Codicon chevron-left (Nerd Fonts `cod-chevron_left` = U+EAB5): fold this
/// pane to a strip and hand its width to the panes still expanded (#313).
///
/// Its own button rather than a new meaning for `-`: `-` closes, and it goes
/// on closing. A control that destroys on one build and folds on the next is
/// the kind of change muscle memory finds out the hard way.
const TERMINAL_COLLAPSE_LABEL: &str = " \u{eab5} ";
/// Codicon chevron-right (U+EAB6), on the header row of a collapsed pane's
/// strip: the way back out. It points the opposite way to the button that put
/// the pane there, which is the whole of the affordance in one column.
const TERMINAL_EXPAND_GLYPH: char = '\u{eab6}';
/// Stands in for a character too wide for the one column a strip owns. A
/// CJK glyph or an emoji is two cells and would paint over the pane next
/// door; dropping it outright left a pane named entirely in them with a
/// blank strip, which is the one thing the strip exists to prevent.
const TERMINAL_STRIP_WIDE_STANDIN: char = '\u{b7}';
/// A collapsed pane's entire width: one column, carrying the expand chevron
/// and the pane's name set vertically.
const TERMINAL_STRIP_W: u16 = 1;
/// Codicon terminal (Nerd Fonts `cod-terminal` = U+EA85), leading each
/// maximize-rail row the way VS Code's terminal tabs list does.
/// Cells the pane's header buttons occupy, measured in from its right edge:
/// `‹`, `⛶`, `-`, `∨` and `+` at three each, plus the one blank column right
/// of `+`. The name pill paints after the buttons and would win the shared
/// cells, so it is clipped to the width left of this strip.
/// `a_long_pane_label_never_overpaints_the_maximize_button` pins it, so adding
/// a SIXTH button fails a test rather than quietly erasing a glyph again -
/// which is how the collapse button (#313) was caught needing this widened
/// from 13 instead of silently sharing the pill's cells.
const TERMINAL_BUTTON_STRIP_W: u16 = 16;
/// Width constraints for the terminal row, given which panes are collapsed
/// (#313).
///
/// A collapsed pane keeps a one-column strip; the panes still expanded divide
/// everything left over. Split out as a pure function of the flags because
/// the apportioning is the whole of the layout risk here, and this way it is
/// asserted directly - a constraint vector measured against expected widths -
/// rather than only through a rendered frame.
///
/// `Fill` rather than `Ratio` for the expanded panes: `Ratio(1, k)` is a
/// share of the WHOLE row, so mixing it with the strips' `Length(1)` asks the
/// solver for more columns than exist and it settles that overflow by shaving
/// the panes. `Fill` divides what the strips leave, which is the arithmetic
/// actually wanted.
///
/// With nothing collapsed every pane is `Fill(1)`, which apportions the row
/// evenly - the same split as before the feature existed, so the common case
/// pays nothing for it.
///
/// Every pane collapsed is unreachable through the UI ([`App::toggle_terminal_collapse`]
/// and [`App::close_terminal_at`] both keep one expanded), but it is answered
/// here rather than left to divide by zero.
fn terminal_pane_constraints(collapsed: &[bool]) -> Vec<Constraint> {
    let any_expanded = collapsed.iter().any(|c| !c);
    collapsed
        .iter()
        .map(|&c| {
            if c && any_expanded {
                Constraint::Length(TERMINAL_STRIP_W)
            } else {
                Constraint::Fill(1)
            }
        })
        .collect()
}

const TERMINAL_RAIL_ICON: char = '\u{ea85}';
/// How many label characters a rail row shows. Fixed and deliberately tiny:
/// the rail is a switcher, not a directory, so four letters identify a pane.
const TERMINAL_RAIL_LABEL_W: u16 = 4;
/// The rail's fixed total width: leading space + icon + gap + the 4 label
/// characters. The rail never grows past this, whatever the names are.
const TERMINAL_RAIL_W: u16 = 3 + TERMINAL_RAIL_LABEL_W;

/// True when croft was invoked over an SSH login (or otherwise inside a
/// remote shell). Used to throttle PTY-driven redraws further so the SSH
/// pipe never saturates and starves input handling on the same thread.
fn is_remote_session() -> bool {
    std::env::var_os("SSH_CONNECTION").is_some()
        || std::env::var_os("SSH_TTY").is_some()
        || std::env::var_os("SSH_CLIENT").is_some()
}

/// Status-line advisory for a remote croft session that will not survive an
/// SSH transport drop. `croft remote` launches the remote croft under dtach
/// and exports `CROFT_SESSION_PERSISTENT=1`; when that marker is absent on a
/// remote (SSH) session the host has no dtach, so croft tells the user how to
/// turn persistence on. Local sessions never see it. Returned as a status
/// string only (the bottom line is info-only; no input).
fn remote_persistence_status(is_remote: bool, persistent: bool) -> Option<&'static str> {
    if is_remote && !persistent {
        Some("Persistence off: install dtach")
    } else {
        None
    }
}

/// Test-only redirect for [`croft_cache_dir`], so the relay tests steer the
/// relay rendezvous without repointing the process-global `$HOME` (#37):
/// every concurrent test thread resolves `$HOME` at call time (the PDF
/// rasteriser's scratch dir, the session paths), and a substituted value
/// leaking across threads made unrelated tests fail inside the fake home.
#[cfg(test)]
pub static CACHE_DIR_OVERRIDE_FOR_TEST: std::sync::Mutex<Option<PathBuf>> =
    std::sync::Mutex::new(None);

/// The user's `triggers.json`, with the built-in secret redactions in front
/// of it when redaction is on (#360).
fn load_trigger_set(redact_secrets: bool) -> std::sync::Arc<crate::triggers::TriggerSet> {
    let set = crate::triggers::TriggerSet::load(&crate::triggers::triggers_path());
    std::sync::Arc::new(if redact_secrets {
        set.with_builtin_redactions()
    } else {
        set
    })
}

/// What the `.http` worker hands back (#370): the file it ran from, the
/// RAW request line (variables unresolved, so a secret can never land in a
/// status line, history entry, or response tab through it), and the result.
struct HttpRunOutcome {
    file: PathBuf,
    raw_line: String,
    result: Result<crate::http_file::HttpResponse, String>,
}

/// Bind the `croft view` socket and put it in the mode the frame loop needs.
///
/// Split out so the tests seat a listener through the SAME function rather
/// than building one themselves. A test that set `set_nonblocking` itself
/// would be asserting against its own setup: production could drop the call
/// and the "the drain does not block" test would still pass, which is a
/// check that cannot fail.
fn prepare_view_listener(path: &Path) -> std::io::Result<std::os::unix::net::UnixListener> {
    let listener = crate::session::bind_socket_0600(path)?;
    // Polled from the frame loop, so a blocking accept would stall every
    // redraw until somebody happened to run `croft view`.
    listener.set_nonblocking(true)?;
    Ok(listener)
}

/// Why the `croft view` socket could not be bound, if it could not.
///
/// A `static` because `bind_view_socket` runs before an `App` exists to hold
/// it: `App::new` reads it once, right after the call, and puts it on the
/// status line.
static VIEW_BIND_ERROR: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

/// The status line a fresh `App` opens on, given whatever `bind_view_socket`
/// latched (#362).
///
/// Split out so it can be tested at all: `bind_view_socket` returns early
/// under `cfg(test)`, so nothing in the suite reaches the latch, and the arm
/// that reports a bind failure was the half that had never once run.
fn view_status(view_bind_error: Option<&str>) -> String {
    match view_bind_error {
        // The one startup failure that would otherwise be invisible until a
        // user ran `croft view` and got told to do what they were doing.
        Some(e) => format!("croft view is unavailable: {e}"),
        None => String::from("Ready"),
    }
}

/// Remove `view-<pid>-<nonce>.sock` files whose croft is gone (#362).
///
/// A Unix socket is not auto-unlinked, so every croft that dies leaves its
/// file behind. An `impl Drop` would clean up the tidy exits and none of the
/// others (a SIGKILL, an OOM kill, a panic in another thread), and those are
/// exactly the cases that litter, so the sweep is the mechanism that has to
/// exist and Drop would only duplicate its easy half.
///
/// Liveness is judged from the PID IN THE NAME rather than by connecting.
/// A connect probe races a concurrent bind: the other croft can be between
/// `bind_socket_0600`'s stale-file removal and its `bind`, where the probe
/// reads "dead" correctly and the unlink then lands on the socket it creates
/// a moment later. `kill(pid, 0)` has no such window. The cost is that a
/// recycled PID keeps one dead file indefinitely, which is a stale byte
/// rather than a stolen socket.
pub(crate) fn sweep_dead_view_sockets(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    // Listed once. `sweep_dead_bind_stages` runs per dead socket and used to
    // re-read the directory each time.
    let names: Vec<(String, PathBuf)> = entries
        .flatten()
        .filter_map(|e| Some((e.file_name().to_str()?.to_string(), e.path())))
        .collect();
    let me = std::process::id();
    for (name, entry_path) in &names {
        // A croft that died between `bind_socket_0600`'s lock creation and its
        // rename leaves a `.bind.lock` with no socket beside it. The
        // socket-keyed pass below can never reach one, because
        // `pid_of_socket` requires the `.sock` suffix, so those leaked
        // permanently. Judging the lock by the pid in its own name closes it.
        let sock_name = match name.as_str().strip_suffix(".bind.lock") {
            Some(stem) => std::borrow::Cow::Owned(format!("{stem}.sock")),
            None => std::borrow::Cow::Borrowed(name),
        };
        let Some(pid) = crate::view_ipc::pid_of_socket(&sock_name) else {
            continue;
        };
        // Signal 0 checks existence and permission without delivering
        // anything; ESRCH is the only answer that means "gone".
        let gone = pid != me
            && unsafe { libc::kill(pid as libc::pid_t, 0) } != 0
            && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
        if gone {
            let _ = std::fs::remove_file(entry_path);
            // `bind_socket_0600` binds inside a `.s<pid>-<n>` dir and removes
            // it on both paths, but a croft killed inside that window strands
            // one, and nothing else ever looks at it again. Same argument as
            // the orphan lock below: it is litter only this sweep can reach.
            sweep_dead_bind_stages(&names, pid);
            // Derived from the SOCKET's name rather than from this entry's,
            // so sweeping a lock entry does not compose a second suffix onto
            // itself. Removing both from either entry is idempotent.
            let _ = std::fs::remove_file(dir.join(sock_name.as_ref()).with_extension("bind.lock"));
        }
    }
    sweep_staged_stdin(dir);
}

/// Remove `.s<pid>-<n>` bind staging directories belonging to a dead croft.
///
/// `crate::session::bind_socket_0600` creates one, binds inside it, renames
/// the socket out and removes the directory on both the success and failure
/// paths. A croft killed between the create and the remove strands it, and
/// the counter in that function restarts with the process, so the name is
/// reused rather than accumulating without bound - but the stranded directory
/// is never revisited by anything else.
///
/// Keyed on the same pid the socket sweep just judged dead, so a LIVE croft's
/// staging directory is never touched: removing one mid-bind would take the
/// socket it is about to rename out with it. "Never" modulo the pid-recycling
/// window the socket unlink above already accepts, which needs the pid space
/// to wrap between the `kill` and the removal.
///
/// Takes the directory listing rather than reading it: this is called once per
/// dead socket, and a cache dir holding N stale sockets was costing N full
/// listings at launch.
fn sweep_dead_bind_stages(names: &[(String, PathBuf)], pid: u32) {
    let prefix = format!(".s{pid}-");
    for (name, path) in names {
        if name.starts_with(&prefix) && name[prefix.len()..].parse::<u64>().is_ok() {
            let _ = std::fs::remove_dir_all(path);
        }
    }
}

/// How long a staged stdin file outlives the pipe that wrote it (#362).
///
/// Generous, because the cost of keeping a file too long is disk and the cost
/// of dropping one too early is a broken tab. It still bounds the pile: the
/// module's own rationale names `vault read … | croft view -`, and without any
/// sweep every such pipe left a permanent copy on disk the user was never told
/// about.
const STAGED_STDIN_RETENTION: std::time::Duration = std::time::Duration::from_secs(60 * 60 * 24);

/// Drop staged stdin that no live croft holds and that has aged out (#362).
///
/// TWO signals, and the order matters: a live holder spares a file at any age,
/// and age only ever reaches files nobody holds.
///
/// Age alone was the whole mechanism, for a reason that still stands as far as
/// it goes. `stage_stdin` runs inside [`crate::view_ipc::run`] - the
/// short-lived `croft view` CLIENT process, which exits milliseconds later —
/// so the pid baked into every staged name belongs to something that is always
/// already dead. A liveness check therefore matched EVERY staged file,
/// including one a running croft had open in a tab, and launching a second
/// croft deleted it. That is not litter: `sqlite_view::table_page` re-opens the
/// file by path on every page turn, so the tab breaks on the next page.
///
/// But age alone still deleted a file a croft was showing, once that session
/// outlived the window: `sqlite_view::table_page` re-opens by path on every
/// page turn, so the tab breaks, and piped input cannot be regenerated by
/// re-running anything. So the SERVER stamps its pid into the name when it
/// opens the file ([`crate::view_ipc::claim_staged`]), which is the one point
/// where a live holder is known, and this reads it back.
///
/// Runs at launch, from `sweep_dead_view_sockets`, so a file staged inside a
/// long-lived session survives until the next croft starts, and now survives
/// that too for as long as its holder is running.
fn sweep_staged_stdin(dir: &Path) {
    let staged = dir.join("view-stdin");
    let Ok(entries) = std::fs::read_dir(&staged) else {
        return;
    };
    for entry in entries.flatten() {
        // Only croft's own staging names, so a file dropped in this directory
        // by anything else is left alone rather than deleted on a guess.
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        if !name.starts_with("stdin-") && !name.starts_with(crate::view_ipc::HELD_PREFIX) {
            continue;
        }
        // A file a LIVE croft is showing is never swept, whatever its age.
        // `apply_view_request` stamps its own pid in at open time, which is
        // the one moment a live holder is known; the name a client staged
        // carries a pid that is dead by construction, which is why age was
        // the only signal here before. Signal 0 checks existence and
        // permission without delivering anything, and ESRCH is the only
        // answer that means gone, exactly as the socket sweep judges it.
        if let Some(holder) = crate::view_ipc::holder_of_staged(name) {
            let alive = holder == std::process::id()
                || unsafe { libc::kill(holder as libc::pid_t, 0) } == 0
                || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH);
            if alive {
                continue;
            }
        }
        // Age still bounds the pile, but now it only ever reaches files no
        // live croft holds: a client that staged bytes nobody opened, and a
        // holder that has since exited.
        let too_old = entry
            .metadata()
            .and_then(|m| m.modified())
            .and_then(|t| t.elapsed().map_err(std::io::Error::other))
            .is_ok_and(|age| age > STAGED_STDIN_RETENTION);
        if too_old {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// How long an ssh-pane offer stays up untouched (#364) before it clears
/// itself: long enough to read and act on, short enough not to be stale
/// when the user next looks at the status bar.
const SSH_OFFER_TTL: std::time::Duration = std::time::Duration::from_secs(90);

pub(crate) fn croft_cache_dir() -> PathBuf {
    #[cfg(test)]
    if let Some(dir) = CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap().clone() {
        return dir;
    }
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    home.join(".cache").join("croft")
}

/// The per-process self-install log: two drift-armed croft instances on one
/// machine must not overwrite each other's build diagnostics (#245).
fn self_install_log_path() -> PathBuf {
    croft_cache_dir().join(format!("self-install-{}.log", std::process::id()))
}

/// The staged release build's log (#333): its own file, since a drift
/// rebuild may run in the same process and must not overwrite it.
fn staged_install_log_path() -> PathBuf {
    croft_cache_dir().join(format!("staged-install-{}.log", std::process::id()))
}

/// Resolve the binary to re-exec into after an update. A local self-install
/// re-execs the exact path cargo reported writing (which honors an
/// `install.root` from cargo config that env resolution can't see), falling
/// back to cargo's env-level root (`CARGO_INSTALL_ROOT` / `CARGO_HOME` /
/// `~/.cargo`); the remote installer always rsyncs to the literal
/// `~/.cargo/bin/croft`. Either way the fresh file is preferred over
/// `current_exe`, which may resolve to the now-replaced inode.
fn reexec_binary_path(local_install: Option<&crate::update_watch::SelfInstall>) -> PathBuf {
    let installed = if let Some(install) = local_install {
        install
            .installed_path()
            .or_else(crate::update_watch::cargo_install_bin)
    } else {
        std::env::var_os("HOME")
            .map(|home| PathBuf::from(home).join(".cargo").join("bin").join("croft"))
    };
    if let Some(p) = installed
        && p.exists()
    {
        return p;
    }
    std::env::current_exe().unwrap_or_else(|_| PathBuf::from("croft"))
}

fn sidebar_view_label(view: SidebarView) -> &'static str {
    match view {
        SidebarView::Explorer => "Explorer",
        SidebarView::Search => "Search",
        SidebarView::SourceControl => "SourceControl",
        SidebarView::Remote => "Remote",
        SidebarView::RunDebug => "RunDebug",
        SidebarView::Extensions => "Extensions",
        SidebarView::Testing => "Testing",
    }
}

fn sidebar_view_from_label(label: &str) -> Option<SidebarView> {
    match label {
        "Explorer" => Some(SidebarView::Explorer),
        "Search" => Some(SidebarView::Search),
        "SourceControl" => Some(SidebarView::SourceControl),
        "Remote" => Some(SidebarView::Remote),
        "RunDebug" => Some(SidebarView::RunDebug),
        "Extensions" => Some(SidebarView::Extensions),
        "Testing" => Some(SidebarView::Testing),
        _ => None,
    }
}

/// Collect the bundled and user-installed extension manifests, project them to
/// the panel's row list, and stamp each with its enabled state from `disabled`.
/// The bundled set ships in the binary; user extensions are read fresh from
/// `~/.config/croft/extensions/` each call so a newly dropped-in extension shows
/// up without a relaunch.
fn build_extension_items(
    disabled: &std::collections::BTreeSet<String>,
    vscode: &[crate::vscode_extensions::Comparison],
) -> Vec<crate::widgets::extensions::ExtensionItem> {
    use crate::lsp::manifest;
    let user = manifest::read_extension_sources(&manifest::user_extensions_dir());
    let mut sources: Vec<&str> = manifest::BUNDLED_MANIFESTS.to_vec();
    sources.extend(user.iter().map(String::as_str));
    let summaries = manifest::summaries(&sources);
    let mut items = crate::widgets::extensions::items_from_summaries(summaries, disabled);
    // Flag installed catalog entries as removable: croft wrote their manifest
    // (so uninstall is reversible), while a hand-dropped user manifest is the
    // user's own file and is never deleted. Drives the per-row trash button.
    for it in &mut items {
        it.removable = !it.builtin && !it.available && crate::mcp::catalog::is_removable(&it.id);
    }
    // Append the curated MCP catalog's not-yet-installed entries under AVAILABLE.
    items.extend(crate::widgets::extensions::items_from_available(
        crate::mcp::catalog::available(),
    ));
    // And what VS Code has that croft covers, or does not (#352).
    items.extend(crate::widgets::extensions::items_from_vscode(vscode));
    items
}

/// Resolve the program to spawn for a sidecar server: PATH-first / pinned
/// managed install (reusing the LSP provisioning), or `None`+kick the install
/// when not yet present. Returns the command plus extra PATH dirs it needs.
fn resolve_mcp_program(
    server: &crate::mcp::registry::ServerSpawn,
) -> Result<(String, Vec<PathBuf>), String> {
    let Some(provision) = &server.provision else {
        // PATH-only server (no croft-managed provisioning declared).
        return Ok((server.command.clone(), Vec::new()));
    };
    if let Some(found) = crate::lsp::install::provisioned_command(&server.id, provision) {
        return Ok(found);
    }
    // Not installed: kick the one-shot managed install (leaking the id to
    // 'static once, only on this first-install path — `resolve_managed` keys its
    // install-started gate on it), and ask the user to retry once it lands.
    let name: &'static str = Box::leak(server.id.clone().into_boxed_str());
    let config = crate::lsp::config::ServerConfig {
        name,
        command: server.command.clone(),
        args: server.args.clone(),
        language: crate::lsp::config::Language("mcp"),
        initialization_options: None,
        provision: Some(provision.clone()),
    };
    crate::lsp::install::resolve_managed(&config, provision, true);
    // First run: the managed install runs in the background. Block here (on the
    // worker thread — the UI stays responsive) until it lands, then resolve, so a
    // single invocation installs AND runs the command instead of erroring with
    // "run again" and dropping the user's argument. spawn_mcp_command shows a
    // first-run status meanwhile.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);
    loop {
        std::thread::sleep(std::time::Duration::from_millis(500));
        if let Some(found) = crate::lsp::install::provisioned_command(&server.id, provision) {
            return Ok(found);
        }
        if std::time::Instant::now() >= deadline {
            return Err(format!(
                "Installing {} timed out — check your network and try again",
                server.id
            ));
        }
    }
}

/// Run a resolved MCP command to completion on a worker thread: provision +
/// spawn the server, verify the tool definition (trust-on-first-use rug-pull
/// guard), call the tool, and return its text. Pure blocking; the caller sends
/// the [`crate::mcp::McpOutcome`] back over a channel.
fn run_mcp_command_blocking(
    resolved: &crate::mcp::registry::ResolvedCommand,
    arg: Option<String>,
    cwd: &Path,
    version: &str,
) -> crate::mcp::McpOutcome {
    use serde_json::json;
    let title = resolved.title.clone();
    let body = (|| -> Result<String, String> {
        let (program, extra_paths) = resolve_mcp_program(&resolved.server)?;
        // Least-privilege env: the declared vars plus a PATH (extra dirs first,
        // then the inherited PATH) so the launcher resolves its interpreter.
        let mut env = resolved.server.env.clone();
        let mut path_parts: Vec<String> = extra_paths
            .iter()
            .map(|p| p.display().to_string())
            .collect();
        if let Ok(sys) = std::env::var("PATH") {
            path_parts.push(sys);
        }
        env.insert("PATH".to_string(), path_parts.join(":"));

        let client = crate::mcp::client::McpClient::connect(
            &program,
            &resolved.server.args,
            cwd,
            &env,
            "croft",
            version,
        )
        .map_err(|e| e.to_string())?;

        // Trust-on-first-use: fingerprint the tool definition and refuse if it
        // changed since the user first ran this command (rug-pull / MCPoison).
        let list = client
            .call("tools/list", json!({}))
            .map_err(|e| e.to_string())?;
        // Validate the declared tool is actually advertised before calling it.
        let tools = crate::mcp::client::parse_tools(&list);
        if !tools.iter().any(|t| t.name == resolved.tool) {
            return Err(format!(
                "the server does not advertise a '{}' tool",
                resolved.tool
            ));
        }
        let fingerprint = crate::mcp::client::tool_fingerprint(&list, &resolved.tool);
        let prefs = crate::prefs::Prefs::load_or_default();
        match prefs.mcp_tool_fingerprints.get(&resolved.command_id) {
            Some(prev) if prev != &fingerprint => {
                return Err(format!(
                    "refusing to run: the '{}' tool definition changed since you approved it (possible rug-pull); toggle the extension off and on to re-approve",
                    resolved.tool
                ));
            }
            Some(_) => {}
            None => {
                let _ = crate::prefs::save_mcp_tool_fingerprint(&resolved.command_id, &fingerprint);
            }
        }

        let arguments = match (resolved.arg.as_ref(), arg) {
            (Some(name), Some(value)) => json!({ name.as_str(): value }),
            _ => json!({}),
        };
        let result = client
            .call_tool(&resolved.tool, arguments)
            .map_err(|e| e.to_string())?;
        let text = crate::mcp::client::tool_result_text(&result);
        Ok(if text.trim().is_empty() {
            String::from("(the tool returned no text content)")
        } else {
            text
        })
    })();
    crate::mcp::McpOutcome { title, body }
}

/// Paint the terminal pane's header buttons on its top border and return
/// their hit-test rectangles. Any of them is `None` when the pane is too
/// narrow or short for the label to fit, and the three that act on ONE pane
/// among several (`-`, `⛶`, `‹`) are absent when a lone terminal is open and
/// there is nothing to drop, maximize against, or fold away from.
///
/// Right to left: `+`, `∨`, `-`, `⛶`, `‹`. The collapse button (#313) went on
/// the far LEFT deliberately: every button already there keeps the exact
/// column it had, so a user reaching for `-` by position still lands on `-`
/// and not on a gesture that merely looks similar.
fn paint_terminal_pane_buttons(
    frame: &mut ratatui::Frame,
    area: Rect,
    show_close_button: bool,
    pane_maximized: bool,
    theme: crate::theme::Theme,
    pointer: Option<(u16, u16)>,
) -> TerminalPaneButtons {
    let add_w = TERMINAL_ADD_LABEL.chars().count() as u16;
    let caret_w = TERMINAL_PROFILE_LABEL.chars().count() as u16;
    let close_w = TERMINAL_CLOSE_LABEL.chars().count() as u16;
    let max_w = TERMINAL_MAX_LABEL.chars().count() as u16;
    let fold_w = TERMINAL_COLLAPSE_LABEL.chars().count() as u16;
    let mut out = TerminalPaneButtons::default();
    if area.height == 0 {
        return out;
    }
    let y = area.y;
    // Styling is the shared header-action look (see `header_pill::action_style`):
    // quiet teal icons under Black with a teal hover pill, navy chips under
    // Croft Dark. The Explorer `⋯` button draws from the same source of truth.
    let style_at = |x: u16, w: u16| -> Style {
        let hovered = pointer.is_some_and(|(px, py)| py == y && px >= x && px < x + w);
        crate::widgets::header_pill::action_style(theme, hovered)
    };
    // Right to left: [+] at the edge, the profile caret just left of it, then
    // [-]. The caret mirrors VS Code's `∨` next to `+`.
    if area.width >= add_w + 2 {
        let x = area.x + area.width - add_w - 1;
        frame
            .buffer_mut()
            .set_string(x, y, TERMINAL_ADD_LABEL, style_at(x, add_w));
        out.add = Some(Rect {
            x,
            y,
            width: add_w,
            height: 1,
        });
    }
    if area.width >= add_w + caret_w + 2 {
        let x = area.x + area.width - add_w - caret_w - 1;
        frame
            .buffer_mut()
            .set_string(x, y, TERMINAL_PROFILE_LABEL, style_at(x, caret_w));
        out.profile = Some(Rect {
            x,
            y,
            width: caret_w,
            height: 1,
        });
    }
    if show_close_button && area.width >= add_w + caret_w + close_w + 2 {
        let x = area.x + area.width - add_w - caret_w - close_w - 1;
        frame
            .buffer_mut()
            .set_string(x, y, TERMINAL_CLOSE_LABEL, style_at(x, close_w));
        out.close = Some(Rect {
            x,
            y,
            width: close_w,
            height: 1,
        });
    }
    // The maximize / restore button sits left of `-` and shares its
    // visibility: with a single terminal there is nothing to maximize
    // against, just as there is nothing to close.
    if show_close_button && area.width >= add_w + caret_w + close_w + max_w + 2 {
        let x = area.x + area.width - add_w - caret_w - close_w - max_w - 1;
        let label = if pane_maximized {
            TERMINAL_RESTORE_LABEL
        } else {
            TERMINAL_MAX_LABEL
        };
        frame
            .buffer_mut()
            .set_string(x, y, label, style_at(x, max_w));
        out.max = Some(Rect {
            x,
            y,
            width: max_w,
            height: 1,
        });
    }
    // Collapse sits left of `⛶`, putting the two layout gestures beside each
    // other and leaving the destructive `-` where it was. Maximize already
    // owns the whole panel and ignores the collapse flags, so while it is on
    // the button would be a control that does nothing: it is not painted.
    if show_close_button
        && !pane_maximized
        && area.width >= add_w + caret_w + close_w + max_w + fold_w + 2
    {
        let x = area.x + area.width - add_w - caret_w - close_w - max_w - fold_w - 1;
        frame
            .buffer_mut()
            .set_string(x, y, TERMINAL_COLLAPSE_LABEL, style_at(x, fold_w));
        out.collapse = Some(Rect {
            x,
            y,
            width: fold_w,
            height: 1,
        });
    }
    out
}

/// Hit rects for one terminal pane's header buttons, as laid out by the most
/// recent render. Any may be `None` when the pane is too narrow.
#[derive(Default)]
struct TerminalPaneButtons {
    add: Option<Rect>,
    profile: Option<Rect>,
    close: Option<Rect>,
    max: Option<Rect>,
    collapse: Option<Rect>,
}

/// `app_cursor` is the pane's DECCKM state: cursor keys switch from the
/// normal CSI form (`\e[A`) to SS3 (`\eOA`), the form terminfo advertises —
/// apps that bind keys from terminfo (Python's REPL, less) only match SS3.
fn key_to_bytes(key: KeyEvent, app_cursor: bool) -> Vec<u8> {
    use KeyCode::*;
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let alt = key.modifiers.contains(KeyModifiers::ALT);
    let cursor =
        |app: &'static [u8], normal: &'static [u8]| if app_cursor { app } else { normal }.to_vec();
    match key.code {
        Enter => vec![b'\r'],
        Tab => vec![b'\t'],
        BackTab => b"\x1b[Z".to_vec(),
        Backspace => vec![0x7f],
        Esc => vec![0x1b],
        Up => cursor(b"\x1bOA", b"\x1b[A"),
        Down => cursor(b"\x1bOB", b"\x1b[B"),
        Right if alt => b"\x1bf".to_vec(),
        Left if alt => b"\x1bb".to_vec(),
        Right => cursor(b"\x1bOC", b"\x1b[C"),
        Left => cursor(b"\x1bOD", b"\x1b[D"),
        Home => cursor(b"\x1bOH", b"\x1b[H"),
        End => cursor(b"\x1bOF", b"\x1b[F"),
        PageUp => b"\x1b[5~".to_vec(),
        PageDown => b"\x1b[6~".to_vec(),
        Insert => b"\x1b[2~".to_vec(),
        Delete => b"\x1b[3~".to_vec(),
        F(n) => match n {
            1 => b"\x1bOP".to_vec(),
            2 => b"\x1bOQ".to_vec(),
            3 => b"\x1bOR".to_vec(),
            4 => b"\x1bOS".to_vec(),
            5 => b"\x1b[15~".to_vec(),
            6 => b"\x1b[17~".to_vec(),
            7 => b"\x1b[18~".to_vec(),
            8 => b"\x1b[19~".to_vec(),
            9 => b"\x1b[20~".to_vec(),
            10 => b"\x1b[21~".to_vec(),
            11 => b"\x1b[23~".to_vec(),
            12 => b"\x1b[24~".to_vec(),
            _ => Vec::new(),
        },
        Char(c) => {
            if ctrl {
                let lc = c.to_ascii_lowercase();
                if lc.is_ascii_lowercase() {
                    return vec![(lc as u8) - b'a' + 1];
                }
                match c {
                    '@' => vec![0x00],
                    '\\' => vec![0x1c],
                    ']' => vec![0x1d],
                    _ => Vec::new(),
                }
            } else if alt {
                let mut v = vec![0x1b];
                let mut buf = [0u8; 4];
                v.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
                v
            } else {
                let mut buf = [0u8; 4];
                c.encode_utf8(&mut buf).as_bytes().to_vec()
            }
        }
        _ => Vec::new(),
    }
}

/// Divider drawn between the diagnostic block and the language hover content,
/// mirroring the horizontal rule VS Code renders between hover sections.
const HOVER_DIVIDER: &str = "────────";

/// Render the diagnostics under the hovered point into a single labelled text
/// block, errors first (so the most severe message leads), each line prefixed
/// with its severity. `None` when there are no diagnostics. The severity word
/// answers the user's "what type of error is it" directly, since a TUI can't
/// show VS Code's coloured marker icon.
fn format_diagnostics(
    diags: &[(crate::lsp::manager::DiagnosticSeverity, String)],
) -> Option<String> {
    use crate::lsp::manager::DiagnosticSeverity;
    if diags.is_empty() {
        return None;
    }
    let rank = |s: &DiagnosticSeverity| match s {
        DiagnosticSeverity::Error => 0,
        DiagnosticSeverity::Warning => 1,
        DiagnosticSeverity::Information => 2,
        DiagnosticSeverity::Hint => 3,
    };
    let label = |s: &DiagnosticSeverity| match s {
        DiagnosticSeverity::Error => "Error",
        DiagnosticSeverity::Warning => "Warning",
        DiagnosticSeverity::Information => "Info",
        DiagnosticSeverity::Hint => "Hint",
    };
    let mut ordered: Vec<&(DiagnosticSeverity, String)> = diags.iter().collect();
    ordered.sort_by_key(|(s, _)| rank(s));
    Some(
        ordered
            .iter()
            .map(|(s, m)| format!("{}: {}", label(s), m))
            .collect::<Vec<_>>()
            .join("\n\n"),
    )
}

/// Stack the diagnostic block above the language hover content, divided by a
/// rule, matching VS Code (PR microsoft/vscode#166560 put marker hovers on
/// top). Either side may be absent; `None` when both are.
fn compose_hover(diagnostic: Option<&str>, hover: Option<&str>) -> Option<String> {
    match (diagnostic, hover) {
        (Some(d), Some(h)) => Some(format!("{d}\n{HOVER_DIVIDER}\n{h}")),
        (Some(d), None) => Some(d.to_string()),
        (None, Some(h)) => Some(h.to_string()),
        (None, None) => None,
    }
}

#[cfg(test)]
mod tests;

/// Stdout wrapper that tallies every byte ratatui flushes through the
/// backend. The main loop reads + resets the counter once per frame to
/// Action verb parsed from a participant-action row id (`grant:3` etc.).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ParticipantVerb {
    Grant,
    Revoke,
    Kick,
}

/// One participant's parked caret in a multiplayer session: where they were
/// when someone else took over typing (docs/MULTIPLAYER.md).
#[derive(Clone, Debug, PartialEq, Eq)]
struct SessionCaret {
    path: PathBuf,
    row: usize,
    col: usize,
}

/// How long a peer's caret keeps its name tag after it last moved (VS Code
/// Live Share shows the name while the cursor works, then collapses to the
/// bare colored cell).
const CARET_LABEL_FADE: std::time::Duration = std::time::Duration::from_secs(2);

/// The typing pause that arms a proactive navigator look: long enough that
/// mid-thought keystrokes never fire it, short enough to feel like a pair
/// partner glancing over (double the 1s auto-save delay).
const PROACTIVE_PAUSE: std::time::Duration = std::time::Duration::from_secs(2);

/// A collab peer's last-known caret: where it is, whose it is, and when it
/// last moved (the name tag shows while `last_moved` is inside
/// [`CARET_LABEL_FADE`]). Keyed by site id, which is per-file, so one peer
/// legitimately holds one entry per shared file.
struct CollabCaret {
    file: String,
    row: usize,
    col: usize,
    name: String,
    last_moved: std::time::Instant,
}

/// A live AI stream announced over the relay (`CollabMsg::StreamState`):
/// who is streaming, into which file, and the pilot's site id in that file
/// (keys the pilot's ghost caret for the gutter stop button's row).
struct CollabStreamInfo {
    file: String,
    name: String,
    site: u64,
}

/// The name this participant broadcasts on its carets: `CROFT_COLLAB_NAME`
/// when set, else the mux's user@host. Truncated here (and again at ingest
/// for remote names) so a tag can never paint a whole row.
fn collab_display_name() -> String {
    std::env::var("CROFT_COLLAB_NAME")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(crate::session_host::client_name)
        .chars()
        .take(24)
        .collect()
}

/// The stable color a participant's ghost caret wears, from a small palette
/// keyed by their id (also the join order, so the first guest is always
/// green, the second magenta, and so on).
fn participant_color(id: u64) -> Color {
    const PALETTE: [Color; 6] = [
        Color::Rgb(0x8c, 0xc2, 0x65), // green
        Color::Rgb(0xd6, 0x6b, 0xd0), // magenta
        Color::Rgb(0x56, 0xb6, 0xc2), // cyan
        Color::Rgb(0xe0, 0x9a, 0x4e), // amber
        Color::Rgb(0x9a, 0x86, 0xfd), // purple
        Color::Rgb(0xe0, 0x6c, 0x75), // red
    ];
    PALETTE[(id % PALETTE.len() as u64) as usize]
}

/// The color a collab caret paints in: the seated navigator's carets wear
/// its fixed identity accent (the same orange as its comment boxes) so the
/// AI's presence is unmistakable; humans keep the join-order palette.
/// Identity is the seat's site ids, never its display name — names are
/// neither unique nor length-stable (truncated to 24 chars at ingest).
fn collab_caret_color(navigator_sites: &[u64], site: u64) -> Color {
    if navigator_sites.contains(&site) {
        crate::widgets::editor::NAVIGATOR_ACCENT
    } else {
        participant_color(site)
    }
}

/// The workspace-relative key a file replicates under in a collab session
/// (docs/MULTIPLAYER.md, Phase D). None outside the workspace: only
/// workspace files are shared.
fn collab_file_key(root: &Path, path: &Path) -> Option<String> {
    path.strip_prefix(root)
        .ok()
        .map(|p| p.to_string_lossy().into_owned())
}

/// Parse a participants action-picker row id back into (verb, participant).
fn parse_participant_action(id: &str) -> Option<(ParticipantVerb, u64)> {
    let (verb, id) = id.split_once(':')?;
    let id = id.parse().ok()?;
    let verb = match verb {
        "grant" => ParticipantVerb::Grant,
        "revoke" => ParticipantVerb::Revoke,
        "kick" => ParticipantVerb::Kick,
        _ => return None,
    };
    Some((verb, id))
}

/// The roster row shown for one participant: name, window size, role.
fn participant_row(p: &crate::session_host::Participant) -> crate::widgets::list_picker::ListRow {
    let role = if p.control { "write" } else { "read-only" };
    let size = if p.cols > 0 && p.rows > 0 {
        format!("{}\u{d7}{}", p.cols, p.rows)
    } else {
        String::from("size unknown")
    };
    crate::widgets::list_picker::ListRow {
        id: p.id.to_string(),
        label: format!("{}  {}  ({})", p.name, size, role),
    }
}

/// surface the per-frame payload size in the F8 perf HUD.
struct CountingWriter {
    inner: Stdout,
    bytes: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}

impl std::io::Write for CountingWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let n = self.inner.write(buf)?;
        self.bytes
            .fetch_add(n, std::sync::atomic::Ordering::Relaxed);
        Ok(n)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

type CroftTerminal = Terminal<CrosstermBackend<CountingWriter>>;

pub fn run(
    root: PathBuf,
    restore_session: Option<PathBuf>,
    open_file: Option<PathBuf>,
    zen: bool,
    workspace_folders: Vec<PathBuf>,
) -> Result<()> {
    // zoxide is a hard dependency of the Cmd+Z jump popup. Probe for it
    // and install it in the background if missing, off the launch path so
    // the first frame is never blocked. Runs on every host croft starts
    // on — the local Mac and the remote Linux box both reach `run` — so
    // the dependency is satisfied identically on both (GOLDEN RULE).
    crate::zoxide::ensure_installed_in_background();
    // Termux ships no font with codicon glyphs, so the activity-bar glyph
    // fallback renders blank cells out of the box. Install the Meslo Nerd
    // Font Mono into ~/.termux/font.ttf in the background (no-op on every
    // other host, and when the user already has a font.ttf).
    crate::termux::ensure_codicon_font_in_background();
    // Build the tree-sitter highlight configurations on a background thread so
    // the first file open paints its syntax (keywords, strings, comments)
    // instantly without the per-tab query-compilation snap, yet the ~80ms of
    // query compilation never blocks the cold-start path before the first
    // frame. The configs land in a process-wide cache, so the UI thread reads
    // the finished build straight out of it on first open (or builds on demand
    // if the user opens a file before the prewarm finishes).
    std::thread::spawn(crate::highlight::prewarm_configs);
    let title = build_title(&root);
    let mut app = App::new(root.clone())?;
    // Resurrect this workspace's terminal panel from the last session
    // (pane layout, cwds, names, focus) before the first frame paints.
    app.restore_terminal_session();
    // A launch from a .code-workspace file (#163) defines the folder set
    // exactly; otherwise the automatic per-primary store restores.
    if workspace_folders.is_empty() {
        let restored_folders = app.restore_workspace_folders();
        if restored_folders > 0 {
            app.status = format!("Restored {restored_folders} workspace folder(s)");
        }
    } else {
        for folder in workspace_folders {
            app.add_workspace_folder(folder);
        }
    }
    // Restore the tabs / layout carried across a self-update re-exec, then
    // delete the handoff file so a later normal launch starts clean.
    if let Some(session_path) = restore_session.as_ref() {
        if let Ok(state) = crate::session_state::SessionState::load(session_path) {
            app.apply_session_state(&state);
        }
        let _ = std::fs::remove_file(session_path);
    }
    // `--zen`: hide the Explorer sidebar and terminal so the editor fills the
    // window. "Move/Copy into New Window" launches the new window this way so it
    // opens focused on just the handed-off file. Toggle back with Cmd+B / Cmd+J.
    if zen {
        app.show_tree = false;
        app.show_terminal = false;
    }
    // `croft <root> --open-file <path>`: open the handed-off file (used by the
    // new window that Move / Copy into New Window spawns).
    if let Some(file) = open_file.as_ref() {
        app.open_file_at_launch(file);
    }
    app.start_update_watch_if_remote();
    app.start_drift_probe_if_local();
    app.start_update_check_if_local();

    enable_raw_mode().context("enable raw mode")?;
    // Sixel has no env var, so when neither iTerm2 nor Kitty was detected from
    // the environment, probe the host with a DA1 query. This runs in raw mode
    // but before the alt-screen switch and long before the event loop's first
    // poll, so crossterm's (lazily-started) event reader can't swallow the
    // reply. A non-sixel terminal (e.g. Apple Terminal) answers DA1 without
    // attribute 4 and the probe returns instantly; init_graphics then promotes
    // the protocol to Sixel only when this is true.
    #[cfg(unix)]
    if app.inline_protocol == crate::iterm2_inline::InlineImageProtocol::None {
        app.sixel_supported = crate::iterm2_inline::probe_sixel_support();
    }
    let mut out = stdout();
    // Alt screen + mouse + bracketed paste + SteadyBar cursor (thin vertical
    // line, no hardware blink: the blink is done in software so it works even
    // when the host terminal's own "Blinking cursor" preference is off). The
    // shared takeover block keeps this list identical to the dtach-reattach
    // re-assert; add new modes in takeover_mode_seq, not here.
    {
        use std::io::Write;
        out.write_all(&takeover_mode_seq())
            .and_then(|()| out.flush())
            .context("enter alt screen")?;
    }
    // From here the tty is in raw mode + alt-screen + mouse + bracketed
    // paste. The normal teardown below restores all of it, but a panic
    // unwinds straight past it and would drop the user back to a shell
    // with mouse-tracking still on (stray `^[[<35;…M` on every mouse
    // move). Install a hook that restores the tty first, then chains to
    // the original so the panic message + backtrace still print.
    install_terminal_restore_panic_hook();
    // Best-effort: terminals that don't speak the kitty keyboard protocol just
    // ignore this; ones that do (iTerm2 >=3.5, Ghostty, kitty, WezTerm) start
    // delivering Cmd/Super as a real modifier so cmd+s reaches the app.
    let kbd_enhanced = execute!(
        out,
        PushKeyboardEnhancementFlags(keyboard_enhancement_flags())
    )
    .is_ok();
    {
        use std::io::Write;
        out.write_all(&set_title_seq(&title)).ok();
        // Force iTerm2's session bg to sRGB(EDITOR_BG_RGB). Combined with
        // `Color::Reset` on welcome-pane cells and the same sRGB hex baked
        // into the OSC-1337 PNG canvas, both surfaces flow through iTerm2's
        // sRGB → display path and the welcome image bg matches the
        // surrounding pane bg pixel-for-pixel
        // (https://gitlab.com/gnachman/iterm2/-/issues/12529).
        let theme = crate::prefs::Prefs::load_or_default().theme();
        out.write_all(host_colors_seq(theme).as_bytes()).ok();
        if crate::iterm2_inline::detect_iterm2_inline_support() {
            out.write_all(set_session_bg_srgb_seq(theme.editor_bg_rgb()).as_bytes())
                .ok();
        }
        out.flush().ok();
    }
    // Env-var-only iTerm2 detection: no stdin queries, so this can't
    // contend with the crossterm event reader.
    app.init_graphics();
    // With the inline-image protocol fully resolved (env detection + the sixel
    // DA1 probe above), decide whether to nudge the user toward a terminal that
    // can render croft's icons and images. Runs identically on the local Mac
    // and the remote Linux box (GOLDEN RULE): both reach `run`, and `croft
    // remote` forwards the local terminal's identity so an SSH session from
    // iTerm2/Ghostty is never falsely warned.
    app.arm_terminal_warning();

    // Wrap stdout so we can count exactly how many bytes ratatui's diff
    // ships per frame — over SSH that byte count, alongside the per-frame
    // render time, is the signal that tells a fat repaint from a slow
    // remote CPU. Toggled on screen with F8.
    let perf_bytes = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    app.perf.attach_counter(perf_bytes.clone());
    let backend = CrosstermBackend::new(CountingWriter {
        inner: out,
        bytes: perf_bytes,
    });
    let mut terminal: CroftTerminal = Terminal::new(backend).context("create terminal")?;

    let result = main_loop(&mut app, &mut terminal);

    // Snapshot the terminal panel for the next launch (cwds are read live
    // here, so plain `cd`s during the session are captured at quit).
    app.save_terminal_session();

    disable_raw_mode().ok();
    {
        use std::io::Write;
        let mut out = stdout();
        out.write_all(&set_title_seq("")).ok();
        // Revert the host terminal's default colors (OSC 110/111, plus the
        // iTerm2 sRGB override where present) so the user's shell after
        // croft exits doesn't keep our forced theme colours.
        out.write_all(reset_host_colors_seq().as_bytes()).ok();
        if crate::iterm2_inline::detect_iterm2_inline_support() {
            out.write_all(reset_session_bg_seq().as_bytes()).ok();
        }
        out.flush().ok();
    }
    if kbd_enhanced {
        execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags).ok();
    }
    execute!(
        terminal.backend_mut(),
        crossterm::cursor::SetCursorStyle::DefaultUserShape,
        LeaveAlternateScreen,
        DisableMouseCapture,
        DisableBracketedPaste,
    )
    .ok();
    terminal.show_cursor().ok();

    // Reap the navigator's claude child before any exit: drop-to-local
    // (process::exit) and self-update (exec) below both bypass Drop, and even
    // a normal return races the detached Drop thread against process exit.
    // shutdown_blocking reverts, hangs up, and grace-kills synchronously.
    if let Some(host) = app.pair_host.take() {
        host.shutdown_blocking();
    }
    // And every teardown a recent unseat DETACHED (toggle off, record
    // disabled, pilot death): those threads race process exit, and a thread
    // that dies mid-grace-kill leaves the claude child running.
    crate::pair_host::join_teardowns();

    result?;
    if app.drop_to_local {
        std::process::exit(crate::remote::DROP_TO_LOCAL_EXIT_CODE);
    }
    // A background self-update landed: serialize the session and replace
    // this process image with the freshly-installed binary. The unix
    // process-image swap keeps the same controlling tty (the ssh PTY), so
    // there is no reconnect - the user sees a redraw, not a dropped
    // session. No shell is involved; args are passed as an argv vector.
    if app.pending_reexec {
        let state = app.capture_session_state();
        let session_path = crate::session_state::handoff_path();
        let _ = state.save(&session_path);
        use std::os::unix::process::CommandExt;
        // A staged release (#333) is swapped over the installed binary
        // only now, on the user's Relaunch: until this line PATH still
        // held the old version.
        let target = reexec_binary_path(app.self_install.as_ref());
        if let Some(staged) = app.staged_update_binary()
            && let Err(err) = crate::update_check::apply_staged(&staged, &target)
        {
            // The installed binary is untouched (copy-beside + rename), so
            // relaunching it is still right: the editor must never simply
            // exit because an update could not be applied.
            eprintln!(
                "croft update failed: could not replace {} with {}: {err} - relaunching the current version",
                target.display(),
                staged.display()
            );
        }
        let mut cmd = std::process::Command::new(target);
        cmd.arg(app.workspace_root())
            .arg("--restore-session")
            .arg(&session_path);
        let err = CommandExt::exec(&mut cmd);
        eprintln!("croft self-relaunch failed: {err}");
        return Ok(());
    }
    if let Some(remote) = app.remote_launch.take() {
        app.fs_watch.disable();
        let launch_result = if let Some(adopted) = remote.adopted {
            crate::remote::launch_only(adopted, remote.path.as_deref())
        } else {
            crate::remote::launch_croft_with(&remote.host, remote.path.as_deref(), None, false)
        };
        restore_host_terminal_state();
        match launch_result? {
            crate::remote::RemoteOutcome::ReturnToLocal => {
                return run(root, None, None, false, Vec::new());
            }
            crate::remote::RemoteOutcome::Exited => return Ok(()),
        }
    }
    Ok(())
}

/// Re-send the terminal-restore escape sequences after a remote ssh
/// session ends. The remote croft enables alt-screen, mouse tracking,
/// and bracketed paste on the local tty; if it crashed or exited
/// abnormally those modes can leak back into the user's shell. Re-
/// emitting the disable sequences here ensures the host shell is
/// always returned to a clean state.
fn restore_host_terminal_state() {
    use std::io::Write;
    let mut out = stdout();
    let _ = out.write_all(TERMINAL_RESTORE_SEQ);
    let _ = out.flush();
}

// Disable every mouse-tracking mode crossterm knows about (1000/1002/1003
// normal+button+any-motion, 1015/1006 urxvt+SGR encodings), bracketed
// paste (2004), exit any leftover alt-screen (1049l), reset the cursor
// style, and reset the host's default fg/bg (OSC 110/111, undoing the
// theme's dynamic colors). Written as raw bytes because the callers that
// need it (the panic hook, the post-remote-ssh restore) no longer hold a
// crossterm Backend handle for `execute!`. Both callers are done with the
// tty (a return from remote re-enters `run`, which re-applies the theme's
// host colors), so the color reset can't strand a live session.
const TERMINAL_RESTORE_SEQ: &[u8] =
    b"\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1015l\x1b[?2004l\x1b[?1049l\x1b[ q\x1b]110\x07\x1b]111\x07";

fn install_terminal_restore_panic_hook() {
    static HOOK: std::sync::Once = std::sync::Once::new();
    HOOK.call_once(|| {
        let original = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            use std::io::Write;
            // Persist the panic BEFORE touching the terminal: the TUI teardown
            // can garble or scroll away the message printed to stderr, so a file
            // is the only reliable record (read with `cat ~/.cache/croft/panic.log`).
            log_panic_to_file(info);
            let _ = disable_raw_mode();
            let mut out = stdout();
            let _ = out.write_all(TERMINAL_RESTORE_SEQ);
            let _ = out.write_all(b"\x1b[?25h");
            let _ = out.flush();
            original(info);
        }));
    });
}

/// Append a panic record (version, thread, location, message, backtrace) to
/// `~/.cache/croft/panic.log`. Best-effort and silent on any I/O failure.
fn log_panic_to_file(info: &std::panic::PanicHookInfo<'_>) {
    use std::io::Write;
    let Some(home) = std::env::var_os("HOME") else {
        return;
    };
    let dir = std::path::PathBuf::from(home).join(".cache").join("croft");
    let _ = std::fs::create_dir_all(&dir);
    let Ok(mut f) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(dir.join("panic.log"))
    else {
        return;
    };
    let payload = info.payload();
    let message = payload
        .downcast_ref::<&str>()
        .map(|s| s.to_string())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| String::from("<non-string panic payload>"));
    let location = info
        .location()
        .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
        .unwrap_or_else(|| String::from("<unknown>"));
    let thread = std::thread::current()
        .name()
        .unwrap_or("<unnamed>")
        .to_string();
    let backtrace = std::backtrace::Backtrace::force_capture();
    let _ = writeln!(
        f,
        "=== croft {} panicked ===\nthread: {thread}\nlocation: {location}\nmessage: {message}\nbacktrace:\n{backtrace}\n",
        env!("CARGO_PKG_VERSION"),
    );
}

/// Suspend the alt-screen, run every queued scp upload with the host
/// shell's stdin / stdout / stderr inherited (so the user sees scp's
/// progress and can answer any prompt it raises), then prompt for Enter
/// and restore the alt-screen. The local source is removed only on a
/// successful upload — if scp fails, the local copy stays put so the
/// user can retry without losing data.
fn run_pending_scp_uploads(app: &mut App, terminal: &mut CroftTerminal) -> Result<()> {
    use std::io::Write;
    let uploads = app.take_pending_scp_uploads();
    if uploads.is_empty() {
        return Ok(());
    }
    // Tear down the TUI surface so scp can use the real terminal.
    disable_raw_mode().ok();
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture,
        DisableBracketedPaste,
        crossterm::cursor::SetCursorStyle::DefaultUserShape,
    )
    .ok();
    terminal.show_cursor().ok();

    let total = uploads.len();
    let mut moved = 0usize;
    let mut error_count = 0usize;
    let mut affected_dirs: Vec<PathBuf> = Vec::new();
    {
        let mut out = stdout();
        let _ = writeln!(out);
        let _ = writeln!(out, "── croft: uploading {total} item(s) via scp ──");
        let _ = writeln!(
            out,
            "(scp prompts for password / passphrase / host-key will appear below)"
        );
        let _ = writeln!(out);
        let _ = out.flush();
    }
    for (i, upload) in uploads.iter().enumerate() {
        if let Some(parent) = upload.src.parent() {
            affected_dirs.push(parent.to_path_buf());
        }
        {
            let mut out = stdout();
            let _ = writeln!(
                out,
                "[{}/{}] scp -r {} {}:",
                i + 1,
                total,
                upload.src.display(),
                upload.alias,
            );
            let _ = out.flush();
        }
        if !upload.src.exists() {
            eprintln!("  ! source no longer exists, skipping");
            error_count += 1;
            continue;
        }
        let dest = format!("{}:", upload.alias);
        let status = std::process::Command::new("scp")
            .arg("-r")
            .arg(&upload.src)
            .arg(&dest)
            .status();
        match status {
            Ok(s) if s.success() => {
                moved += 1;
            }
            Ok(s) => {
                eprintln!("  ! scp exited with {s}; local source preserved");
                error_count += 1;
            }
            Err(e) => {
                eprintln!("  ! could not spawn scp: {e}");
                error_count += 1;
            }
        }
    }
    {
        let mut out = stdout();
        let _ = writeln!(out);
        let _ = writeln!(
            out,
            "── done: {moved}/{total} uploaded, {error_count} error(s) ──"
        );
        let _ = write!(out, "Press Enter to return to croft ");
        let _ = out.flush();
    }
    let mut line = String::new();
    let _ = std::io::stdin().read_line(&mut line);

    // Restore the TUI via the shared takeover block (same modes as startup
    // and the dtach-reattach re-assert).
    enable_raw_mode().ok();
    {
        use std::io::Write;
        let out = terminal.backend_mut();
        let _ = out.write_all(&takeover_mode_seq());
        let _ = out.flush();
    }
    terminal.clear().ok();
    app.overlays.activity.mark_dirty();
    app.overlays.welcome.mark_dirty();
    app.report_scp_results(moved, total, error_count, &affected_dirs);
    Ok(())
}

/// Consume every overlay's one-shot image-clear latch; true when any fired.
/// Shared by the pre-draw and post-draw eviction checks in [`main_loop`].
fn consume_any_image_clear(app: &mut App) -> bool {
    let fired = [
        app.consume_welcome_image_clear(),
        app.consume_editor_image_clear(),
        app.consume_terminal_image_clear(),
        app.consume_markdown_image_clear(),
        app.consume_run_debug_image_clear(),
        app.consume_problems_badge_image_clear(),
        app.consume_no_repo_hero_image_clear(),
        app.consume_shortcuts_image_clear(),
        app.consume_file_finder_image_clear(),
        app.consume_command_palette_image_clear(),
        app.consume_process_picker_image_clear(),
        app.consume_zoxide_jump_image_clear(),
        app.consume_branch_picker_image_clear(),
        app.consume_input_prompt_image_clear(),
        app.consume_list_picker_image_clear(),
        app.consume_ssh_empty_state_image_clear(),
        app.consume_minimap_image_clear(),
        app.consume_activity_image_clear(),
    ];
    fired.into_iter().any(|f| f)
}

fn main_loop(app: &mut App, terminal: &mut CroftTerminal) -> Result<()> {
    // Force the very first frame to render so the user sees the UI even
    // before the first event arrives or any timer fires.
    let mut needs_redraw = true;
    let mut last_blink_visible = app.cursor_visible_phase();
    // Advances every UPDATE_SPINNER_FRAME_MS while a background update runs;
    // forces a status-bar redraw so the spinner animates. Constant otherwise.
    let mut last_spinner_phase = app.update_spinner_phase();
    // Frame-rate accounting for the F8 HUD: count draws over a rolling 1s
    // window so a high idle FPS (always-dirty redraw loop saturating the
    // SSH link) is visible at a glance.
    let mut fps_window_start = std::time::Instant::now();
    let mut frames_in_window: u32 = 0;
    let mut keys_in_window: u32 = 0;
    let mut iters_in_window: u32 = 0;
    let mut work_max_us: u128 = 0;
    let mut poll_max_us: u128 = 0;
    // PTY-only redraws are capped so a chatty embedded shell (Claude Code,
    // npm install, log streams) cannot saturate stdout and starve mouse /
    // key events on the same thread. Input + FS + search + git + remote
    // signals always bypass the cap, so clicks and keystrokes stay at 0ms.
    // Over SSH the user's link is the bottleneck, so we drop further to
    // ~20 Hz; locally ~30 Hz is plenty for shell text.
    let pty_min_interval = if is_remote_session() {
        Duration::from_millis(50)
    } else {
        Duration::from_millis(33)
    };
    // A keystroke echo, a shell line-rewrite, or an input-box update
    // advances only a handful of bytes into the grid; a bulk stream (cat,
    // build logs, a full-pane scroll, a TUI's streaming output) advances
    // many. We let small updates redraw immediately so echo feels native
    // even when croft itself is the remote end of an SSH link, and keep
    // the cap on large updates so a flood can't saturate the pipe and
    // starve input. A full-pane repaint runs tens of KB; interactive
    // echo stays well under this, so the two never alias.
    const PTY_SMALL_UPDATE_BYTES: usize = 4096;
    let mut last_pty_redraw = std::time::Instant::now()
        .checked_sub(pty_min_interval)
        .unwrap_or_else(std::time::Instant::now);

    while !app.quit {
        iters_in_window += 1;
        if fps_window_start.elapsed() >= Duration::from_secs(1) {
            app.perf.record_window(
                frames_in_window,
                keys_in_window,
                iters_in_window,
                work_max_us,
                poll_max_us,
            );
            frames_in_window = 0;
            keys_in_window = 0;
            iters_in_window = 0;
            work_max_us = 0;
            poll_max_us = 0;
            fps_window_start = std::time::Instant::now();
        }
        let iter_start = std::time::Instant::now();
        // If the user dropped files onto the Remote Explorer, suspend the
        // alt-screen and run scp in the host shell so the user sees its
        // progress, can answer password / FIDO / known_hosts prompts,
        // and gets explicit success / failure output before we resume.
        if !app.pending_scp_uploads.is_empty() {
            run_pending_scp_uploads(app, terminal)?;
            needs_redraw = true;
        }
        // Pull in any filesystem-watcher events first so the tree reflects
        // disk reality on the very next frame.
        let fs_changed = app.drain_fs_events();
        // Peek without clearing so we can coalesce PTY-only redraws without
        // losing bytes that the reader thread has already advanced into the
        // terminal grid.
        let pty_pending = app.peek_terminals_dirty();
        let blink_visible = app.cursor_visible_phase();
        let blink_changed = blink_visible != last_blink_visible;
        // Either spinner advancing must wake a redraw; both stay 0 when idle.
        let spinner_phase =
            app.update_spinner_phase() + app.mcp_spinner_phase() + app.problems_fix_spinner_phase();
        let spinner_changed = spinner_phase != last_spinner_phase;
        let ext_index_changed = app.drain_ext_index_refresh();
        let search_changed = app.drain_search_results();
        let log_index_changed = app.poll_log_index();
        let remote_changed = app.refresh_remote_if_config_changed();
        let pulls_changed = app.drain_remote_pulls();
        let view_changed = app.drain_view_requests();
        let ports_changed = app.drain_ports_and_poll();
        let session_presence_changed = app.poll_session_presence();
        let session_typing_changed = app.poll_session_typing();
        let collab_changed = app.poll_collab();
        let bells_changed = app.drain_terminal_bells();
        // A block whose command has finished gets its output box (#354).
        let captures_changed = app.settle_block_captures();
        // Every tick, not only when a capture settles: this is what notices
        // the editor has moved to another document (#354 review).
        app.publish_block_outputs();
        let labels_changed =
            app.refresh_terminal_labels() | app.drain_agent_events() | app.drain_fleet_results();
        app.flush_terminal_session();
        let auto_save_changed = app.tick_auto_save();
        let connect_changed = app.poll_connect_dialog();
        let install_changed = app.poll_install_session();
        let update_changed = app.poll_update_watch();
        let http_changed = app.drain_http_responses();
        let reveal_changed = app.tick_redaction_reveal();
        app.sync_lsp();
        app.sync_git_gutters();
        app.sync_blame();
        app.sync_provenance();
        let blame_changed = app.drain_blame();
        // Request/refresh the OUTLINE for the active file (after sync_lsp so the
        // edit-seq it reads is current) and advance follow-cursor.
        let outline_sync_changed = app.sync_outline();
        let outline_changed = app.drain_lsp_document_symbols();
        app.workspace_symbols_dispatch_due();
        let ws_symbols_changed = app.drain_lsp_workspace_symbols();
        // Refresh the Explorer's other stacked sub-views (Open Editors list,
        // Timeline git history, Dependencies) and drain their workers.
        let explorer_panels_changed = app.sync_explorer_panels();
        app.refresh_semantic_tokens_if_requested();
        app.refresh_inlay_hints_if_requested();
        app.refresh_workspace_diagnostics_if_requested();
        let lsp_changed = app.drain_lsp_completion();
        app.refresh_signature_help_if_moved();
        let sig_help_changed = app.drain_lsp_signature_help();
        app.poll_hover();
        let hover_changed = app.drain_lsp_hover();
        let tab_hover_changed = app.poll_tab_hover();
        let ui_tooltip_changed = app.poll_ui_tooltip();
        let definition_changed = app.drain_lsp_definition();
        let declaration_changed = app.drain_lsp_declaration();
        let type_definition_changed = app.drain_lsp_type_definition();
        let implementation_changed = app.drain_lsp_implementation();
        let references_changed = app.drain_lsp_references();
        let call_hierarchy_changed = app.drain_lsp_call_hierarchy();
        let sidebar_hide_changed = app.tick_sidebar_auto_hide();
        let occ_tick_changed = app.tick_occurrences();
        let linked_tick_changed = app.tick_linked_editing();
        let linked_changed = app.drain_lsp_linked_editing();
        app.tick_on_type_formatting();
        let on_type_changed = app.drain_lsp_on_type_format();
        let prepare_rename_changed = app.drain_lsp_prepare_rename();
        let occurrences_changed = app.drain_lsp_document_highlights();
        let rename_changed = app.drain_lsp_rename();
        let format_changed = app.drain_lsp_format();
        let code_action_changed = app.drain_lsp_code_actions();
        let semantic_changed = app.drain_lsp_semantic_tokens();
        let inlay_changed = app.drain_lsp_inlay_hints();
        app.drain_lsp_document_links();
        let folds_changed = app.drain_lsp_folding_ranges();
        let selection_ranges_changed = app.drain_lsp_selection_ranges();
        let colors_changed = app.drain_lsp_document_colors();
        let color_pres_changed = app.drain_lsp_color_presentations();
        let diagnostics_changed = app.drain_lsp_diagnostics();
        let progress_changed = app.drain_lsp_progress();
        let dap_changed = app.poll_dap();
        let tests_changed =
            app.test_worker.drain(&mut app.testing) | app.drain_pending_test_debug();
        // A queued run the worker refused (runner disabled after the entry
        // check) rolled its cases back in the drain; say why nothing ran.
        if app.testing.take_refusal() {
            app.status = String::from(crate::testing::NO_RUNNER_STATUS);
        }
        // One notification per red run (#358), from the latch the panel
        // sets when a run ends, never per test case.
        if app.testing.take_failed_run() {
            let (passed, failed, _) = app.testing.counts();
            app.notifier.emit(
                crate::notifications::Event::TestsFailed {
                    failed,
                    passed,
                    reported: app.testing.run_reported_failed(),
                },
                app.roots.primary(),
                &remote_host_label(),
            );
        }
        let mcp_changed = app.poll_mcp();
        let pair_changed =
            app.maybe_seat_navigator() | app.poll_pair() | app.tick_proactive_navigator();
        let voice_changed = app.drain_voice();
        // Surface managed language-server install progress in the status bar so
        // the background work (which can take a few seconds) is visible.
        let install_status_changed = match crate::lsp::install::take_status() {
            Some(msg) => {
                app.status = msg;
                true
            }
            None => false,
        };
        // When a managed install finishes, forget the LSP sync state for the
        // docs that language serves so the next `sync_lsp` re-opens them. That
        // re-open makes the manager re-probe and spawn the just-installed
        // server, so "installed" becomes "working" without a further action.
        let just_installed = crate::lsp::install::take_just_installed();
        if !just_installed.is_empty() {
            app.lsp_last_seen
                .retain(|path, _| !just_installed_covers_path(&just_installed, path));
        }

        let non_pty_dirty = needs_redraw
            || fs_changed
            || mcp_changed
            || pair_changed
            || tests_changed
            || blink_changed
            || spinner_changed
            || ext_index_changed
            || search_changed
            || log_index_changed
            || remote_changed
            || pulls_changed
            || view_changed
            || ports_changed
            || session_presence_changed
            || session_typing_changed
            || collab_changed
            || bells_changed
            || captures_changed
            || labels_changed
            || auto_save_changed
            || ws_symbols_changed
            || connect_changed
            || install_changed
            || update_changed
            || http_changed
            || reveal_changed
            || lsp_changed
            || sig_help_changed
            || hover_changed
            || tab_hover_changed
            || ui_tooltip_changed
            || definition_changed
            || declaration_changed
            || type_definition_changed
            || implementation_changed
            || references_changed
            || call_hierarchy_changed
            || sidebar_hide_changed
            || occ_tick_changed
            || linked_tick_changed
            || linked_changed
            || on_type_changed
            || prepare_rename_changed
            || occurrences_changed
            || rename_changed
            || format_changed
            || code_action_changed
            || semantic_changed
            || inlay_changed
            || folds_changed
            || selection_ranges_changed
            || colors_changed
            || color_pres_changed
            || diagnostics_changed
            || progress_changed
            || voice_changed
            || outline_sync_changed
            || outline_changed
            || explorer_panels_changed
            || install_status_changed
            || blame_changed
            || dap_changed;
        let pty_eligible = pty_pending
            && (app.peek_terminals_pending_bytes() <= PTY_SMALL_UPDATE_BYTES
                || last_pty_redraw.elapsed() >= pty_min_interval);
        let do_redraw = non_pty_dirty || pty_eligible;
        // Consume the PTY dirty flags only when we are actually redrawing.
        // Skipping a frame must leave them set so the next eligible tick
        // emits the deferred output.
        let pty_changed = if do_redraw {
            app.drain_terminals_dirty()
        } else {
            false
        };

        if do_redraw {
            if pty_changed {
                last_pty_redraw = std::time::Instant::now();
            }
            // If the welcome OSC-1337 image was painted earlier and the
            // user has just opened a file, wipe the screen so iTerm drops
            // its cached image cells AND ratatui repaints every cell on
            // the next draw (its diff alone misses cells whose content
            // didn't change between welcome and editor buffers).
            // A resize/WINCH is not image eviction: it invalidated the text on
            // screen (dtach reattach repaints into a blank terminal), so it
            // wipes unconditionally, Kitty included. It never fires while the
            // user merely types, so the blink fix below is untouched.
            let resize_repaint = app.consume_resize_repaint();
            if consume_any_image_clear(app) || resize_repaint {
                // iTerm2/sixel image cells live in the normal cell buffer, so
                // evicting them takes a full `2J` + repaint. Kitty images are
                // deleted on their own layer below - wiping the text there
                // blanks the whole app for an SSH round trip per latch (the
                // every-keystroke blink), so Kitty skips the screen clear.
                if resize_repaint || app.image_eviction_needs_screen_wipe() {
                    terminal.clear()?;
                }
                app.evict_inline_images_on_clear();
                // Activity-bar icons live outside ratatui too; re-emit
                // them on the next post-draw flush. The welcome wordmark
                // and the source-control hero also live in iTerm's image
                // cache that just got wiped - re-arm them so the next
                // render re-emits whichever one is currently visible.
                app.overlays.activity.mark_dirty();
                app.overlays.welcome.mark_dirty();
                app.overlays.hero.mark_dirty();
            }
            let draw_start = std::time::Instant::now();
            terminal.draw(|f| {
                app.render(f);
            })?;
            // Record render+flush time and the bytes ratatui shipped this
            // frame so the F8 HUD can show where remote latency goes.
            app.perf.record_draw(draw_start.elapsed().as_micros());
            frames_in_window += 1;
            if consume_any_image_clear(app) {
                if app.image_eviction_needs_screen_wipe() {
                    terminal.clear()?;
                }
                app.evict_inline_images_on_clear();
                app.overlays.activity.mark_dirty();
                app.overlays.welcome.mark_dirty();
                app.overlays.hero.mark_dirty();
                terminal.draw(|f| {
                    app.render(f);
                })?;
            }
            // After ratatui flushes its diff, paint the activity-bar icons
            // directly via OSC-1337 on every redraw. We previously gated
            // this on a `dirty` flag and only re-emitted on resize / view
            // change, but the icons would intermittently vanish: iTerm2
            // can drop cached OSC-1337 image cells under heavy SGR traffic
            // on adjacent cells (cursor-blink redraws, search updates,
            // mouse motion bursts) and the dirty gate had no way to detect
            // that. Since `render_activity_bar` writes nothing to the
            // buffer in image-mode, ratatui's diff produces zero per-cell
            // writes here — re-emitting the pre-encoded OSC bytes every
            // frame is cheap and locks the images in.
            app.flush_activity_image_overlays();
            // Active editor image preview: bake-once-emit-each-frame
            // overlay, just like the welcome wordmark. Sent after ratatui
            // has finished its diff so the image bytes land on cells
            // ratatui won't repaint until layout changes again. One slot
            // per editor split column (0 = left, 1 = right); when not
            // split only slot 0 ever has a payload.
            for side in 0..2 {
                if let Some((osc, layout)) = app.editor_image_payload(side)
                    && app.overlay_fits_on_screen(
                        layout.cell_x,
                        layout.cell_y,
                        layout.cell_w,
                        layout.cell_h,
                    )
                {
                    use std::io::Write;
                    let mut out = stdout();
                    let cursor_on = app.cursor_should_be_visible();
                    let _ = write!(out, "\x1b[?25l\x1b[s");
                    let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
                    let _ = out.write_all(osc.as_bytes());
                    let _ = write!(out, "\x1b[u");
                    if cursor_on {
                        let _ = write!(out, "\x1b[?25h");
                    }
                    let _ = out.flush();
                    app.mark_editor_image_displayed(side);
                }
            }
            // Terminal-pane inline image (captured imgcat output): same
            // bake-once / emit-each-frame overlay, anchored to its grid row.
            if let Some((osc, layout)) = app.terminal_image_payload()
                && app.overlay_fits_on_screen(
                    layout.cell_x,
                    layout.cell_y,
                    layout.cell_w,
                    layout.cell_h,
                )
            {
                use std::io::Write;
                let mut out = stdout();
                let cursor_on = app.cursor_should_be_visible();
                let _ = write!(out, "\x1b[?25l\x1b[s");
                let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
                let _ = out.write_all(osc.as_bytes());
                let _ = write!(out, "\x1b[u");
                if cursor_on {
                    let _ = write!(out, "\x1b[?25h");
                }
                let _ = out.flush();
                app.mark_terminal_image_displayed();
            }
            // Markdown-preview inline image (#176): same bake-once /
            // emit-each-frame overlay, anchored at its reserved rows.
            if let Some((osc, layout)) = app.markdown_image_payload()
                && app.overlay_fits_on_screen(
                    layout.cell_x,
                    layout.cell_y,
                    layout.cell_w,
                    layout.cell_h,
                )
            {
                use std::io::Write;
                let mut out = stdout();
                let cursor_on = app.cursor_should_be_visible();
                let _ = write!(out, "\x1b[?25l\x1b[s");
                let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
                let _ = out.write_all(osc.as_bytes());
                let _ = write!(out, "\x1b[u");
                if cursor_on {
                    let _ = write!(out, "\x1b[?25h");
                }
                let _ = out.flush();
                app.mark_markdown_image_displayed();
            }
            // Editor minimap: same bake-once / emit-each-frame overlay, painted
            // after ratatui's diff so the raster lands on the strip cells.
            if let Some((osc, layout)) = app.minimap_image_payload()
                && app.overlay_fits_on_screen(
                    layout.cell_x,
                    layout.cell_y,
                    layout.cell_w,
                    layout.cell_h,
                )
            {
                use std::io::Write;
                let mut out = stdout();
                let cursor_on = app.cursor_should_be_visible();
                let _ = write!(out, "\x1b[?25l\x1b[s");
                let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
                let _ = out.write_all(osc.as_bytes());
                let _ = write!(out, "\x1b[u");
                if cursor_on {
                    let _ = write!(out, "\x1b[?25h");
                }
                let _ = out.flush();
                app.mark_minimap_image_displayed();
            }
            // Run-and-Debug headline icon: same re-emit-every-frame trick.
            // Only fires while the sidebar is on the Run-Debug view and the
            // panel reserved a cell for the icon on its last render. On
            // view change the `consume_run_debug_image_clear` gate above
            // already armed `terminal.clear()`, evicting the cached
            // image cells before the next sidebar paints.
            app.flush_run_debug_icon_overlay();
            app.flush_problems_badge_overlay();
            app.flush_no_repo_hero_overlay();
            app.flush_ssh_empty_state_overlay();
            // Welcome-screen logo: same OSC-1337 trick, gated by its own
            // dirty flag and only emitted while the editor pane is in its
            // blank initial state.
            if let Some((img, layout)) = app.welcome_image_emit_payload()
                && app.overlay_fits_on_screen(
                    layout.cell_x,
                    layout.cell_y,
                    layout.cell_w,
                    layout.cell_h,
                )
            {
                use std::io::Write;
                let mut out = stdout();
                let cursor_on = app.cursor_should_be_visible();
                let _ = write!(out, "\x1b[?25l\x1b[s");
                let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
                let _ = out.write_all(img.as_bytes());
                let _ = write!(out, "\x1b[u");
                if cursor_on {
                    let _ = write!(out, "\x1b[?25h");
                }
                let _ = out.flush();
                app.mark_welcome_image_emitted();
            }
            // Last of all: re-paint the chrome tooltip on top of any sidebar
            // illustration it overlaps. Must run after every inline-image flush
            // above so the box wins those cells (last writer per cell wins).
            app.flush_tooltip_over_image();
            needs_redraw = false;
            last_blink_visible = blink_visible;
            last_spinner_phase = spinner_phase;
        }

        // 8 ms (~125 Hz) keeps echo lag tight when the embedded pty is the
        // hot path (remote-launched croft over SSH). Idle cost is still
        // negligible because the redraw branch above gates on dirty flags;
        // this poll just decides how often we wake up to *check*.
        work_max_us = work_max_us.max(iter_start.elapsed().as_micros());
        let poll_start = std::time::Instant::now();
        if event::poll(Duration::from_millis(8))? {
            // Drain every event already queued so a click burst (Down + zero-
            // movement Drag + Up, all delivered in <50ms by the terminal)
            // coalesces into a single redraw. Otherwise each event triggers
            // its own terminal.draw cycle, which Hides+Shows the hardware
            // caret each time and the user sees the cursor blink twice
            // rapidly before settling into the normal 530ms blink.
            loop {
                match event::read()? {
                    Event::Key(key) => {
                        if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat {
                            keys_in_window += 1;
                        }
                        app.handle_key(key)?;
                    }
                    Event::Mouse(m) => app.handle_mouse(m),
                    Event::Paste(s) => app.handle_paste(&s),
                    Event::Resize(_, _) => {
                        // Alt-screen reflow blanks the activity bar's SGR cells
                        // but iTerm2's OSC-1337 image layer survives, so a plain
                        // re-emit ghosts a fresh icon over the stale one. Re-mark
                        // dirty AND arm a one-shot terminal.clear() to evict it.
                        app.on_resize();
                        // Under dtach a reattach arrives as a bare WINCH into a
                        // terminal that never saw the startup DECSETs: without
                        // this re-assert the mouse (and bracketed paste, kitty
                        // keyboard flags, alt screen) stays dead until the next
                        // F9 reload happens to re-exec croft.
                        if std::env::var_os("CROFT_SESSION_PERSISTENT").is_some() {
                            use std::io::Write;
                            let out = terminal.backend_mut();
                            let _ = out.write_all(&mode_reassert_seq());
                            let _ = out.flush();
                        }
                    }
                    _ => {}
                }
                if !event::poll(Duration::ZERO)? {
                    break;
                }
            }
            needs_redraw = true;
        }
        poll_max_us = poll_max_us.max(poll_start.elapsed().as_micros());
        // Drive edge auto-scroll for an in-progress terminal drag-selection
        // even when the pointer is held still (no fresh events): the poll
        // above wakes us every 8 ms, and this advances the selection while
        // the pointer stays pinned past the pane edge.
        if app.tick_terminal_autoscroll() {
            needs_redraw = true;
        }
    }
    Ok(())
}